Python: list clusters, hosts and VMs
Just following on from my previous article (HERE) on using Python Pyvmomi SDK wrapper for the vSphere Web Services API this time I show you how to iterate through the Web Services API tree. In numerous posts and VMUG sessions, I have given dating back to 2007 I have discussed that the objects in vSphere Web API are laid out in a hierarchical tree. Probably using the same relationship that objects have inside the vCenter Database. Here is the current diagram form the Vmware documentation. At the root of the tree, there is a folder; it contains the datacenter object. Underneath the Datacenter object is several other folders containing related objects. One for hosts, one for VMs, one for Networks and one for Storage.
The objective of this posts Python script is to move down the left-hand side of the tree list each object and finally getting to a list of VMs. The script below assumes you have to use the setup for authenticating to vSphere as in the previous script (HERE) and only contains the difference of what we are trying to achieve this time.
content = si.RetrieveContent() # now loop through any object that is tagged as "rooFolder" for child in content.rootFolder.childEntity: if hasattr(child, 'hostFolder'): datacenter = child # first object will be a datacentre hostFolder = datacenter.hostFolder # now assign the datacenter to a hostfolder variable cluster = hostFolder.childEntity # childs of hosts folders are clusters print("Datacenter name: " + child.name) # now loop through the clusters object for clusterList in cluster: print(clusterList.name) if hasattr(clusterList, 'host'): #if a child is tagged is host loop through the child for host in clusterList.host: print(host.name) for vm in host.vm: # host.vm holds a list of vm associated to that host print(" VM name: " + vm.name)
You can see from this code that we first find the folder tagged as rootfolder. This contains the datacenter object. Which in turn contains a hostfolder object which in turn contains a computer resource folder (the cluster). Which in turn contains the Host objects. This is where we stop. But hold on arent’t we suppose to list the VMs too? Well the VM objects are actually in a different folder. We observed that last time. However each host as a parameter called host.vm which is a list just of the name of each VM that is associated with that particular host.
Next time we will see how we can build to lists of objects and compare them so we cannot only list up the the VMs but list there properties too.
Leave a Reply
You must be logged in to post a comment.