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

Ansible如何合并两个字典 实现同键列表值拼接而非覆盖

Ansible 字典同键对应列表合并实现

默认combine过滤器的逻辑是后传入字典的同键值直接覆盖原值,不会自动拼接列表元素,要实现目标合并效果可以用以下两种方案:

方案一:combine过滤器参数实现(推荐,Ansible 2.10+ 支持)

Ansible 2.10版本开始,combine新增了列表合并控制参数,开启递归合并同时指定列表追加规则即可,不需要写额外循环:

- debug:
    msg: "{{ item.key }} = {{ item.value }}"
  with_dict: "{{ policies_json.working_dir | combine(new_project_working_dirs, recursive=True, list_merge='append') }}"

执行后输出结果完全匹配预期:

{'raw': ['gore', 'logs', 'output', 'input'], 'stg': ['gore', 'logs'], 'itl': ['gore', 'logs'], 'biz': ['gore', 'logs', 'cars', 'bus']}

如果合并后需要对列表去重,给对应值追加unique过滤器即可,无去重需求直接用上述写法。

方案二:低版本兼容写法(Ansible <2.10 版本使用)

如果使用的Ansible版本低于2.10,没有list_merge参数,可以通过循环遍历键值手动拼接列表:

# 先遍历新字典,拼接同键的列表元素
- set_fact:
    merged_tmp: "{{ merged_tmp | default({}) | combine({item.key: (policies_json.working_dir[item.key] | default([])) + item.value}) }}"
  loop: "{{ new_project_working_dirs | dict2items }}"

# 补全原字典中未被新字典覆盖的键值
- set_fact:
    final_merged: "{{ policies_json.working_dir | combine(merged_tmp) }}"

最终final_merged变量就是合并完成的结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 01:36:19