ansible之获取主机IP地址

{{ hostvars[inventory_hostname]['ansible_local']['interfaces']['management']['ipv4']['address'] }}
1、hostvars
获取某台指定的主机的相关变量。如果有一台web服务器的配置文件中需要指定db服务器的ip地址,我们假定这台db服务器的hostname为 db.exmaple.com,ip地址绑定在eth0网卡上,我们可以通过如下方法在web服务器上调用db服务器的ip地址:
{{ hostvars['db.example.com'].ansible_eth0.ipv4.address }}
2. ansible_local
本地fact默认存放于目标主机的/etc/ansible/facts.d目 录下,如果文件为.ini格式或者json格式,ansible会自动识别。以这种形式加载的fact是key为ansible_local的特殊变量。


cat facts/10.0.194.7 
省略..........
    "ansible_local": {
        "bond_nic": {
            "enp129s0f1": {}, 
            "enp1s0f0": {}
        }, 
        "interfaces": {
            "management": {
                "device": "enp1s0f1.1151", 
                "ipv4": {
                    "address": "10.0.194.7", 
                    "netmask": "255.255.255.0", 
                    "network": "10.0.194.0"
                }
            }, 
            "storage": {
                "device": "enp130s0f0.1170", 
                "ipv4": {
                    "address": "10.0.196.7", 
                    "netmask": "255.255.255.0", 
                    "network": "10.0.196.0"
                }
            }, 
            "tenant": {
                "device": "enp129s0f1.1250", 
                "ipv4": {
                    "address": "10.0.204.7", 
                    "netmask": "255.255.255.0", 
                    "network": "10.0.204.0"
                }
            }
        }, 
省略..........


上一篇:网络连接详细信息出现两个自动配置ipv4地址的解决办法


下一篇:ubuntu 开启ip转发的方法