I've got some variables:
vars:
foo:
- {name: "bar", path: "/tmp"}
- {name: "zob" }
default: "/home"
I'd like to make json_query that extracts name and path, and when path is not defined takes a default value.
The result I would like is
- {name: "bar", path: "/tmp"}
- {name: "zob", path: "/home"}
Is there a possiblity in json_query to defined a default value when the key is not defined?
Thanks, Raoul
The following will merge every elements of your list with a default hash map overiding existing values if redefined using the merge
jmespath function. This works for the path
in the example but you can add more mappings if needed.
---
- hosts: localhost
gather_facts: false
vars:
foo:
- {name: "bar", path: "/tmp"}
- {name: "zob" }
foo_defaults:
path: "/home"
tasks:
- debug:
msg: "{{ foo | json_query(query) }}"
vars:
query: >-
[].merge(`{{ foo_defaults | to_json }}`, @)
Which gives
PLAY [localhost] ***********************************************************************************************************************************************************************************************************************
TASK [debug] ***************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": [
{
"name": "bar",
"path": "/tmp"
},
{
"name": "zob",
"path": "/home"
}
]
}
PLAY RECAP *****************************************************************************************************************************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0