Interview Prep/Ansible/Variables, Facts and Precedence

How do you read another host's variables, and when does it fail?

AdvancedConceptVariables, Facts and Precedence
Answer

Use hostvars['hostname']['var'], commonly to build config that mentions other nodes.

upstream_servers: >-
  {{ groups['app'] | map('extract', hostvars, ['ansible_facts', 'default_ipv4', 'address']) | list }}

It fails with undefined variable for facts when that host has not been contacted in this run: facts only exist after fact gathering (or from the fact cache). Fix by running a short fact-gathering play against those hosts first (gather_subset: network) or enable cache with gathering = smart. Inventory and group variables are available without contacting the host.

All Ansible questions Roadmap: Ansible

More on Variables, Facts and Precedence