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

时间:2019-06-19 09:29:10

标签: list dictionary ansible

我正在尝试将现有列表添加到Ansible中的现有字典中。

我有一个字典“ jbossvars”,其中包含以下内容(可调试)

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

以及包含以下内容(可调试)的列表“ env_homes”

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

我想将其合并为新词典“ 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"
        }
    }
}

以下游戏没有没有给我想要的情况:

- 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

1 个答案:

答案 0 :(得分:2)

获得结果

  

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

下面的戏

  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

给予

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