如何访问 ansible 字典 ansible_net_interfaces 子分支

如何访问 ansible 字典 ansible_net_interfaces 子分支

我正在尝试从 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 地址,那么就可以了(因为我不需要使用未配置的接口),但如果我使用 when 语句,我不知道将它放在哪里,因为它需要成为读取字典的循环的一部分。

我已经研究过使用 with_subelements,但我不太清楚如何定义它,而且我不确定是否需要使用 with_dict 来正确读取字典

答案1

我终于弄明白了:

- 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 }}"

相关内容