In Ansible how do you change a existing dictionary

2019-07-25 15:56发布

问题:

As the title suggest i want to loop over an existing dictionary and change some values, based on the answer to this question i came up with the code below but it doesn't work as the values are unchanged in the second debug call, I'm thinking it is because in the other question they are creating a new dictionary from scratch, but I've also tried it without the outer curly bracket which i would have thought would have caused it to change the existing value.

- set_fact:
  uber_dict:
    a_dict:
      some_key: "abc"
      another_key: "def"
    b_dict:
      some_key: "123"
      another_key: "456"

- debug: var="uber_dict"

- set_fact: "{ uber_dict['{{ item }}']['some_key'] : 'xyz' }"
  with_items: "{{ uber_dict }}"

- debug: var="uber_dict"

回答1:

You can not change existing variable, but you can register new one with the same name.

Check this example:

---
- hosts: localhost
  gather_facts: no
  vars:
    uber_dict:
      a_dict:
        some_key: "abc"
        another_key: "def"
      b_dict:
        some_key: "123"
        another_key: "456"
  tasks:
    - set_fact:
        uber_dict: "{{ uber_dict | combine(new_item, recursive=true) }}"
      vars:
        new_item: "{ '{{ item.key }}': { 'some_key': 'some_value' } }"
      with_dict: "{{ uber_dict }}"
    - debug:
        msg: "{{ uber_dict }}"

result:

ok: [localhost] => {
    "msg": {
        "a_dict": {
            "another_key": "def",
            "some_key": "some_value"
        },
        "b_dict": {
            "another_key": "456",
            "some_key": "some_value"
        }
    }
}