acin
acin

Reputation: 93

Ansible: Assign JSON value to a variable

I am using a custom facts module to get JSON back in Ansible 2.9

ok: [Host] => {
    "msg": {
        "changed": false,
        "failed": false,
        "msg": "Successfully completed the view storage volume operation",
        "storage_status": {
            "Message": {
                "Controller": {
                    "AHCI.Embedded.3-1": {},
                    "RAID.Integrated.1-1": {
                        "Enclosure": {
                            "Enclosure.Internal.0-1:RAID.Integrated.1-1": {
                                "PhysicalDisk": [
                                    "Disk.Bay.0:Enclosure.Internal.0-1:RAID.Integrated.1-1",
                                    "Disk.Bay.1:Enclosure.Internal.0-1:RAID.Integrated.1-1"
                                ]
                            }
                        },
                        "VirtualDisk": {
                            "Disk.Virtual.0:RAID.Integrated.1-1": {
                                "PhysicalDisk": [
                                    "Disk.Bay.0:Enclosure.Internal.0-1:RAID.Integrated.1-1",
                                    "Disk.Bay.1:Enclosure.Internal.0-1:RAID.Integrated.1-1"
                                ]
                            }
                        }
                    }
                }
            },
            "Status": "Success"
        }
    }
}

And I would like to assign "Disk.Virtual.0:RAID.Integrated.1-1" value to a variable using set_fact module. Using the following filter:

{{ disks['storage_status']['Message']['Controller']['RAID.Integrated.1-1']['VirtualDisk'] }}

I am able to just select the following:

ok : [Host] => {
        "msg": {
            "Disk.Virtual.0:RAID.Integrated.1-1": {
                "PhysicalDisk": [
                    "Disk.Bay.0:Enclosure.Internal.0-1:RAID.Integrated.1-1",
                    "Disk.Bay.1:Enclosure.Internal.0-1:RAID.Integrated.1-1"
                ]
            }
        }
    }

But I am unable to work out how to grab Disk.Virtual.0:RAID.Integrated.1-1 and assign it to the variable.

Any help/guidance will be greatly appreciated.

Thanks

Upvotes: 0

Views: 477

Answers (1)

Jack
Jack

Reputation: 6158

Use dict lookup with .key:

  - debug:
      msg: "{{ lookup('dict', disks['storage_status']['Message']['Controller']['RAID.Integrated.1-1']['VirtualDisk']).key }}"

Gives:

TASK [debug] *****************************************
ok: [localhost] => {
    "msg": "Disk.Virtual.0:RAID.Integrated.1-1"
}

To assign to a variable (my_var), use set_fact:

  - set_fact:
      my_var: "{{ lookup('dict', disks['storage_status']['Message']['Controller']['RAID.Integrated.1-1']['VirtualDisk']).key }}"

Upvotes: 1

Related Questions