pyvmomi to retrieve custom attribute "owner" for all VMs

1.7k Views Asked by At

I'm trying (and failing) to figure out how to use pyvmomi to retrieve a custom attribute named "owner" for all VMs in a vCenter.

I use code like this to retrieve VM name, power state, and uuid:

summary = vm.summary print(summary.config.name, " ", summary.runtime.powerState, " summary.config.uuid)

But, I cannot figure out how to retrieve the custom attribute named "owner" for all VMs in a vCenter.

Thanks in advance

1

There are 1 best solutions below

3
On

CustomAttribute is stored separately in customValue field. Each customValue have its name and key, the "Owner" in your case is the name, you need to get its key first.

here is a sample:

conn=connect.SmartConnect(host='***', user='***',  pwd='***', port=443)
content = conn.RetrieveContent()
cfm = content.customFieldsManager
required_field = ["Owner"]
my_customField = {}
for my_field in cfm.field:
    if my_field.name in required_field:
        my_customField[my_field.key]=my_field.name

The key and its display name is in my_customField dict, you can get customValue by it

for opts in vm.customValue:
    if opts.key in my_customField:
        output[my_customField[opts.key]]=opts.value

and in output dict you have what you want.