【问题标题】:Merging Ansible dictionaries合并 Ansible 字典
【发布时间】:2020-12-28 01:01:01
【问题描述】:

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

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 可以做到这一点吗?关于合并列表或字典有很多问题,但它们通常是关于添加更多项目,而不是组合相同项目的不同属性。

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

【问题讨论】:

    标签: dictionary merge ansible jinja2


    【解决方案1】:

    您可以使用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   
    
    

    【讨论】:

    • 完美,谢谢!我会试一试,看看我怎么走。
    • 完美运行!再次感谢。
    猜你喜欢
    • 2014-10-14
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2010-12-28
    • 1970-01-01
    相关资源
    最近更新 更多