VMware {code} Community
cmccvm
Contributor
Contributor

Get cluster name from VM with API via python script

I have a script to get a few details from VMware VSphere 6.0 on my VMs using a python script, but can't seem to find the cluster name anywhere with regards to a VM. My python script looks like this

from __future__ import print_function

import atexit

import creds

from pyVim.connect import SmartConnectNoSSL, Disconnect

from pyVmomi import vim

from tools import cli

MAX_DEPTH = 10

vm_info = []

def printvminfo(vm, depth=1):

    if hasattr(vm, 'childEntity'):

        if depth > MAX_DEPTH:

            return

        vmlist = vm.childEntity

        for child in vmlist:

            printvminfo(child, depth+1)

        return

   

    network = vm.network

    summary = vm.summary

    hardware = vm.config.hardware.device

  

    test = {}

    mac_addresses = []

    test['name'] = summary.config.name

    test['vCPU'] = summary.config.numCpu

    test['memory'] = summary.config.memorySizeMB

    test['IP'] = summary.guest.ipAddress

    for d in hardware:

        if hasattr(d, 'macAddress'):

            mac_addresses.append(d.macAddress)

        test['mac'] = mac_addresses

        if isinstance(d, vim.vm.device.VirtualDisk):

    #disk_gb = d.capacityInKB / 1024 / 1024

            test['disksizeGB'] = int((d.capacityInKB / 1024 / 1024))

    vm_info.append(test)

def get_vm_stuff():

    print(vm_info)

def main():

    si = None

 

    host = creds.host

    user = creds.user

    password = creds.password

    try:

        si = SmartConnectNoSSL(host=host,

                               user=user,

                               pwd=password)

        atexit.register(Disconnect, si)

    except vim.fault.InvalidLogin:

        raise SystemExit("Unable to connect to host "

                         "with supplied credentials.")

    content = si.RetrieveContent()

    for child in content.rootFolder.childEntity:

        if hasattr(child, 'vmFolder'):

            datacenter = child

            vmfolder = datacenter.vmFolder

            vmlist = vmfolder.childEntity

            for vm in vmlist:

                printvminfo(vm)

    get_vm_stuff()

if __name__ == "__main__":

    main()

Is there anyway I can return the cluster name for a VM from the vmFolder directory?

Reply
0 Kudos
0 Replies