如何遍历Ansible ios_facts返回的字典格式接口数据筛选up状态接口
核心问题原因
你遇到的报错主要来自三个问题:
- 原Playbook存在YAML语法缩进错误,任务层级、模块参数、循环/判断语句的缩进完全不符合规范
dict2items过滤器将字典转换为列表后,每个元素的结构为{"key": "接口名称", "value": {"bandwidth": xxx, "lineprotocol": xxx}},你直接调用item.lineprotocol无法匹配到对应字段,需要通过item.value.lineprotocol取值- 你配置了
gather_facts: no,直接调用全局ansible_facts变量存在加载延迟或未定义的风险,优先从注册的cisco_output变量中取值更稳妥
正确可运行的Playbook
--- - name: 检查接口状态 gather_facts: no hosts: iosxe tasks: - name: 采集Cisco设备全量事实 cisco.ios.ios_facts: gather_subset: all register: cisco_output - name: 输出所有协议状态为up的接口 debug: msg: "接口名:{{ item.key }},IP地址:{{ item.value.ipv4 | map(attribute='address') | join(',') }},物理状态:{{ item.value.operstatus }}" loop: "{{ cisco_output.ansible_facts.ansible_net_interfaces | dict2items }}" when: item.value.lineprotocol == "up"
你之前三种写法的错误说明
- 第一种
loop: "{{ ansible_facts['ansible_net_interfaces'] | dict2items }}":全局ansible_facts未加载完成,且when条件取值路径错误 - 第二种
loop: "{{ cisco_output['ansible_facts']['ansible_net_interfaces'] }}":直接将字典结构传给loop,loop仅支持遍历列表/数组类型,直接报错 - 第三种
loop: "{{ cisco_output['ansible_facts']['ansible_net_interfaces'] | dict2items }}":循环对象写法正确,但when条件未加.value前缀,找不到lineprotocol字段报错
内容的提问来源于stack exchange,提问作者Adam Freemotion
相关产品推荐
相关产品推荐

