我正在尝试从ansible_net_interfaces读取信息,但是每个设备的接口名称都不同。我在访问大多数信息时没有遇到任何困难,但是当我到达ipv4时,会有一个子数组,而且无论我尝试了什么,我都不能始终访问它。以下是我的任务:
- name: Get config for Cisco Routers
ios_facts:
gather_subset: interfaces
- name: Display all interface data
debug:
msg: "{{ item.key }},{{item.value.description}},{{item.value.ipv4}}"
with_dict:
- "{{ ansible_net_interfaces }}"
这个打印出界面。描述,然后是子数组ipv4中的密钥对子网和地址。
我对此做了一点修改,我发现
{{item.value.ipv4.0.address}}
将从一些接口中获取信息,然后退出任务,说"FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: list object has no element 0"
一碰到没有配置IP的接口就会立即失效。
如果有可能预先检查接口是否配置了一个可以工作的IP地址(因为我不需要使用未配置的接口),但是如果我使用一个where语句,我不知道把它放在哪里,因为它需要成为通过字典读取的循环的一部分。
我研究过使用with_subelements,但我不太确定如何定义它,我也不确定是否需要使用with_dict来正确地阅读字典
发布于 2020-09-17 13:38:22
我终于明白了:
- name: Display all interface data
debug:
msg: "{{ item.key }},{{item.value.description}},{{item.value.ipv4.0.address}},{{item.value.ipv4.0.subnet}}"
when: item.value.ipv4.0.address is defined
with_dict:
- "{{ ansible_net_interfaces }}"
https://serverfault.com/questions/1034237
复制相似问题