Ansible: 如何获取主机IP How to get host IP?

ansible会使用ansible facts收集主机信息,针对使用度较高的主机IP提供多种获取方法。

获取IP地址及使用范围可参考这篇文章的写法

https://www.middlewareinventory.com/blog/ansible-get-ip-address/

使用度最广的写法:

{{hostvars[inventory_hostname]['ansible_env'].SSH_CONNECTION.split(' ')[2]}}

规范写法:(需主机设定默认ip)

{{ hostvars[inventory_hostname]['ansible_default_ipv4']['address']}}

简便写法:(需了解默认网卡)

ansible_enp0s8.ipv4.address


官方建议写法best practice:

https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html

Some provided facts, like networking information, are made available as nested data structures. To access them a simple {{ foo }} is not sufficient, but it is still easy to do. Heres how we get an IP address:

{{ ansible_facts["eth0"]["ipv4"]["address"]}}

OR alternatively:

{{ ansible_facts.eth0.ipv4.address }}

Similarly, this is how we access the first element of an array:

{{ foo[0]}}

如:groups['teleport-auth'][0]]

你可能感兴趣的:(Ansible: 如何获取主机IP How to get host IP?)