Istvan
Istvan

Reputation: 8572

Is there a way to abort execution when vars file is missing?

I would like to wrap the following with something that stops execution when the file is missing:

  vars_files:
    - "{{ customer }}.yml"

Not sure if there is something like that in Ansible (2.4).

Upvotes: 1

Views: 251

Answers (1)

techraf
techraf

Reputation: 68559

You don't need to do anything ― if the file is missing Ansible stops by default. Example:

ansible-playbook playbook.yml --extra-vars customer=non_existing_file

produces the following error and stops the execution:

ERROR! vars file {{ customer }}.yml was not found


I suspect your customer variable is not set in the scope to be used in vars_files declaration, so use include_vars module instead:

- hosts: all
  pre_tasks:
    - include_vars:
        file: "{{ customer }}.yml"

By default it produces an error if customer is undefined:

fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'customer' is undefined\n\nThe error appears to have been in '/Users/techraf/so48065296-is-there-a-way-to-abort-execution-when-vars-file-is-missing/playbook.yml': line 8, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n tasks:\n - include_vars:\n ^ here\n\nexception type: \nexception: 'customer' is undefined"}


If you are unhappy with the error message itself, you can prepend it with a task using assert or fail.

Upvotes: 1

Related Questions