Search code examples
ansibleansible-inventory

Ansible: How to get the ip of ansible_hosts with shell command?


I have a inventory.yaml file:

secondtest:
  hosts:
    host1:
      ansible_host: 192.168.33.168
    host2:
      ansible_host: 192.168.7.151
    host3:
      ansible_host: 192.168.33.158

I want to get all ip address and I tried ansible secondtest -i inventory.yaml --list-hosts and this is the output:

  hosts (3):
    host1
    host2
    host3

How can I get the Ips?


Solution

  • You can use ansible-inventory to list the inventory

    shell> ansible-inventory -i inventory.yaml --list
    {
        "_meta": {
            "hostvars": {
                "host1": {
                    "ansible_host": "192.168.33.168"
                },
                "host2": {
                    "ansible_host": "192.168.7.151"
                },
                "host3": {
                    "ansible_host": "192.168.33.158"
                }
            }
        },
        "all": {
            "children": [
                "ungrouped",
                "secondtest"
            ]
        },
        "secondtest": {
            "hosts": [
                "host1",
                "host2",
                "host3"
            ]
        }
    }
    

    Then you can use, for example, jq to select what you want

    shell> ansible-inventory -i inventory.yaml --list | jq '._meta.hostvars[].ansible_host'
    "192.168.33.168"
    "192.168.7.151"
    "192.168.33.158"