Get the value from the dict in JSON output stored in a variable

39 views Asked by At
{
  "changed": false,
  "clusters": {
    "ADC_CORE4": {
      "enable_ha": true,
      "ha_failover_level": 2,
      "ha_vm_monitoring": "vmMonitoringDisabled",
      "datacenter": "ADC_AI"
    }
  }
}

this is the output and ADC_CORE4 this is the cluster value which keep on changing. how to get the datacenter value in an variable using set_facts in ansible.

#i stored the output as cluster_info. and tried to get the datacenter value using :

- name: get the datacenter value
    msg: "datacenter : {{ cluster_info.clusters.ADC_CORE4.datacenter }}"

but ADC_CORE4 is not constant value it keep on changing. so i cant use it in automation of deploying #the vm. so need help on how to get the datacenter value in an variable.

1

There are 1 answers

3
Vladimir Botka On

Given the dictionary (equivalent in YAML for better readability):

    cluster_info:
      changed: false
      clusters:
        ADC_CORE4:
          datacenter: ADC_AI
          enable_ha: true
          ha_failover_level: 2
          ha_vm_monitoring: vmMonitoringDisabled

Q: "Get the datacenter value in a variable using set_fact. The name of cluster(s) may vary."

A: Use the filter json_query

    - set_fact:
        datacenter: "{{ cluster_info.clusters |
                        json_query('*.datacenter') }}"

gives a list because there might be more clusters

  datacenter:
  - ADC_AI

In this particular case, take the first item

    - set_fact:
        datacenter: "{{ cluster_info.clusters |
                        json_query('*.datacenter') |
                        first }}"

gives

  datacenter: ADC_AI