I'd like to pass a variable to an included Ansible playbook as follows:
---
- hosts: localhost
connection: local
vars:
my_group: foo
- include: site.yml hosts={{ my_group }}
Then, in site.yml...
---
- hosts: "{{ hosts }}"
...
Unfortunately, I get an error saying that my_group is undefined in site.yml. Ansible docs do say that:
Note that you cannot do variable substitution when including one playbook inside another.
Is this my case? Is there a way around it?
You can use this syntax, but
my_grouphas to be defined at the global level. Now it's local to the first play - it's even clear from the indentation.You can confirm this by running your playbook with
--extra-vars my_group=foo.But generally what you seem to want to achieve is done using in-memory inventory files and
add_hostmodule. Take this as an example:with
site.yml:I added
some_other_variableto answer the question from your comment "how do I make a variable globally available from inside a play". It's not global, but it's passed to another play as a "hostvar".From what I see (and I can't explain why) in Ansible >=2.1.1.0, there must be an inventory file specified for the dynamic in-memory inventory to work. In older versions it worked with Ansible executed ad hoc, without an inventory file, but now you must run
ansible-playbookwith-i inventory_fileor have an inventory file defined throughansible.cfg.