I’d like to share some info on a new feature Benno Joy recently added to the devel branch.
In Ansible, you could already load in OS-based variables in a play based on facts like so:
- hosts: webservers
vars_files: - [ “{{ ansible_os_distribution }}”.yml, ‘defaults.yml’ ]
What does this do?
It loads variables from a YAML file based on the type of distribution (run ansible hostname -m setup to see the value of the distribution), and if not found, it uses a defaults file.
This is nice, but you couldn’t do this in roles, because the mechanism didn’t have a way to say when to pull in variable files.
Now, the new thing.
Inside roles/foo/tasks/main.yml, imagine:
- include_vars: “{{ ansible_os_distribution }}.yml”
That will look in
roles/foo/vars/.yml
Nice!
Basically you now have something like vars_files for roles, which was much requested for distribution type variables.
For example you can also do:
- include_vars: “{{ item }}.yml”
with_first_found:
- “{{ ansible_os_distribution}}.yml”
- default.yml
and this basically completely emulates vars_files, but can also be used in some new ways.
This could of course be used for any variable or fact, not just the OS distribution, but that’s a likely simple example.
You are allowed to use any kinds of iterators you want (for instance, you could do:)
- include_vars: “{{ item }}.yml”
with_fileglob: “…/vars/*.yml”
And easily load all YAML files in a given directory. Just an example – I don’t expect that will be frequent, but you can do it.
And it also works with conditionals:
- include_vars: foo.yml
when: x == 27
Basically this allows you to do everything like vars_files, but a bit more dynamically. You couldn’t do this with vars_files before either.
vars_files is not going away – this is included to provide some creative control to role authors to make their roles more flexible.