在 Ansible 中合并列表的哈希值?

在 Ansible 中合并列表的哈希值?

我正在尝试在剧本中设置 /etc/hosts 条目。

我正在管理三个列表哈希:common_stubs、env_stubs 和 host_stubs。

我正在使用的示例

common_stubs:
  "127.0.0.1": 
    - localhost

env_stubs:
  "127.0.0.1": 
    - someservice.mydomain

host_stubs: {}

我想把它们结合起来,这样我就得到了

combined_stubs:
  "127.0.0.1":
    - localhost
    - someservice.mydomain

这就是我目前正在做的事情

- name: "Configure /etc/hosts"
  lineinfile:
    path: /etc/hosts
    regex: "{{ '^' + item.key + '.*$' }}"
    line: "{{ item.key + ' ' + ' '.join(item.value) }}"
    state: "{% if item.value | length > 0 %}present{% else %}absent{% endif %}"
  loop: "{{ common_stubs | combine(env_stubs, host_stubs, recursive=True) | dict2items }}"
  become: true

但中的数组env_stubs覆盖了中的数组common_stubs

答案1

首先创建 IP 列表

- set_fact:
    list_ip: "{{ list_ip|default([]) + item }}"
  loop:
    - "{{ common_stubs.keys()|list }}"
    - "{{ env_stubs.keys()|list }}"
    - "{{ host_stubs.keys()|list }}"
- set_fact:
    list_ip: "{{ list_ip|flatten|unique }}"

然后循环列表并结合词典

- set_fact:
    combined_stubs: "{{ combined_stubs|default({})|
                        combine({item: [[common_stubs[item]|default([])] +
                                        [env_stubs[item]|default([])] +
                                        [host_stubs[item]|default([])]]|
                                       flatten}) }}"
  loop: "{{ list_ip }}"

"combined_stubs": {
    "127.0.0.1": [
        "localhost", 
        "someservice.mydomain"
    ]
}


下一个选项是创建自定义过滤器

$ cat filter_plugins/dict_utils.py
def dict_merge_lossless(x, y):
    d = x.copy()
    d.update(y)
    for key, value in d.items():
       if key in x and key in y:
               d[key] = [value , x[key]]
    return d

class FilterModule(object):
    ''' Ansible filters. Interface to Python dictionary methods.'''

    def filters(self):
        return {
            'dict_merge_lossless' : dict_merge_lossless
        }

然后下面的任务

- set_fact:
    combined_stubs: "{{ common_stubs|
                        dict_merge_lossless(env_stubs)|
                        dict_merge_lossless(host_stubs) }}"
- debug:
    var: combined_stubs

  combined_stubs:
    127.0.0.1:
    - - someservice.mydomain
    - - localhost

相关内容