A three-line template builds /etc/hosts from all hosts' facts with hostvars. How does it work, and what can go wrong?
It loops over groups['all'] and reads each host's address, FQDN and short name from hostvars[host]['ansible_facts']; this needs the facts of every host, so a host that was not gathered breaks the render, and the generated file replaces /etc/hosts completely, including its localhost line.
* hostvars lets one host's template read every other host's facts. *
- name: /etc/hosts is up to date
hosts: all
gather_facts: true
tasks:
- name: Deploy /etc/hosts
ansible.builtin.template:
src: templates/hosts.j2
dest: /etc/hosts
{% for host in groups['all'] %}
{{ hostvars[host]['ansible_facts']['default_ipv4']['address'] }} {{ hostvars[host]['ansible_facts']['fqdn'] }} {{ hostvars[host]['ansible_facts']['hostname'] }}
{% endfor %}
hostvars holds the variables and facts of every host, so while rendering for web1 the template can read db1's address. That only works if db1's facts exist: here they do because the play runs hosts: all with fact gathering. If a host is unreachable, or the play is limited (--limit web1), its ansible_facts are missing and the render fails with an undefined-variable error. Guard with {% if 'default_ipv4' in hostvars[host]['ansible_facts'] %} or gather facts in an earlier play.
The second trap is ownership: the template now is /etc/hosts. Without a line like 127.0.0.1 localhost in the template, that entry is gone after the first run.
Go deeper:
Special variables: hostvars (official docs) — what
hostvarscontains and when.hosts (file) (Wikipedia) — the file format and the usual localhost entries.