You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ansible Loop中遍历长度可变的嵌套列表?

解决Ansible嵌套列表的全元素遍历问题

问题分析

当前任务通过硬编码索引0(item.value.0)仅能获取列表首个元素的LLDP数据,要适配长度可变的列表并遍历全部元素,需要对item.value这个嵌套列表添加一层循环。

方案1:嵌套循环实现

直接在外层循环的基础上,对每个交换机对应的端口列表再做遍历:

- name: 打印所有LLDP端口数据
  debug:
    msg: "交换机{{ switch_item.key }} - 端口{{ port_item.key }}的LLDP系统名: {{ port_item.value.lldp.systemName | default('未配置') }}"
  loop: "{{ cdp_lldp_by_switch | dict2items }}"
  loop_control:
    loop_var: switch_item
  with_items: "{{ switch_item.value }}"
  loop_control:
    loop_var: port_item

方案2:使用subelements插件(推荐)

Ansible的subelements插件专门用于展开嵌套的列表结构,写法更简洁:

- name: 遍历所有LLDP端口数据
  debug:
    var: item.1.value.lldp.systemName | default('无系统名称')
  loop: "{{ cdp_lldp_by_switch | dict2items | subelements('value') }}"

这里item.0对应外层的交换机条目,item.1对应每个端口的详细数据,无需关心列表长度,自动遍历所有元素。

内容的提问来源于stack exchange,提问作者John

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 08:52:26