vivekyad4v
vivekyad4v

Reputation: 14853

Ansible dictionary inside list - get keys and values of the dictionary

I have an ansible playbook with variable value as below -

"instances": [
    {
        "architecture": "x86_64",
        "tags": {
            "A": "B",
            "C": "D"
        }
    },
    {
        "architecture": "x86",
        "tags": {
            "A": "X",
            "G": "D"
        }
    }
]

Instances list is dynamic and #values may vary on each run.

I want to -

  1. Get the value of key "architecture" if we have tag key "A" present for the whole list.
  2. Get the value of key "architecture" if we have tag value "D" present for the whole list.

I tried with_subelements but no luck since it expects a list.

Upvotes: 2

Views: 4251

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

The first task can be achieved with pure Jinja, the second one requires some JMESPath.

- name: List archs with tag A present
  debug:
    msg: >-
      {{ instances
         | selectattr('tags.A','defined')
         | map(attribute='architecture')
         | list
         | unique
      }}

- name: List archs with any tag set to D
  debug:
    msg: >-
      {{ instances
         | json_query('[?contains(values(tags),`D`)]')
         | map(attribute='architecture')
         | list
         | unique
      }}

Upvotes: 5

Related Questions