问题:
由于线上机器是多家厂商的且网卡会有公网IP和内网IP都绑定情形,并且有些服务必须保证监听内网IP,但在host清单文件配置中有可能是内网IP,也有可能是公网IP。
使用:变量 {{ ansible_all_ipv4_addresses }} 会获取机器所有IP,但没有排序
使用: 变量 {{ ansible_default_ipv4['address'] }} 则是网卡默认IP,经验证此时有可能是内网IP也有可能是公网IP
解决:
安装:netaddr 模块
yum install -y python-netaddr pip3 install netaddr
对变量 ansible_all_ip_addresses
使用 ipaddr
过滤
{{ ansible_all_ipv4_addresses | ipaddr('private') | first }} or {{ ansible_all_ipv4_addresses | ipaddr('10.0.0.0/8') | first }}
参考:
https://docs.ansible.com/ansible/2.3/playbooks_filters_ipaddr.html
https://docs.ansible.com/ansible/2.3/playbooks_filters.html#filters
https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters_ipaddr.html
https://stackoverflow.com/questions/34730239/how-to-get-host-private-network-address-in-ansible
https://www.cnblogs.com/carriezhangyan/p/10950970.html