I’ve set up Ansible to write out /etc/hosts files, so I want to know about all the hosts in my system. Here’s what’s in my template for /etc/hosts:
{% for key, host in hostvars.iteritems() %}
{% if hostvars[key][‘internal_ip’] %}
{{ hostvars[key][‘internal_ip’] }} {{ hostvars[key][‘name’] }}
{% endif %}
{% endfor %}
My hosts ini file defines ‘name’ and ‘internal_ip’ for each host. The problem is if I execute a playbook on a subset of hosts, such as when I’m setting up a new server, hostvars only contains data about the hosts the playbooks is running on, so I have no way to access any information about them to write to /etc/hosts.
Is there a way to get all the variables, regardless of what hosts the playbook is being applied to? (Obviously I don’t care about the facts Ansible assembles, only the variables I defined myself)
In order to access variables about other hosts you need to talk to
them, but this can be as simple as a play that just speaks to them and
does not do anything.
That hopefully answers your question. Let us know if not.
Is there a way to get all the variables, regardless of what hosts the
playbook is being applied to? (Obviously I don't care about the facts
Ansible assembles, only the variables I defined myself)
It is possible. Hostvars is modified dict that looks up variables from
other hosts as needed.
{% for key, host in hostvars.iteritems() %}
{% if hostvars[key]['internal_ip'] %}
{{ hostvars[key]['internal_ip'] }} {{ hostvars[key]['name'] }}
{% endif %}
{% endfor %}
That should be something like:
{% for host in groups['<groupname'] -%}
{% if hostvars[host].internal_ip %}
{{ hostvars[host].internal_ip }} {{ hostvars[host].name }}
{% endif %}
{% endfor -%}
Your solution works for a single group. I’ve found if I want to iterate through all the hosts, I have to do this in my /etc/hosts template
All servers
{% for host in groups[‘all’] %}
{% if hostvars[host].internal_ip %}
{{ hostvars[host].internal_ip }} {{ hostvars[host].name }}
{% endif %}
{% endfor %}
Is there a more elegant way to iterate through all the hosts defined in the hosts file? I’d have expected I could use {% for host in hosts %} or something like that.