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

Ansible使用with_items合并字典仅保存最后一项,求正确实现语法

问题根因

你代码中定义的single_entry是字符串类型而非字典对象,Ansible的combine过滤器仅支持字典之间的合并,老版本隐式转换字符串为字典失败,导致每次合并操作实际都覆盖了之前的ids值,最终仅保留最后一次遍历的结果。

修复方案

直接在combine过滤器内构造临时字典即可,无需单独定义single_entry变量,适配Ansible 2.5版本的完整playbook如下:

---
- name: TestingLab
  hosts: localhost
  gather_facts: False
  tasks:
    - name: Hello Vars
      set_fact:
        two_nums:
          - 1
          - 2

    - name: create empty dict
      set_fact:
        ids: {}

    - name: Merge all
      set_fact:
        ids: "{{ ids | combine({ item | string: item }) }}"
      with_items: "{{ two_nums }}"

    - name: Print Result
      debug:
        msg: "{{ ids }}"

如果需要保留整数类型的字典key,去掉item | string中的string过滤器即可,Ansible 2.5对整数key的处理存在少量兼容问题,默认使用字符串类型key更稳妥。

如果一定要单独定义single_entry变量,写法如下即可:

- name: Merge all
  vars:
    single_entry: "{{ { item | string: item } }}"
  set_fact:
    ids: "{{ ids | combine(single_entry) }}"
  with_items: "{{ two_nums }}"

运行结果

修改后执行playbook输出如下:

ok: [localhost] => {
"msg": {
"1": 1,
"2": 2
}
}


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 08:48:00