如何使用shell命令获取ansible_hosts的IP地址?

huangapple go评论69阅读模式
英文:

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

问题

我想获取所有IP地址,我尝试过 ansible secondtest -i inventory.yaml --list-hosts,以下是输出结果:

  hosts (3):
    host1
    host2
    host3

我该如何获取IP地址?

英文:

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?

答案1

得分: 2

你可以使用 ansible-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"
        ]
    }
}

然后,你可以使用,例如,jq 来选择你想要的内容

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

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"

huangapple
  • 本文由 发表于 2023年5月17日 17:37:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76270650.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定