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

Time:08-04

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": ""
}

CodePudding user response:

note: taking for granted you want to read a file on the target machine


In a nutshell:

- hosts: your_group
  gather_facts: false

  vars:
    file_to_read: /path/to/file.sub

  tasks:
    - name: slurp file content from target
      slurp:
        src: "{{ file_to_read }}"
      register: slurped_file

    - name: display keys from json inside file
      debug:
        msg: "{{ (slurped_file.content | b64decode | from_json).keys() }}" 

CodePudding user response:

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
  • Related