Sometimes there is a scenario where you will want a managed node in your inventory to get a fact about the other managed nodes in your inventory. For example, the ansible_default_ipv4.address fact will display each managed nodes IP address.
---
- hosts: all
tasks:
- name: display IP address
debug:
msg: "{{ ansible_default_ipv4.address }}"
...
The following should be returned. Notice the IP addresses are different, because the IP address of each managed node is being returned.
ok: [server1.example.com] => {
"msg": "192.168.0.7"
}
ok: [server2.example.com] => {
"msg": "192.168.0.11"
}
ok: [server3.example.com] => {
"msg": "192.168.0.15"
}
hostvars can be used to get the fact of some other managed node in your inventory. Since hostvars displays facts, the gather_facts module must be set to true, which is the default setting of the gather_facts module. In other words, the gather_facts module must not be set to false.
---
- hosts: all
tasks:
- name: display server2 IP address
debug:
msg: "{{ hostvars['server2.example.com']['ansible_default_ipv4']['address'] }}"
...
Something like this should be returned. Notice that 192.168.0.11 is being returned, which is server2 IP address.
TASK [display server2 IP address]
ok: [server1.example.com] => {
"msg": "192.168.0.11"
}
ok: [server2.example.com] => {
"msg": "192.168.0.11"
}
ok: [server3.example.com] => {
"msg": "192.168.0.11"
}