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

Ansible如何合并三个独立字典列表得到指定结构化输出

合并三个字典列表到目标结构的Ansible实现

你可以通过zip过滤器结合循环完成合并,完整实现代码如下:

---
- name: Merge three lists to target structure
  hosts: localhost
  gather_facts: false
  vars:
    remoteports:
      - remoteport: Gi1/0/11
      - remoteport: Gi1/0/12
      - remoteport: Gi1/0/13
    shorthosts:
      - host: HOST01
      - host: HOST02
      - host: HOST03
    neighbour_keys:
      - GigabitEthernet1/0/1
      - GigabitEthernet1/0/2
      - GigabitEthernet1/0/3

  tasks:
    - name: Initialize empty Combined dict
      set_fact:
        Combined: {}

    - name: Build Combined dict by paired items
      set_fact:
        Combined: "{{ Combined | combine({item[0]: [{'host': item[1].host, 'remoteport': item[2].remoteport}]}) }}"
      loop: "{{ neighbour_keys | zip(shorthosts, remoteports) | list }}"

    - name: Print result
      debug:
        var: Combined

运行后输出和你要求的结构完全一致:

TASK [Print result] *********************************************************************
ok: [localhost] => {
    "Combined": {
        "GigabitEthernet1/0/1": [
            {
                "host": "HOST01",
                "remoteport": "Gi1/0/11"
            }
        ],
        "GigabitEthernet1/0/2": [
            {
                "host": "HOST02",
                "remoteport": "Gi1/0/12"
            }
        ],
        "GigabitEthernet1/0/3": [
            {
                "host": "HOST03",
                "remoteport": "Gi1/0/13"
            }
        ]
    }
}

核心逻辑说明

  • 用zip过滤器将三个列表按索引位置一一配对,每一项的顺序为[neighbour_keys元素, shorthosts元素, remoteports元素]
  • 每次循环用combine过滤器往已有的Combined字典中追加新的键值对,值的部分按要求构造为包含host和remoteport的单元素列表即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:06:03