简体   繁体   English

如何在ansible中修改现有字典?

[英]How to modify an existing dictionary in ansible?

I'm trying to add an existing list to an existing dict in Ansible. 我正在尝试将现有列表添加到Ansible中的现有字典中。

I have a dict "jbossvars" containing the following (ansible debug) 我有一个字典“ jbossvars”,其中包含以下内容(可调试)

"jbossvars": {
    "environments": {
        "TEST_ENV": {
            "key1": "value1",
            "key2": "value2"
        },
        "TEST_ENV2": {
            "key1": "value1",
            "key2": "value2"
        }
    }
}

and a list "env_homes" containing the following (ansible debug) 以及包含以下内容(可调试)的列表“ env_homes”

"env_homes": [
    "/opt/redhat/jboss-7.2.0/TEST_ENV",
    "/opt/redhat/jboss-7.2.0/TEST_ENV2"
]

which I want to combine to a new dictionary "new_dict" 我想将其合并为新词典“ new_dict”

"jbossvars": {
    "environments": {
        "TEST_ENV": {
            "key1": "value1",
            "key2": "value2",
            "key3": "/opt/redhat/jboss-7.2.0/TEST_ENV"
        },
        "TEST_ENV2": {
            "key1": "value1",
            "key2": "value2",
            "key3": "/opt/redhat/jboss-7.2.0/TEST_ENV2"
        }
    }
}

The following play does not give me the desired situation: 以下游戏不能给我期望的情况:

- name: Create dict to append 
  set_fact: 
    env_homes: "{{ {'TEST_ENV': [ jbossvars.environments.TEST_ENV ] + env_homes} }}" 
- name: Insert created dict into existing dict and save it into a new variable newdict 
  set_fact: 
    newdict: "{{ jbossvars.environments|combine(env_homes) }}" 
- debug: var: newdict

To get the result 得到结果

TEST_ENV: { "a": 1, "b": [ 2, "x1", "x2" ] } TEST_ENV:{“ a”:1,“ b”:[2,“ x1”,“ x2”]}

The play below 下面的戏

  vars:
    TEST_ENV:
      a: 1
      b: 2
    add_this:
      c: [ x1, x2 ]
  tasks:
    - set_fact:
        add_this: "{{ {'b': [ TEST_ENV.b ] + add_this.c} }}"
    - set_fact:
        TEST_ENV: "{{ TEST_ENV|combine(add_this) }}"
    - debug:
        var: TEST_ENV

gives

"TEST_ENV": {
    "a": 1, 
    "b": [
        2, 
        "x1", 
        "x2"
    ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM