我正在尝试弄清楚如何组合大小不同的两个字典。目的是将其他收件人添加到第三本词典的收件人列表中。
mail_aliases_list:
- name: mailer-daemon
recipients:
- foo
- name: postmaster
recipients:
- bar
- name: bin
recipients:
- baz
...
和
mail_aliases_defaults:
- name: mailer-daemon
recipients:
- postmaster
- name: postmaster
recipients:
- root
- name: bin
recipients:
- root
...
产生
mail_aliases:
- name: mailer-daemon
recipients:
- postmaster
- foo
- name: postmaster
recipients:
- root
- bar
- name: bin
recipients:
- root
- baz
...
这有点超出我对过滤器的理解,我很沮丧,我什至不得不寻求帮助,但希望我会在此过程中学到一些东西。
答案 0 :(得分:0)
没有一种简单的方法可以准确地完成您想要的操作,而数据的结构方式则使其变得更加困难。如果将mail_aliases_list
和mail_aliases_defaults
变成字典,则可以更轻松地实现所需的最终状态。
类似的东西:
- hosts: localhost
gather_facts: false
become: true
vars:
mail_aliases_overrides:
mailer-daemon:
recipients:
- foo
postmaster:
recipients:
- bar
bin:
recipients:
- baz
not_in_defaults:
recipients:
- bob
mail_aliases_defaults:
mailer-daemon:
recipients:
- postmaster
postmaster:
recipients:
- root
bin:
recipients:
- root
only_in_defaults:
recipients:
- alice
tasks:
- set_fact:
mail_aliases: >-
{{ mail_aliases|default({})|combine({item:
(mail_aliases_overrides[item]|default({'recipients': []})).recipients +
(mail_aliases_defaults[item]|default({'recipients': []})).recipients
})
}}
loop: "{{ (mail_aliases_overrides.keys()|list + mail_aliases_defaults.keys()|list)|unique }}"
- debug:
var: mail_aliases
这将作为输出生成:
PLAY [localhost] ******************************************************************************************************************************************************************************
TASK [set_fact] *******************************************************************************************************************************************************************************
ok: [localhost] => (item=mailer-daemon)
ok: [localhost] => (item=postmaster)
ok: [localhost] => (item=bin)
ok: [localhost] => (item=not_in_defaults)
ok: [localhost] => (item=only_in_defaults)
TASK [debug] **********************************************************************************************************************************************************************************
ok: [localhost] => {
"mail_aliases": {
"bin": [
"baz",
"root"
],
"mailer-daemon": [
"foo",
"postmaster"
],
"not_in_defaults": [
"bob"
],
"only_in_defaults": [
"alice"
],
"postmaster": [
"bar",
"root"
]
}
}
PLAY RECAP ************************************************************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0
我已经确保它可以与仅存在于mail_aliases_defaults
或mail_aliases_overrides
之一中的键一起使用。