Ansible 从清单文件中获取主机的 public ip

Ansible getting public ip of host from inventory file

我想获取 public 清单文件中定义的主机的 ip

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

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

如何获取清单文件中定义的 "test-site-1-2" 的 ipv4 和 ipv6 地址?我已经检查了 答案,但它给出了所有地址(public 和私人)。我只对清单文件中定义的 ips 感兴趣。

[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:如果剧本是 运行 at "test-site-1-2",只需直接引用变量即可。例如

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

如果其他主机需要这些变量,则需要引用 "hostvars"。例如

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

Basic inventory