Getting all your VMs with Affinity rules

Getting all your VMs with Affinity rules

So! Today i wanted to list all the VMs in our cluster that had any host affinity rules.  So, just for future reference here is a oneliner that you can run from any PC CVM

First we take a look at the nuclei command vm_host_affinity_legacy_policy.list

It gives a JSON output like this

"Total Entities : 27"
"Length : 27"
"Offset : 0"
"Entities :"
{
  "message": {
    "entities": [
      {
        "config": {
          "host_reference_list": [
            {
              "kind": "host",
              "name": "AVH-HOST-A",
              "uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
            },
            {
              "kind": "host",
              "name": "AVH-HOST-B",
              "uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
            },
            {
              "kind": "host",
              "name": "AVH-HOST-C",
              "uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
            },
            {
              "kind": "host",
              "name": "AVH-HOST-D",
              "uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
            }
          ],
          "vm_reference": {
            "kind": "vm",
            "name": "VirtualMachine01",
            "uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
          }
        },
        "metadata": {
          "uuid": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx"
        }
      },

As you can se, the response is in JSON format. And to read trough all the entities in this format can be challenging. So we ned to format the output. We're only intressted in the message.entities.config.vm_reference.name value, and display that value for each entry in the list.

Below Oneliner will provide us with the output that we're looking for.

nuclei vm_host_affinity_legacy_policy.list | grep -A 5 '"vm_reference":' | grep '"name":' | awk -F'"' '{print $4}'

The response will look something like this:

nutanix@NTNX-PCVM:~$ nuclei vm_host_affinity_legacy_policy.list | grep -A 5 '"vm_reference":' | grep '"name":' | awk -F'"' '{print $4}'
2023/08/18 08:09:21 Connected to x.x.x.x:9876
2023/08/18 08:09:21 Authenticating connection 0x0
2023/08/18 08:09:21 nuclei is attempting to connect to Zookeeper
2023/08/18 08:09:21 Authenticated: id=0x0000000, timeout=20000
VirtualMachine01
VirtualMachine02
VirtualMachine03
VirtualMachine04
VirtualMachine05
VirtualMachine06
VirtualMachine07
VirtualMachine08
VirtualMachine09
VirtualMachine10
VirtualMachine11
VirtualMachine12
VirtualMachine13
VirtualMachine14
VirtualMachine15
VirtualMachine16
VirtualMachine17
VirtualMachine18
VirtualMachine19
VirtualMachine20
VirtualMachine21
VirtualMachine22
VirtualMachine23
VirtualMachine24
VirtualMachine25
VirtualMachine26
VirtualMachine27
Output

I hope this can help someone out there :) thanks for reading!