Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extracting data from nested dict in ansible with conditional checks in the list?

I’m stuck with the following issue.
My JSON data looks like this:

[
   {
      "clusters":[
         {
            "id":"1",
            "name":"cluster1"
         },
         {
            "id":"2",
            "name":"cluster2"
         }
      ],
      "tag":"a"
   },
   {
      "clusters":[
         {
            "id":"3",
            "name":"cluster2"
         }
      ],
      "tag":"b"
   }
]

What I am trying to do is extracting the tag values which are connected to a certain cluster (say, cluster1). So, I need to check if cluster1 is in the list of clusters[*].name somehow.

Here is my playbook:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

- name: "Test"
  hosts: localhost
  gather_facts: False

  vars:
  - test:
        - clusters:
            - name: "cluster1"
              id: "1"
            - name: "cluster2"
              id: "2"
          tag: "a"
        - clusters:
            - name: "cluster2"
              id: "3"
          tag: "b"

  - set_fact:
      tags_test: "{{ test | community.general.json_query('[?clusters[].name==`cluster1`].tag') }}"

  - debug:
      msg: "{{ tags_test }}"

What I am expecting to get is the tag value: "a".

This is the result:

TASK [debug] ******************************************************
ok: [localhost] => {
    "msg": []
}

I also tried combining json_query with selectattr, but, no luck.

>Solution :

With JMESPath you have to nest your conditions because you are looking for an object named cluster1 inside the the JSON array clusters which is nested in another array:

[?clusters[?name==`cluster1`]].tag|[0]

So as a task,

- set_fact:
    tags_test: >-
      {{ test | community.general.json_query(
           '[?clusters[?name==`cluster1`]].tag|[0]'
      ) }}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading