FreeKB - Ansible managed node variables and facts (hostvars)
Ansible - managed node variables and facts (hostvars)

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"
}

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter 9d47f in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |