Interview Prep/Ansible/Variables, Facts and Templates

A template needs the IPs of all hosts in the `db` group, for example for a replication config.

IntermediateScenarioVariables, Facts and Templates
Answer

Situation read → Cross-host data inside a template.

What I'd do →

{% for h in groups['db'] %}
host replication repl {{ hostvars[h].ansible_default_ipv4.address }}/32 md5
{% endfor %}

Make sure facts for the db hosts exist, either by gathering in an earlier play or via fact caching.

Why → hostvars exposes other hosts' variables and facts, but only if gathered in this run or cached.

Interview tip → Facts missing causes 'ansible_default_ipv4' is undefined; gather facts for db hosts first.

All Ansible questions Roadmap: Ansible

More on Variables, Facts and Templates