Ansible: Can I use vars_files when some files do not exist

That's the part:

vars_files:
  - vars/vars.default.yml
  - vars/vars.yml

If a file vars/vars.yml does not exist - here is an error.

ERROR: file could not read: /.../vars/vars.yml

How can I load additional variables from this file only if it exists? (with no errors)


It's quite simple really. You can squash your different vars_files items into a single tuple and Ansible will automatically go through each one until it finds a file that exists and load it. E.x.:

vars_files:
  - [ "vars/foo.yml", "vars/bar.yml", "vars/default.yml" ]

According to Ansible developers, the proper way to solve this is to use something like:

vars_files_locs: ['../path/to/file1', '../path/to/file2', ...]

- include_vars: "{{ item }}"
  with_first_found: vars_files_locs

Furthermore, they say:

The above will properly load only the first file found, and is more flexible than trying to do this via the vars_files language keyword.