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]]

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。