Search code examples
ansibleansible-inventory

Ansible getting public ip of host from inventory file


I would like to get public ip of a host defined in inventory file

[test-sites:children]
test-site-1

[test-site-1]
test-site-1-2 ipv4=192.168.0.1 ipv6=....

How do I get the ipv4 and ipv6 address of "test-site-1-2" defined in the inventory file? I have checked this answer but it gives all of the addresses (public & private). I am interested in ips defined in the inventory file only.


Solution

  • [test-site-1]
    test-site-1-2 ipv4=192.168.0.1 ipv6=....
    

    Q: "How do I get the ipv4 and ipv6 address of "test-site-1-2" defined in the inventory file?"

    A: If the playbook is running at "test-site-1-2" simply reference the variables directly. For example

    - hosts: test-site-1-2
      tasks:
        - debug:
            var: ipv4
        - debug:
            var: ipv6
    

    If these variables are needed by other hosts reference to "hostvars" is needed. For example

    - hosts: test-site-1
      tasks:
        - debug:
            var: hostvars['test-site-1-2'].ipv4
        - debug:
            var: hostvars['test-site-1-2'].ipv6
    

    See Basic inventory.