Home > OS >  Count number of json objects in output
Count number of json objects in output

Time:10-07

I am using Ansible's vmware_cluster_info to give the following json. I need to be able to count the number of hosts in a cluster. Cluster names will change.

                                                                                                                {
"ansible_facts": {
    "discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"clusters": {
    "Cluster1": {
        "drs_default_vm_behavior": "fullyAutomated",
        "ha_restart_priority": [
            "medium"
        ],
        "ha_vm_failure_interval": [
            50
        ],
        "ha_vm_max_failure_window": [
            0
        ],
        "ha_vm_max_failures": [
            10
        ],
        "ha_vm_min_up_time": [
            90
        ],
        "ha_vm_monitoring": "vmMonitoringOnly",
        "ha_vm_tools_monitoring": [
            "vmAndAppMonitoring"
        ],
        "hosts": [
            {
                "folder": "/Datacenter/host/Cluster1",
                "name": "host1"
            },
            {
                "folder": "/Datacenter/host/Cluster1",
                "name": "host2"
            },
            {
                "folder": "/Datacenter/host/Cluster1",
                "name": "host3"
            },
            {
                "folder": "/Datacenter/host/Cluster1",
                "name": "host4"
            }
        ],
        "resource_summary": {
            "cpuCapacityMHz": 144000,
        },
        "tags": [],
        "vsan_auto_claim_storage": false
    }
},
"invocation": {
    "module_args": {
        "cluster_name": "Cluster1",
    }
}

}

I have tried:

- debug:
    msg: "{{ cluster_info.clusters.[].hosts.name | length }}"

- debug:
    msg: "{{ cluster_info.clusters.*.hosts.name | length }}"

Both give me template error while templating string... Also, any suggestions on tutorials, etc to learn how to parse json would be appreciated. It seems to be a difficult topic for me. Any ideas?

CodePudding user response:

one similar approach to what you were trying is by using json_query. I understand you want to print the count of hosts, so the .name is not needed in your code:

  - name: print count of hosts
    debug:
      var: cluster_info.clusters | json_query('*.hosts') | first | length

json_query returns a list, this is why we pass it to first before length.

  • Related