{{ hostvars['test.example.com']['ansible_facts']['distribution'] }}
With “Fact Caching” disabled, to share information among Ansible playbooks, it's possible to store all hostvars in a file. For example with, given the inventory
shell> cat hosts
[test]
test_01
test_02
test_03
this template
$ cat my_hostvars.json.j2
my_hostvars_all:
{% for my_host in ansible_play_hosts_all %}
{{ my_host }}:
{{ hostvars[my_host]|to_nice_json }}
{% endfor %}
shell> cat my_hostvars.json.j2
my_hostvars_all:
{% for my_host in ansible_play_hosts_all %}
{{ my_host }}:
{{ hostvars[my_host]|to_nice_json }}
{% endfor %}
and the playbook below stores
shell> cat pb1.yml
- hosts: test
tasks:
- set_fact:
test_var: "test_var_in_{{ inventory_hostname }}"
- template:
src: my_hostvars.json.j2
dest: "{{ playbook_dir }}/my_hostvars.json"
delegate_to: localhost
run_once: true
store hostvars of all hosts ininto the dictionary my_hostvars_all and put it into the file {{ inventory_dir }}/my_hostvars.json
{{ playbook_dir }}/my_hostvars.json
at localhost(master)
- hosts: test_jails
tasks:
- set_fact:
test_var: "test_var_in_{{ inventory_hostname }}"
- template:
src: my_hostvars.json.j2
dest: "{{ inventory_dir }}/my_hostvars.json"
delegate_to: localhost
run_once: true
. The dictionary can be included in the next playbook. For example, the playbook below
- hosts: test_jails
tasks:
- include_vars: my_hostvars.json
- set_fact:
my_hostvars: "{{ my_hostvars_all[inventory_hostname] }}"
- debug:
var: my_hostvars.test_var
shell> cat pb2.yml
- hosts: test
tasks:
- include_vars: my_hostvars.json
- debug:
msg: "{{ my_hostvars_all[inventory_hostname]['test_var'] }}"
gives (abridged)
ok: [test_01] => {
"my_hostvars.test_var": "test_var_in_test_01"
}
ok: [test_02] => {
"my_hostvars.test_var": "test_var_in_test_02"
}
ok: [test_03] => {
"my_hostvars.test_var": "test_var_in_test_03"
}
ok: [test_01] =>
msg: test_var_in_test_01
ok: [test_02] =>
msg: test_var_in_test_02
ok: [test_03] =>
msg: test_var_in_test_03