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

如何在Ansible中扁平化多层列表以实现便捷遍历解析?

Ansible 扁平化多层列表并实现可遍历解析

你当前用模板生成的是纯文本内容,无法被Ansible识别为可遍历的列表结构。要实现多层列表的扁平化并得到可直接遍历的结构化数据,推荐使用Ansible内置过滤器或循环任务来生成目标列表,以下是两种可行方案:

方案一:使用subelements过滤器(简洁高效)

subelements过滤器专门用于展开嵌套列表,配合map等过滤器可快速生成扁平化后的字典列表:

- hosts: localhost
  vars:
    the_list:
      - clusters: ["host1", "host2"]
        space: "space1"
      - clusters: ["host1", "host2"]
        space: "space2"
    # 直接在变量中生成扁平化列表
    flattened_list: >-
      {{ 
        the_list | subelements('clusters') 
        | map('extract', [0, 'space']) 
        | zip(the_list | subelements('clusters') | map('extract', [1])) 
        | map('dict', ['namespace', 'clusters']) 
        | list 
      }}
  tasks:
    - name: 遍历扁平化列表输出结果
      debug:
        msg: "namespace: {{ item.namespace }}, clusters: {{ item.clusters }}"
      loop: "{{ flattened_list }}"

方案二:使用循环构建(直观易理解)

通过双层循环逐个拼接目标字典,逐步生成结构化列表:

- hosts: localhost
  vars:
    the_list:
      - clusters: ["host1", "host2"]
        space: "space1"
      - clusters: ["host1", "host2"]
        space: "space2"
  tasks:
    - name: 循环构建扁平化列表
      set_fact:
        flattened_list: "{{ flattened_list | default([]) + [{'namespace': space_item.space, 'clusters': cluster_item}] }}"
      loop: "{{ the_list }}"
      loop_control:
        loop_var: space_item
      with_items: "{{ space_item.clusters }}"
      loop_control:
        loop_var: cluster_item

    - name: 遍历输出结果
      debug:
        msg: "namespace: {{ item.namespace }}, clusters: {{ item.clusters }}"
      loop: "{{ flattened_list }}"

输出效果

两种方案执行后都会输出你期望的内容:

ok: [localhost] => (item={'namespace': 'space1', 'clusters': 'host1'}) => {
    "msg": "namespace: space1, clusters: host1"
}
ok: [localhost] => (item={'namespace': 'space1', 'clusters': 'host2'}) => {
    "msg": "namespace: space1, clusters: host2"
}
ok: [localhost] => (item={'namespace': 'space2', 'clusters': 'host1'}) => {
    "msg": "namespace: space2, clusters: host1"
}
ok: [localhost] => (item={'namespace': 'space2', 'clusters': 'host2'}) => {
    "msg": "namespace: space2, clusters: host2"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 04:18:23