ansible-合并三个词典列表 [英] ansible - combine three lists of dictionaries
问题描述
在我的剧本中,我从多个来源收集有关应用程序的事实,并最终得到3个(或更多)列表,每个列表都有一个字典.
In my playbook I'm gathering facts on applications, from multiple sources and end up with 3 (or more) lists, each of them have a dict.
有没有一种方法可以将这种结构组合成一个字典列表.如果没有,关于我将如何更改数据结构的任何建议?
Is there a way to combine such structure into one list of dictionaries. If not, any suggestion on how I would need to change the data structure?
我的代码尝试结合 2个字典列表(即使在最终用例中也要3个或更多).
My code that tries to combine 2 list-of-dict (even that in final usecase there would be 3 or more).
所有war_ *列表应具有相同数量的字典,并带有键"app_name",只是我们随意选择war_time作为迭代器-并且 app_name 在所有这些字典中都是通用的
All war_* lists should have the same number of dictionaries, with key "app_name", just arbitrarily we choose war_time as iterator - and app_name is common among them all
- hosts: localhost
vars:
war_status:
- app_name: app1-SNAPSHOT
app_status: running
- app_name: app2
app_status: stopped
- app_name: app3-jsf
app_status: unknown
war_time:
- app_name: app1-SNAPSHOT
app_time: '2017-07-07 06:38:30'
- app_name: app2
app_time: '2018-07-19 09:16:57'
- app_name: app3-jsf
app_time: '2019-07-21 06:00:57'
war_proxy_status:
- app_name: app1-SNAPSHOT
app_where_found: inst1
- app_name: app2
app_where_found: inst2
- app_name: app3-jsf
app_where_found: inst3
tasks:
- set_fact:
war_combined: []
- name: combine1 war_status and war_time
set_fact:
war_combined: "{{ war_combined | default([]) + [ war_status | combine( item ) ] }}"
loop: "{{ war_time }}"
- debug:
msg: "{{ war_combined }}"
我想要实现的结果是:
war_combined:
- app_name: app1-SNAPSHOT
app_status: running
app_time: '2017-07-07 06:38:30'
app_where_found: inst1
- app_name: app2
app_status: stopped
app_time: '2018-07-19 09:16:57'
app_where_found: inst2
- app_name: app3-jsf
app_status: unknown
app_time: '2019-07-21 06:00:57'
app_where_found: inst3
推荐答案
您应该合并单个元素,但是尝试将单个项目合并到整个列表中.
You should combine individual elements, but you try merge single item into whole list.
赞:
- set_fact:
war_combined: >-
{{ war_combined | default([])
+ [item | combine(time_item) | combine(proxy_item)]
}}
vars:
time_item: >-
{{ war_time
| selectattr('app_name','equalto',item['app_name'])
| list
| first
}}
proxy_item: >-
{{ war_proxy_status
| selectattr('app_name','equalto',item['app_name'])
| list
| first
}}
loop: "{{ war_status }}"
我们遍历war_status
并使用帮助变量time_item
和proxy_item
,这些变量针对每次迭代进行评估,从与当前项目的app_name
匹配的app_name
列表中选择特定元素.
We loop over war_status
and use helper variables time_item
and proxy_item
that are evaluated for each iteration selecting specific element from lists with app_name
matching current item's app_name
.
这篇关于ansible-合并三个词典列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!