Search code examples
jsonansiblejmespath

Select mid-level attribute from JMESPATH expression


I am trying to select the cluster name for a specific virtual machine using Ansible's json_query which uses JMESPATH in the backend. I have followed the tutorial and examples at http://jmespath.org but am unable to construct the correct query.

My datastructure is as follows:

{
"datacenters": [
  {
  "name": "dc-a",
  "clusters": [
    { "name": "cluster-a",

      "hosts": [
        {
          "name": "host-a",
          "vms": [
            {
              "name": "vm-a",
              "summary": {
                "mem": "8",
                "diskGB": "78.00",
                "annotation": "",
                "state": "poweredOn",
                "ostype": "Microsoft Windows Server 2008 R2 (64-bit)",
                "cpu": "2"
              }
            },
            {
              "name": "vm-b",
              "summary": {
                "mem": "24",
                "diskGB": "114.00",
                "annotation": "",
                "state": "poweredOn",
                "ostype": "Microsoft Windows Server 2008 R2 (64-bit)",
                "cpu": "4"
              }
            }]
        }]
    }]
 }]
}

I am able to select the VM ('vm-a') using the query below but I am looking for the cluster (i.e. 'cluster-a').

datacenters[].clusters[].hosts[].vms[?name=='vm-a'].name[] 

Solution

  • datacenters[].clusters[?contains(hosts[].vms[].name, 'vm-a')].name[]