我想使用Ansible在一台机器上得到networking接口的有序列表。 现代Linux系统不使用eth0,eth1等,所以名称是不可预知的。 在我们的networking中,我们将编号最小的接口连接到局域网,最高的接口连接到广域网,因此我可以使用有序列表中的接口位置来确定它的function。
我正在寻找在Ansible中执行此操作的规范方法。 所以我可以使用{{ansible_eth0.ipv4.address}}之类的东西。 (其中eth0是其他名称)。
即使我手动设置一个variables与接口的名称似乎没有办法获得该接口的IP(使用variables的内容)。
我想处理Ansible的事实,以获得我想要的,而不是在远程系统上运行一个shell脚本。
ansible_interfaces事实列出了所有现有的networking接口。
我知道Neik是从哪里来的,所以经过一番试验后,我觉得我find了一个可以解决问题的任务。
正如Michael Hamilton在上面提到的那样, ansible_interfaces事实包含了所有networking接口的列表,并且它们似乎是按顺序的(即,第一个以太网接口将被称为eth0,第二个eth1等)。 所以有一点set_fact魔术和以后的很多实验:
- name: define traditional ethernet facts set_fact: ansible_eth: "{% set ansible_eth = ansible_eth|default([]) + [hostvars[inventory_hostname]['ansible_' + item]] %}{{ ansible_eth|list }}" when: hostvars[inventory_hostname]['ansible_' + item]['type'] == 'ether' with_items: - "{{ hostvars[inventory_hostname]['ansible_interfaces'] }}"
这将ansible_interfaces当前机器的所有ansible_interfaces条目,并构build一个type等于“ether”的hostvars[inventory_hostname]['ansible_' + item]条目的列表。
因此,现在ansible_eth.0和ansible_eth.1应该大致相当于旧的ansible_eth0和ansible_eth1 。
我没有彻底地testing这个以确保顺序总是像预期的那样工作,但它似乎是伎俩。
非常感谢这个StackOverflow答案 ,向我展示了如何使用with_items构build列表。
过了一段时间,因为我触及到可靠的,但没有更多的细节,我期望像这样的东西:
ip link show | grep mode | sed 's/://g' | awk '{print $1,$2}'
上class…
1 lo 2 eth0