合并 Ansible 字典

Merging Ansible dictionaries

我正在尝试将两个字典与通用键结合起来,例如:

vpns:
  example:
    vpn_connection_name: "example"
    vpn_client_public_ip: "xxx.xxx.xxx.xxx"
  example2:
    vpn_connection_name: "example2"
    vpn_client_public_ip: "xxx.xxx.xxx.xxx"

加上:

vpn_credentials:
  example:
    vpn_shared_key: "somekey"
  example2:
    vpn_shared_key: "someotherkey"

待合并生产:

vpns:
  example:
    vpn_connection_name: "example"
    vpn_client_public_ip: "xxx.xxx.xxx.xxx"
    vpn_shared_key: "somekey"
  example2:
    vpn_connection_name: "example2"
    vpn_client_public_ip: "xxx.xxx.xxx.xxx"
    vpn_shared_key: "someotherkey"

这在 Ansible 中可行吗?关于合并列表或字典的问题很多,但它们通常是关于添加更多项,而不是组合相同项的不同属性。

需要这个的原因是将共享密钥放在一个单独的保险库加密文件中(我知道我可以在同一个字典中内联加密,但不幸的是那不是一个选项)。

您可以使用 combine 过滤器执行此操作,如下所示:

---
- hosts: localhost
  gather_facts: false
  vars:
    vpns:
      example:
        vpn_connection_name: "example"
        vpn_client_public_ip: "xxx.xxx.xxx.xxx"
      example2:
        vpn_connection_name: "example2"
        vpn_client_public_ip: "xxx.xxx.xxx.xxx"
    vpn_credentials:
      example:
        vpn_shared_key: "somekey"
      example2:
        vpn_shared_key: "someotherkey"

  tasks:
    - set_fact:
        vpns_new: "{{ vpns|combine(vpn_credentials, recursive=true) }}"

    - debug:
        var: vpns_new

以上将输出:


PLAY [localhost] ******************************************************************************

TASK [set_fact] *******************************************************************************
ok: [localhost]

TASK [debug] **********************************************************************************
ok: [localhost] => {
    "vpns_new": {
        "example": {
            "vpn_client_public_ip": "xxx.xxx.xxx.xxx",
            "vpn_connection_name": "example",
            "vpn_shared_key": "somekey"
        },
        "example2": {
            "vpn_client_public_ip": "xxx.xxx.xxx.xxx",
            "vpn_connection_name": "example2",
            "vpn_shared_key": "someotherkey"
        }
    }
}

PLAY RECAP ************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0