我正在尝试合并包含多个应用设置的两个词典。在附加到单个主机的主词典中,它包含特定于该服务器的内容(例如,与应用程序的git仓库相关的版本):
installed_apps:
pineapple:
version: master
pear:
version: "1.1"
然后,辅助版包含特定于该应用的所有设置:
all_apps:
pineapple:
setting1: blah
setting2: di
setting3: blah
apple:
setting1: hi
pear:
setting3: there
从这些我想构建一个字典,结合两个的值,但仅当应用程序存在于“installed_apps”时,以便ansible包含它需要安装的所有应用程序的所有详细信息某个服务器:
new_dict:
pineapple:
version: master
setting1: blah
setting2: di
setting3: blah
pear:
version: "1.1"
setting3: there
在Python中它会是这样的:
installed_apps = {
"pineapple": {"version": "master"},
"pear": {"version": "1.1"}
}
all_apps = {
'pineapple': {'setting1': 'blah', 'setting2': 'di', 'setting3': 'blah'},
'apple': {'setting1': 'hi'},
'pear': {'setting3': 'there'}
}
new_dict = dict()
for k, v in all_apps.items():
if k in installed_apps:
new_dict[k] = v
new_dict[k].update(installed_apps[k])
但我不能为我的生活找到如何在Ansible中做到这一点。
答案 0 :(得分:3)
您可以使用Ansible的combine过滤器执行此操作。
以下示例假定以下内容:
- hosts: localhost
gather_facts: false
vars:
installed_apps:
pineapple:
version: master
pear:
version: "1.1"
all_apps:
pineapple:
setting1: blah
setting2: di
setting3: blah
apple:
setting1: hi
pear:
setting3: there
首先,我们创建一个新词典(installed_app_settings
),其中包含all_apps
中installed_apps
中匹配键的项目:
- set_fact:
installed_app_settings: >
{{ (installed_app_settings|default([])) + [{item: all_apps[item]}] }}
with_items: "{{ installed_apps }}"
- debug:
var: installed_app_settings
现在我们使用它来更新installed_apps
变量,其中包含上一个set_fact
任务中提取的值:
- set_fact:
installed_apps: >
{{ installed_apps|combine(item, recursive=True) }}
with_items: "{{ installed_app_settings }}"
- debug:
var: installed_apps
结果是:
ok: [localhost] => {
"installed_apps": {
"pear": {
"setting3": "there",
"version": "1.1"
},
"pineapple": {
"setting1": "blah",
"setting2": "di",
"setting3": "blah",
"version": "master"
}
}
}
......我认为这就是你所追求的目标。