Using Key(@) function to extract keys from an object in Ansible

Issue

I have a file file.sub which contains this JSON object {"kas_sub.test1": "true", "kas_sub.test2": "true"}. I would extract the keys and to get this: kas_sub.test1 kas_sub.test1.
When i try

- shell: 'cat path/to/file.sub'
  register: file1
- debug:
    var: file1.stdout_lines

I got:

TASK [shell] *****************************************************************************************************************
changed: [ansible4]
changed: [control]

TASK [debug] *****************************************************************************************************************
ok: [control] => {
    "file1.stdout_lines": [
        "{\"kas_sub.tes1\": \"true\", \"kas_sub.test2\": \"true\"}"
    ]
}

So it’s not conserving the same JSON format because i would use the json_query filter.

     
- debug:
    msg: "{{ file1.stdout_lines| json_query(value1)}}"
  vars:
    value1: "@[?keys(@)]"

keys(@)function doesn’t return anything

ok: [control] => {
    "msg": ""
}

Solution


Given the file

shell> cat /tmp/file.sub 
{"kas_sub.test1": "true", "kas_sub.test2": "true"}


Use jq (if you can). For example, get the keys

    - command: jq 'keys' /tmp/file.sub
      register: result

and convert them to a list

keys: "{{ result.stdout|from_yaml }}"

gives

keys:
  - kas_sub.test1
  - kas_sub.test2


Example of a complete playbook

- hosts: localhost
  vars:
    keys: "{{ result.stdout|from_yaml }}"
  tasks:
    - command: jq 'keys' /tmp/file.sub
      register: result
    - debug:
        var: keys

Answered By – Vladimir Botka

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published