FreeKB - Ansible hostvars magic variable
Ansible - hostvars magic variable

hostvars can be used to display the facts about your managed nodes (the target systems). Refer to run tasks on the control node if you want to display the facts of your control node (your Ansible server).

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 facts
      debug:
        msg: "{{ hostvars[inventory_hostname] }}"

 

Something like this will be returned.

TASK [display facts]
ok: [server1.example.com] => {
    "msg": {
        "ansible_all_ipv4_addresses": [
            "192.168.0.5"
        ],
        "ansible_all_ipv6_addresses": [
            "fe80::20c:29ff:fead:315d"
        ],
        "ansible_apparmor": {
            "status": "disabled"
        },
        "ansible_architecture": "x86_64",
        "ansible_bios_date": "04/05/2016",
        "ansible_bios_vendor": "Phoenix Technologies LTD",
        "ansible_bios_version": "6.00",
        "ansible_board_asset_tag": "NA",

 

Often, you will be looking to display a specific facts, such as the IPv4 address. This can be done with brackets.

 

---
- hosts: all
  tasks:
    - name: display IPv4 address fact
    - debug:
        msg: "{{ hostvars[inventory_hostname]['ansible_distribution'] }}"

 

Or with a period.

---
- hosts: all
  tasks:
    - name: display IPv4 address fact
    - debug:
        msg: "{{ hostvars[inventory_hostname].ansible_distribution }}"

 

Something like this should be returned.

 

TASK [display IPv4 address fact]
ok: [server1.example.com] => {
    "msg": [
        "192.168.0.5"
    ]
}

 



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 430e8 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   |