1

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

Raoul Debaze
  • 466
  • 1
  • 8
  • 24
  • 1
    Instead of defining the default in the variables part, you can use define it in the code part, using defaullt values. but depends of the use-case, which is not fully explained here. If you want specific answer, edit the question and provide more information. Best – Baptiste Mille-Mathias Jun 26 '20 at 17:13

1 Answers1

2

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  
Zeitounator
  • 38,476
  • 7
  • 53
  • 66