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
相关产品推荐
相关产品推荐

