来自ansible的设置模块提供了ansible_interfaces的事实
"ansible_interfaces": [ "lo", "eth0", "eth1" ],
和每个接口的一些事实:
"ansible_eth0": { "active": true, "device": "eth0", "ipv4": { "address": "192.168.10.2", "broadcast": "192.168.10.255", "netmask": "255.255.255.0", "network": "192.168.10.0" }, "macaddress": "52:54:00:5c:c1:36", "module": "virtio_net", "mtu": 1500, "pciid": "virtio0", "promisc": false, "type": "ether" }
如何使用ansible_interfaces事实来循环可用的接口?
tasks: - name: find interface facts debug: msg=ansible_{{ item }} with_items: "{{ ansible_interfaces }}"
这显然不起作用,因为它打印出stringansible_lo,ansible_eth0和ansible_eth1,但我希望它从这些接口打印出事实。 有些服务器有其他接口,比如网桥,所以我不知道有哪些接口可以使用。
ps这个例子不是非常有用的,但最终我想用它来存储事实,如在elasticsearch中的macaddresses,以方便search哪个服务器有哪个macaddress。
您遇到了Jinja / Ansible模板的一个局限性,也就是说无法评估expression式,这对于获得类似于ansible_{{ item }}这样的值是必需的。 你被一个string卡住了。
幸运的是,全局hostvars对象可以通过键访问所有的事实,这是一个string。
沿着这些线路的东西应该让你在那里:
tasks: - name: find interface facts debug: msg: "{{ hostvars[inventory_hostname]['ansible_%s' | format(item)] }}" with_items: "{{ ansible_interfaces }}"