I'm querying an API using an example script I've made a few changes to from their documentation. The function I'm using looks like this
def info(vm, depth=1):
if hasattr(vm,'childEntity'):
if depth > MAX_DEPTH:
return
vms = vm.childEntity
for child in vms:
info(child, depth+1)
return
summary = vm.summary
hardware = vm.config.hardware.device
macs = []
print("Name : {}".format(summary.config.name))
print("No of vCPUs : {}".format(summary.config.numCpu))
print("Memory (Mb) : {}".format(summary.config.memorySizeMB))
print("IP Address : {}".format(summary.guest.ipAddress))
for hw in hardware:
if hasattr(hw, 'macAddress'):
macs.append(hw.macAddress)
print("MAC Addresses :{}".format(mac_addresses))
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)
if __name__ == "__main__":
main()
This will print out something like this
Name : vm1
No of vCPUs : 2
Memory (Mb) : 10000
IP Address : 127.0.0.1
MAC Addresses :['00:01:22:33:4a:b5']
Name : vm2
No of vCPUs : 2
Memory (Mb) : 10000
IP Address : 127.0.0.2
MAC Addresses :['00:01:12:33:4g:b9', '40:51:21:38:4t:b5', '00:01:88:55:6y:z1']
Name : vm3
No of vCPUs : 2
Memory (Mb) : 10000
IP Address : 127.0.0.3
MAC Addresses :['00:50:56:83:d0:10']
I'm trying to create a dictionary of the entire output with
test['name'] = summary.config.name
test['vCPU'] = summary.config.numCpu
test['memory'] = summary.config.memorySizeMB
test['IP'] = summary.guest.ipAddress
test['mac'] = mac_addresses
print(test)
But keep overwriting the dictionary so only one vm entry will print at a time rather than the entire output, so my output currently is
{'vCPU': 2, 'IP': '127.0.0.1', 'mac': ['00:01:22:33:4a:b5'], 'name': 'vm1', 'memory': 10000}
{'vCPU': 2, 'IP': '127.0.0.2', 'mac': ['00:01:12:33:4g:b9', '40:51:21:38:4t:b5', '00:01:88:55:6y:z1'], 'name': 'vm2', 'memory': 10000}
{'vCPU': 2, 'IP': '127.0.0.3', 'mac': ['00:50:56:83:d0:10'], 'name': 'vm3', 'memory': 10000}
Whereas I would like
{
{
'vCPU': 2,
'IP': '127.0.0.1',
'mac': ['00:01:22:33:4a:b5'],
'name': 'vm1',
'memory': 10000
},
{
'vCPU': 2,
'IP': '127.0.0.2',
'mac': ['00:01:12:33:4g:b9', '40:51:21:38:4t:b5', '00:01:88:55:6y:z1'],
'name': 'vm2',
'memory': 10000
}
{
'vCPU': 2,
'IP': '127.0.0.3',
'mac': ['00:50:56:83:d0:10'],
'name': 'vm3',
'memory': 10000
}
}
Is there a more efficient function/loop I could be using?