How to get the value from key `datacenter` from a JSON output which is stored in an variable?

46 Views Asked by At

From this YAML output I need to get the datacenter value in a variable.

changed: "false"
clusters: 
  ADC_CORE4: 
    hosts: 
    - name: "b125.abc.com"
      folder: "/ADC_3C/host/ADC_CORE4"
    enable_ha: "true"
    ha_failover_level: "2"
    resource_summary: 
      cpuCapacityMHz: "2183328"
      cpuUsedMHz: "71374"
    moid: "test"
    datacenter: "ADC_AI"

But the key ADC_CORE4 is not stable and changes on every output I get when the cluster changes.

I like to get the datacenter value from this output and trying to use it in deployment of VM.

2

There are 2 best solutions below

0
larsks On

Assuming that your example YAML data is the content of a variable myvariable, you can get the datacenter value like this:

(myvariable.clusters.values()|list).0.datacenter

The values() method returns a list of values; since there's only a single value, we just grab the first item in the list and then ask for the datacenter attribute.

For example:

- hosts: localhost
  gather_facts: false
  vars:
    myvariable:
      changed: "false"
      clusters: 
        ADC_CORE4: 
          hosts: 
          - name: "b125.abc.com"
            folder: "/ADC_3C/host/ADC_CORE4"
          enable_ha: "true"
          ha_failover_level: "2"
          resource_summary: 
            cpuCapacityMHz: "2183328"
            cpuUsedMHz: "71374"
          moid: "test"
          datacenter: "ADC_AI"

  tasks:
    - debug:
        msg: "datacenter: {{ (myvariable.clusters.values()|list).0.datacenter }}"
0
U880D On

An other approach than

  - debug:
      msg: "{{ (cluster_info.clusters.values() | list | first).datacenter }}"

but with bracket notation is

  - debug:
      msg: "{{ cluster_info.clusters[(result.clusters.keys() | first)]['datacenter'] }}"

A minimal example playbook

- hosts: localhost
  gather_facts: false

  vars:

    cluster_info:
      changed: "false"
      clusters:
        ADC_CORE4:
          hosts:
          - name: "b125.abc.com"
            folder: "/ADC_3C/host/ADC_CORE4"
          enable_ha: "true"
          ha_failover_level: "2"
          resource_summary:
            cpuCapacityMHz: "2183328"
            cpuUsedMHz: "71374"
          moid: "test"
          datacenter: "ADC_AI"

  tasks:

  - debug:
      msg: "{{ (cluster_info.clusters.values() | list | first).datacenter }}"

  - debug:
      msg: "{{ cluster_info.clusters[(result.clusters.keys() | first)]['datacenter'] }}"

will result for any clusters.NAME or clusters['NAME'] into an output of

TASK [debug] *****
ok: [localhost] =>
  msg: ADC_AI

TASK [debug] *****
ok: [localhost] =>
  msg: ADC_AI


Also possible and probably the more simple one is Selecting JSON data: JSON queries as shown in your

Duplicate Q&A