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

Ansible中如何拆分列表内值含多个元素的字典?

Ansible 拆分字典列表中多值food字段

实现思路

遍历原始列表中的每个条目,对每个条目的food列表进行二次遍历,将每个食物项单独与对应animal组成新字典,最终合并为新的列表。

示例代码

首先定义原始变量:

original_animals:
  - animal: fox
    food: [chickens]
  - animal: rabbit
    food: [carrots, apples]

使用set_fact结合Jinja2模板生成拆分后的列表:

- name: 拆分food字段为独立字典
  set_fact:
    split_animals: >-
      {% set output = [] %}
      {% for animal_entry in original_animals %}
        {% for food_item in animal_entry.food %}
          {% do output.append({'animal': animal_entry.animal, 'food': [food_item]}) %}
        {% endfor %}
      {% endfor %}
      {{ output }}

执行结果

运行上述任务后,split_animals变量的结构将符合预期:

ok: [localhost] => {
    "split_animals": [
        {
            "animal": "fox",
            "food": [
                "chickens"
            ]
        },
        {
            "animal": "rabbit",
            "food": [
                "carrots"
            ]
        },
        {
            "animal": "rabbit",
            "food": [
                "apples"
            ]
        }
    ]
}

补充说明

  • 若原始数据来自之前任务的输出(比如msg字段),只需将original_animals替换为对应变量(例如{{ previous_task_result.msg }})即可。
  • Jinja2的do语句用于修改列表,默认已启用,无需额外配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:12:25