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

如何在Ansible中根据ID匹配合并两个列表?

问题解决:根据ID匹配筛选列表条目

需求说明

我有如下两个列表:

list1

list1: [
    {
        "id": "1",
        "name": "a"
    },
    {
        "id": "2",
        "name": "b"
    },  
    {
        "id": "3",
        "name": "c"
    },
    {
        "id": "4",
        "name": "d"
    }
]

list2

list2: [
    {
        "id": "1"
    },
    {
        "id": "4"
    }
]

需要生成list3,要求保留list1中与list2的ID匹配的条目,同时保留id和name字段,最终格式如下:

list3: [
    {
        "id": "1",
        "name": "a"
    },
    {
        "id": "4",
        "name": "d"
    }
]

之前尝试使用combine过滤器:

list3: "{{ list1 | combine(list2) }}"

得到的结果不符合需求,仅返回了最后一个匹配的条目:

ok: [localhost] => {
"msg": {
"id": "4",
"name": "d"
}

正确实现方法

combine过滤器的作用是合并字典,无法完成列表的筛选匹配,所以不能满足需求。要实现按ID匹配筛选列表,需要结合map和selectattr过滤器,步骤如下:

  1. 先提取list2中的所有ID,生成一个纯ID列表:
    target_ids: "{{ list2 | map(attribute='id') | list }}"
    
  2. 用selectattr筛选list1中id属于target_ids的条目:
    list3: "{{ list1 | selectattr('id', 'in', target_ids) | list }}"
    

完整Playbook示例

- name: 筛选匹配ID的列表条目
  hosts: localhost
  vars:
    list1: [
        {"id": "1", "name": "a"},
        {"id": "2", "name": "b"},
        {"id": "3", "name": "c"},
        {"id": "4", "name": "d"}
    ]
    list2: [
        {"id": "1"},
        {"id": "4"}
    ]
    target_ids: "{{ list2 | map(attribute='id') | list }}"
    list3: "{{ list1 | selectattr('id', 'in', target_ids) | list }}"
  tasks:
    - debug:
        var: list3

运行后会得到符合要求的list3:

ok: [localhost] => {
"list3": [
{
"id": "1",
"name": "a"
},
{
"id": "4",
"name": "d"
}
]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 17:25:20