arnoutvh
arnoutvh

Reputation: 161

How to modify an existing dictionary in ansible?

I'm trying to add an existing list to an existing dict in Ansible.

I have a dict "jbossvars" containing the following (ansible debug)

"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": [
    "/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"

"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

Upvotes: 0

Views: 202

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67959

To get the result

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"
    ]
}

Upvotes: 2

Related Questions