Add a new key-value to a json file using Ansible explains how to load the remote json, but this method overwrites the existing nested dictionary, so you end up with this on the remote server:
{
"foo": {
"val2": "newvalue",
}
}
how to modify multiple values in deep dictionary in ansible explains how to modify key-value pairs, but assumes you already have the json available. It also doesn't explain how to write out the file to the remote location.
Combining both solutions:
- name: load foobar.json
slurp:
src: /path/to/foobar.json
register: imported_json
- debug:
msg: "{{ imported_json.content|b64decode|from_json }}"
- name: modify individual key-value
set_fact:
imported_json: "{{ imported_json.content|b64decode|from_json | combine(item, recursive=True)}}"
loop:
- { 'settings': { 'val2': 'newvalue' }}
- debug:
var: imported_json.foo.val2
- name: write updated foobar.json to file
copy:
content: "{{ imported_json | to_nice_json }}"
dest: /path/to/foobar.json
And I get the result I want on the remote server:
{
"foo": {
"val1": "bar1",
"val2": "newvalue",
}
}