Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific key/value from a nested dictionary based on another key/value

Tags:

ansible

Just started working with Ansible and JSON dictionary data. I am trying to process the following dictionary using a jmesquery:

{
  "Entities": [
    {
      "MetaData": {
        "NumDiscoveredWorkloads": 20,
        "NumMigratedWorkloads": 1,
        "UUID": "uuid1234567890"
      },
      "Spec": {
        "Type": "VMWARE_ESXI_VCENTER",
        "UUID": "uuid1234567890"
      }
    },
    {
      "MetaData": {
        "NumDiscoveredWorkloads": 40,
        "UUID": "uuid1234567891"
      },
      "Spec": {
        "Type": "AOS_PC",
        "UUID": "uuid1234567891"
      }
    }
  ],
  "MetaData": {
    "Count": 2
  }
}

I want to find the value for the UUID of the ESXi item. I created the following Ansible code:

- name: "Get ESXiUUID"
  var:
    jmesquery: "Entities[*].Spec[?Type==`VMWARE_ESXI_VCENTER`].UUID"
  set_fact:
    move_providers_filtered: "{{ move_providers_details_content | json_query(jmesquery) }}"

But this does not work. I get strange errors from Ansible. Been checking the web for a day now, but nothing I tried solves the error. Can anybody tell me what I am doing wrong and how to solve this? Thanks for any support

like image 578
Marc Avatar asked Aug 28 '26 20:08

Marc


1 Answers

Given the data

  providers:
    Entities:
      - MetaData:
          NumDiscoveredWorkloads: 20
          NumMigratedWorkloads: 1
          UUID: uuid1234567890
        Spec:
          Type: VMWARE_ESXI_VCENTER
          UUID: uuid1234567890
      - MetaData:
          NumDiscoveredWorkloads: 40
          UUID: uuid1234567891
        Spec:
          Type: AOS_PC
          UUID: uuid1234567891

The query below

  provider: "{{ providers.Entities|json_query(jmesquery) }}"
  jmesquery: "[].Spec | [?Type==`VMWARE_ESXI_VCENTER`].UUID"

gives

  provider:
  - uuid1234567890

Example of a complete playbook for testing

- hosts: localhost

  vars:

    providers:
      Entities:
      - MetaData:
          NumDiscoveredWorkloads: 20
          NumMigratedWorkloads: 1
          UUID: uuid1234567890
        Spec:
          Type: VMWARE_ESXI_VCENTER
          UUID: uuid1234567890
      - MetaData:
          NumDiscoveredWorkloads: 40
          UUID: uuid1234567891
        Spec:
          Type: AOS_PC
          UUID: uuid1234567891

    provider: "{{ providers.Entities|json_query(jmesquery) }}"
    jmesquery: "[].Spec | [?Type==`VMWARE_ESXI_VCENTER`].UUID"

  tasks:

    - debug:
        var: provider
like image 122
Vladimir Botka Avatar answered Aug 30 '26 17:08

Vladimir Botka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!