pythonvmwarevmware-toolspyvmomi

Get vmId via pyVmomi


Currently Im using vim-cmd to perform multiple operations in my VMware center.

I'm using SSH paramiko module to connect and retrieve vim-cmd command status:

vim-cmd vmsvc/getallvms
vim-cmd vmsvc/power.getstate 13
vim-cmd vmsvc/power.on 13
vim-cmd vmsvc/power.off 13
vim-cmd vmsvc/destroy 13

I want to use pyVmomi library to run some commands and for this it is required to provide the vmId identifier:

from pyvim import connect
from pyVmomi import vim
from pyVmomi import vmodl

vim-cmd vmsvc/get.summary 13
Listsummary:

(vim.vm.Summary) {
   dynamicType = <unset>, 
   vm = 'vim.VirtualMachine:13', 

What command can I use to get the vmId?


Solution

  • What you are calling the vmid is called a ManagedObjectReference or mor, or a moref (within the context of the vSphere Web services API). With pyVmomi there are a couple of ways to get the moref. One is to just print the object. That method will print the moref in a format such that it gives the ManagedObjectType:moref like below. Another way if you just want the actual moref you can access vm._moId. Below is an example using a Datacenter object.

    from pyVim.connect import SmartConnect
    from pyVmomi import vim
    si = SmartConnect(host='10.12.254.137', user='administrator@vsphere.local', pwd='password')
    content = si.RetrieveContent()
    children = content.rootFolder.childEntity
    for child in children:
        print child
    
    'vim.Datacenter:datacenter-33'
    'vim.Datacenter:datacenter-2'
    children[0].name
    '1000110'
    dc = vim.Datacenter('datacenter-33')
    dc._stub = si._stub
    dc.name
    '1000110'
    

    If you want to access an Object using its moref then follow the example I provided. I covered this on my blog here about a year or so ago. You might check out that article for a more in depth explanation.