Access hostvars from a group of hosts in a play
Lets say you need to perform an action and include hostvars from a group of hosts. Information on how to do this in templates can be found here: http://ansible.cc/docs/playbooks2.html#magic-variables-and-how-to-access-information-about-other-hosts - but what if you want to do this during a play?
An Example:
You have a controller system that needs to register all hosts in a particular group as slaves for the application. In this example, the group is named "slaves" and the hostname and ip address of each host is required.
name: Register slave systems
action: command register-slave --hostname ${hostvars.{$item}.ansible_hostname} --ip ${hostvars.${item}.ansible_em1.ipv4.address}
with_items: ${groups.slaves}
As seen, this allows you to iterate through a groups hostvars for use in your play!
Written by Lester Wade
Related protips
2 Responses
Hello,
What's the equivalent with the new convention? {{ item }} doesn't seem to work.
Thanks in advance.
@leseb: With the new convention, you can just use item in the hostvars without any braces. e.g.:
hostvars[item]['ansible_hostname']