Is there a function to update values in a json in Ansible?

Viewed 91

I have a playbook to update the values in a json file:

- hosts: localhost
  connection: local
  gather_facts: false
  vars:

  tasks:
  - name: load var from file
    include_vars:
      file: ./test1.json
      name: imported_var
      
  - name: update object
    set_fact:
      imported_var: "{{ imported_var | default({}) | combine({'test3': 'good'}) }}"

  - debug:
      var: imported_var

and the input json file like is:

{
    "test1": 1,
    "test2": {
        "test3": 3,
        "test4": 4
    },
    "test5": 5
}

The expected result is, that test3's value is updated to 'good' like this:

{
    "test1": 1,
    "test2": {
        "test3": "good",
        "test4": 4
    },
    "test5": 5
}

but I got this results:

ok: [localhost] => {
    "imported_var": {
        "test1": 1,
        "test2": {
            "test3": 3,
            "test4": 4
        },
        "test3": "good",
        "test5": 5
    }
} 

What am I doing wrong?

1 Answers

Your code currently modifies the parent-dictionary, but you want to modify the the dictionary in "test2". To do that, you need to do this:

  - name: update object
    set_fact:
      new_var: "{{ imported_var['test2'] | default({}) | combine({'test3': 'good'}) }}"

  - debug:
      var: new_var

If you are interested in the whole imported dictionary, you can do it like this:

  - name: update object
    set_fact:
      new_var: "{{ imported_var | default({}) | combine({'test2': {'test3': 'good'}}, recursive=true) }}"

  - debug:
      var: new_var
Related