When orchestrating a playbook against multiple hosts, you may need to pull facts from one host in order to feed those values to another host. For example, a database master may need to provide its IP address to its many replicas, or a CA certificate from a controller may need to be distributed among its members.
By default, facts are cached in-memory for the duration of the playbook run. This idea can be leveraged to distribute information from one host to another using the Ansible special ‘hostvars’ variable.
# save IP address of Ansible orchestrator - hosts: localhost connection: local gather_facts: yes tasks: - set_fact: hostvm_ip: "{{ ansible_default_ipv4.address }}" - debug: msg="The localhost default IP is {{hostvm_ip}}" # IP address now available to other hosts, pulled from in-memory cache - hosts: all tasks: - debug: msg="The ansible orchestrator default IP was {{hostvars['localhost']['hostvm_ip']}}"
Here is a link to playbook-cached-facts.yml, the playbook that exercises the snippet above.
REFERENCES