Search code examples
pythonvmwarevsphere

Where are virtual switches kept in vSphere? (through pyVmomi)


I have a number of virtual portgroups on a virtual switch. When I execute

datacenters = si.RetrieveContent().rootFolder.childEntity
for datacenter in datacenters:
    hosts = datacenter.hostFolder.childEntity
    for host in hosts:
        networks = host.network
        for network in networks:
             print network.name

(si is a service instance) I get all the vlans (portgroups) on the network, but none of the switches (which the docs claim should be in the network directory). Given that folders also have the name attribute, any folders that I looked over should have been printed. So where does vsphere/vcenter keep these switches?


Solution

  • To retrieve vSwitches with pyVmomi you can do:

    def _get_vim_objects(content, vim_type):
        '''Get vim objects of a given type.'''
        return [item for item in content.viewManager.CreateContainerView(
            content.rootFolder, [vim_type], recursive=True
        ).view]
    
    content = si.RetrieveContent()
    for host in self._get_vim_objects(content, vim.HostSystem):
        for vswitch in host.config.network.vswitch:
            print(vswitch.name)
    

    Result would be:

    vSwitch0
    vSwitch1
    vSwitch2
    

    To retrieve Distributed vSwitches you can use the _get_vim_objects function (above) with vim_type=vim.dvs.VmwareDistributedVirtualSwitch parameter.