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.
More on Variables, Facts and Precedence
Where can you define variables in Ansible?BeginnerHow do you reference a variable, and when must you quote it?BeginnerGive a summary of variable precedence.IntermediateWhat are the lowest and highest precedence sources, and why does that matter?IntermediateWhat is the difference between a role's `defaults/` and `vars/`?IntermediateWhat are facts and how are they gathered?Beginner