Python pyVmomi.vim.Datacenter() Examples

The following are 30 code examples of pyVmomi.vim.Datacenter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyVmomi.vim , or try the search function .
Example #1
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def get_all_vms_in_dc(self, dc):
        """
        Fetches all VMs in Datacenter

        Args:
            dc (str): Datacenter name

        Returns:
            list: List of VMs instance in a Datacenter

        """
        vms = []
        dc = self.get_dc(dc)
        vmfolder = dc.vmFolder
        vmlist = vmfolder.childEntity
        for each in vmlist:
            if hasattr(each, 'childEntity'):
                for vm in each.childEntity:
                    vms.append(vm)
            else:
                # Direct VMs created in cluster
                # This are the VMs created directly on cluster
                # without ResourcePool
                vms.append(each)
        return vms 
Example #2
Source File: __init__.py    From kcli with Apache License 2.0 6 votes vote down vote up
def report(self):
        si = self.si
        about = si.content.about
        print("Host: %s" % self.vcip)
        print("Datacenter: %s" % self.dc.name)
        print("Version: %s" % about.version)
        print("Api Version: %s" % about.apiVersion)
        print("Datacenter: %s" % self.dc.name)
        rootFolder = self.rootFolder
        o = si.content.viewManager.CreateContainerView(rootFolder, [vim.HostSystem], True)
        view = o.view
        o.Destroy()
        for h in view:
            print("Host: %s" % h.name)
        o = si.content.viewManager.CreateContainerView(rootFolder, [vim.ComputeResource], True)
        view = o.view
        o.Destroy()
        for clu in view:
            print("Cluster: %s" % clu.name)
            for dts in clu.datastore:
                print("Pool: %s" % dts.name) 
Example #3
Source File: __init__.py    From kcli with Apache License 2.0 6 votes vote down vote up
def __init__(self, host, user, password, datacenter, cluster, debug=False, filtervms=False, filteruser=False,
                 filtertag=None):
        # 4-1-CONNECT
        si = connect.SmartConnect(host=host, port=443, user=user, pwd=password, sslContext=_create_unverified_context())
        self.conn = si
        self.si = si
        self.vcip = host
        self.url = "https://%s:%s@%s/sdk" % (user, password, host)
        self.rootFolder = si.content.rootFolder
        self.dc = find(si, self.rootFolder, vim.Datacenter, datacenter)
        self.macaddr = []
        self.clu = cluster
        self.distributed = False
        self.filtervms = filtervms
        self.filtervms = filtervms
        self.filteruser = filteruser
        self.filtertag = filtertag
        self.debug = debug
        return 
Example #4
Source File: vsphere_class.py    From ADLES with Apache License 2.0 6 votes vote down vote up
def get_info(self):
        """
        Retrieves and formats basic information about the vSphere instance.

        :return: formatted server information
        :rtype: str
        """
        about = self.content.about
        info_string = "\n"
        info_string += "Host address: %s:%d\n" % (self.hostname, self.port)
        info_string += "Datacenter  : %s\n" % self.datacenter.name
        info_string += "Datastore   : %s\n" % self.datastore.name
        info_string += "Full name   : %s\n" % about.fullName
        info_string += "Vendor      : %s\n" % about.vendor
        info_string += "Version     : %s\n" % about.version
        info_string += "API type    : %s\n" % about.apiType
        info_string += "API version : %s\n" % about.apiVersion
        info_string += "OS type     : %s" % about.osType
        return info_string 
Example #5
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def get_pool(self, name, dc, cluster):
        """
        Gets the Resource pool

        Args:
            name (str): Resource pool name
            dc (str): Datacenter name
            cluster (str): Cluster name

        Returns:
            vim.ResourcePool: Resource pool instance

        """
        cluster_obj = self.get_cluster(cluster, dc)
        for rp in cluster_obj.resourcePool.resourcePool:
            if rp.name == name:
                return rp 
Example #6
Source File: vsphere_class.py    From ADLES with Apache License 2.0 6 votes vote down vote up
def get_folder(self, folder_name=None):
        """
        Finds and returns the named Folder.

        :param str folder_name: Name of folder [default: Datacenter vmFolder]
        :return: The folder found
        :rtype: vim.Folder
        """
        if folder_name:  # Try to find the named folder in the datacenter
            return self.get_obj(self.datacenter, [vim.Folder], folder_name)
        else:  # Default to the VM folder in the datacenter
            # Reference: pyvmomi/docs/vim/Datacenter.rst
            self._log.warning("Could not find folder '%s' in Datacenter '%s', "
                              "defaulting to vmFolder",
                              folder_name, self.datacenter.name)
            return self.datacenter.vmFolder 
Example #7
Source File: folder.py    From vsphere-automation-sdk-python with MIT License 6 votes vote down vote up
def detect_vm_folder(context, datacenter_name, folder_name):
    """Find vm folder based on datacenter and folder name"""
    datacenter = datacenter_helper.get_datacenter(context.client,
                                                  datacenter_name)
    if not datacenter:
        print("Datacenter '{}' not found".format(datacenter_name))
        return None

    folder_summaries = context.client.vcenter.Folder.list(
        Folder.FilterSpec(type=Folder.Type.VIRTUAL_MACHINE,
                          names=set([folder_name]),
                          datacenters=set([datacenter])))
    if len(folder_summaries) > 0:
        folder = folder_summaries[0].folder
        print("Detected VM Folder '{}' as {}".format(folder_name, folder))
        context.testbed.entities['VM_FOLDER_IDS'][folder_name] = folder
        return True
    else:
        print("VM Folder '{}' missing in Datacenter {}".
              format(folder_name, datacenter_name))
        return False 
Example #8
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def destroy_pool(self, pool, dc, cluster):
        """
        Deletes the Resource Pool

        Args:
            pool (str): Resource pool name
            dc (str): Datacenter name
            cluster (str): Cluster name

        """
        vms_in_pool = self.get_all_vms_in_pool(pool, dc, cluster)
        logger.info(f"VM's in resource pool {pool}: {[vm.name for vm in vms_in_pool]}")
        self.destroy_vms(vms_in_pool)

        # get resource pool instance
        pi = self.get_pool(pool, dc, cluster)
        WaitForTask(pi.Destroy())
        logger.info(f"Successfully deleted resource pool {pool}") 
Example #9
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def check_folder_exists(self, name, cluster, dc):
        """
        Checks whether folder exists in Templates

        Args:
            name (str): Folder name
            cluster (str): Cluster name
            dc (str): Datacenter name

        Returns:
            bool: True if folder exists, False otherwise

        """
        _rc = False
        dc = self.get_dc(dc)

        vms = dc.vmFolder.childEntity
        for vm in vms:
            if vm.name == name:
                _rc = True
        return _rc 
Example #10
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def destroy_folder(self, name, cluster, dc):
        """
        Removes the folder from Templates

        Args:
            name (str): Folder name
            cluster (str): Cluster name
            dc (str): Datacenter name

        """
        if self.check_folder_exists(name, cluster, dc):
            dc = self.get_dc(dc)
            vms = dc.vmFolder.childEntity
            for vm in vms:
                if vm.name == name:
                    for dvm in vm.childEntity:
                        self.poweroff_vms([dvm])
                    logger.info(f"Destroying folder {name} in templates")
                    WaitForTask(vm.Destroy())
        else:
            logger.info(f"Folder {name} doesn't exist in templates") 
Example #11
Source File: cluster.py    From vsphere-automation-sdk-python with MIT License 6 votes vote down vote up
def setup_cluster_vim(context):
    """Create a cluster using only the VIM API"""
    cluster1_name = context.testbed.config['CLUSTER1_NAME']

    # Get the host folder for the Datacenter2 using the save identifier
    datacenter_name = context.testbed.config['DATACENTER2_NAME']

    for entity in context.service_instance.content.rootFolder.childEntity:
        if isinstance(entity,
                      vim.Datacenter) and entity.name == datacenter_name:
            folder_mo = entity.hostFolder
            cluster_mo = folder_mo.CreateClusterEx(cluster1_name,
                                                   vim.cluster.ConfigSpecEx())

            print("Created Cluster '{}' ({})".format(cluster_mo._moId,
                                                     cluster1_name))

            context.testbed.entities['CLUSTER_IDS'] = {
                cluster1_name: cluster_mo._moId
            }
            break 
Example #12
Source File: cluster.py    From vsphere-automation-sdk-python with MIT License 6 votes vote down vote up
def setup_cluster_vapi1(context):
    """Create a cluster from the Datacenter managed object."""
    cluster1_name = context.testbed.config['CLUSTER1_NAME']

    # Get the host folder for the Datacenter2 using the save identifier
    datacenter_name = context.testbed.config['DATACENTER2_NAME']
    datacenter = context.testbed.entities['DATACENTER_IDS'][datacenter_name]

    # Create a managed object from the datacenter identifier
    datacenter_mo = vim.Datacenter(datacenter, context.soap_stub)

    # Using pyvmomi to get the host folder on which to create the cluster
    folder_mo = datacenter_mo.hostFolder
    cluster_mo = folder_mo.CreateClusterEx(cluster1_name,
                                           vim.cluster.ConfigSpecEx())

    print("Created Cluster '{}' ({})".format(cluster_mo._moId, cluster1_name))

    context.testbed.entities['CLUSTER_IDS'] = {
        cluster1_name: cluster_mo._moId
    } 
Example #13
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def find_datastore_by_name(self, datastore_name, datacenter_name):
        """
        Fetches the Datastore

        Args:
            datastore_name (str): Name of the Datastore
            datacenter_name (str): Name of the Datacenter

        Returns:
            vim.Datastore: Datastore instance

        """
        dc = self.find_datacenter_by_name(datacenter_name)
        folder = dc.datastoreFolder
        return self.find_object_by_name(
            self.get_content,
            datastore_name,
            [vim.Datastore],
            folder=folder
        ) 
Example #14
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def find_datacenter_by_name(self, datacenter_name):
        """
        Fetches the Datacenter

        Args:
            datacenter_name (str): Name of the Datacenter

        Returns:
            vim.Datacenter: Datacenter instance

        """
        return self.find_object_by_name(
            self.get_content,
            datacenter_name,
            [vim.Datacenter]
        ) 
Example #15
Source File: vsphere.py    From ocs-ci with MIT License 6 votes vote down vote up
def get_datastore_type_by_name(self, datastore_name, datacenter_name):
        """
        Gets the Datastore Type

        Args:
            datastore_name (str): Name of the Datastore
            datacenter_name (str): Name of the Datacenter

        Returns:
            str: Datastore type. Either VMFS or vsan

        """
        datastore = self.find_datastore_by_name(
            datastore_name,
            datacenter_name
        )
        return self.get_datastore_type(datastore) 
Example #16
Source File: run.py    From vcenter-netbox-sync with Apache License 2.0 6 votes vote down vote up
def create_view(self, vc_obj_type):
        """
        Create a view scoped to the vCenter object type desired.

        This should be called before collecting data about vCenter object types.
        :param vc_obj_type: vCenter object type to extract, must be key in vc_obj_views
        :type vc_obj_type: str
        """
        # Mapping of object type keywords to view types
        vc_obj_views = {
            "datacenters": vim.Datacenter,
            "clusters": vim.ClusterComputeResource,
            "hosts": vim.HostSystem,
            "virtual_machines": vim.VirtualMachine,
            }
        # Ensure an active vCenter session exists
        if not self.vc_session:
            log.info("No existing vCenter session found.")
            self.authenticate()
        return self.vc_session.viewManager.CreateContainerView(
            self.vc_session.rootFolder, # View starting point
            [vc_obj_views[vc_obj_type]], # Object types to look for
            True # Should we recurively look into view
            ) 
Example #17
Source File: nsxt_vcenter_moids.py    From ansible-module-chaperone with Apache License 2.0 6 votes vote down vote up
def find_object_by_name(module,content, object_name):
    try:
    	if(object_name == module.params['datacenter']):
    	    vmware_objects = get_all_objs(module,content,[vim.Datacenter])
    	elif (object_name == module.params['cluster']):
    	    vmware_objects = get_all_objs(module,content,[vim.ComputeResource])
    	elif (object_name == module.params['datastore']):
            vmware_objects = get_all_objs(module,content,[vim.Datastore])
    	elif (object_name == module.params['portgroup1'] or module.params['portgroup2'] or module.params['portgroup3'] ):
            vmware_objects = get_all_objs(module,content,[vim.dvs.DistributedVirtualPortgroup, vim.Network])
 
    	for object in vmware_objects:
            if object.name == object_name:
            	logger.info('object: %s',object.name)
            	return object
    	return None
    except Exception as err:
       module.fail_json(changed=False, msg= "Error Occured while Finding the Object by name. Error is %s" %(to_native(err))) 
Example #18
Source File: vmware_exporter.py    From vmware_exporter with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def datastore_labels(self):

        def _collect(node, level=1, dc=None, storagePod=""):
            inventory = {}
            if isinstance(node, vim.Folder) and not isinstance(node, vim.StoragePod):
                logging.debug("[Folder    ] {level} {name}".format(name=node.name, level=('-' * level).ljust(7)))
                for child in node.childEntity:
                    inventory.update(_collect(child, level + 1, dc))
            elif isinstance(node, vim.Datacenter):
                logging.debug("[Datacenter] {level} {name}".format(name=node.name, level=('-' * level).ljust(7)))
                inventory.update(_collect(node.datastoreFolder, level + 1, node.name))
            elif isinstance(node, vim.Folder) and isinstance(node, vim.StoragePod):
                logging.debug("[StoragePod] {level} {name}".format(name=node.name, level=('-' * level).ljust(7)))
                for child in node.childEntity:
                    inventory.update(_collect(child, level + 1, dc, node.name))
            elif isinstance(node, vim.Datastore):
                logging.debug("[Datastore ] {level} {name}".format(name=node.name, level=('-' * level).ljust(7)))
                inventory[node.name] = [node.name, dc, storagePod]
            else:
                logging.debug("[?         ] {level} {node}".format(node=node, level=('-' * level).ljust(7)))
            return inventory

        labels = {}
        dcs = yield self.datacenter_inventory
        for dc in dcs:
            result = yield threads.deferToThread(lambda: _collect(dc))
            labels.update(result)

        return labels 
Example #19
Source File: vm_listener.py    From vsphere-storage-for-docker with Apache License 2.0 6 votes vote down vote up
def vm_folder_traversal():
    """
    Build the traversal spec for the property collector to traverse vmFolder
    """

    TraversalSpec = vmodl.query.PropertyCollector.TraversalSpec
    SelectionSpec = vmodl.query.PropertyCollector.SelectionSpec

    # Traversal through vmFolder branch
    dcToVmf = TraversalSpec(name='dcToVmf', type=vim.Datacenter, path='vmFolder', skip=False)
    dcToVmf.selectSet.append(SelectionSpec(name='visitFolders'))

    # Recurse through the folders
    visitFolders = TraversalSpec(name='visitFolders', type=vim.Folder, path='childEntity', skip=False)
    visitFolders.selectSet.extend((SelectionSpec(name='visitFolders'), SelectionSpec(name='dcToVmf'),))

    return SelectionSpec.Array((visitFolders, dcToVmf,)) 
Example #20
Source File: create_dvs_and_dvport_group.py    From vmware-pyvmomi-examples with Apache License 2.0 6 votes vote down vote up
def main():
    try:
        si = None
        try:
            print "Trying to connect to VCENTER SERVER . . ."
            si = connect.Connect(inputs['vcenter_ip'], 443, inputs['vcenter_user'], inputs['vcenter_password'])
        except IOError, e:
            pass
            atexit.register(Disconnect, si)

        print "Connected to VCENTER SERVER !"
        
        content = si.RetrieveContent()
        datacenter = get_obj(content, [vim.Datacenter], inputs['datacenter'])
	cluster = get_obj(content, [vim.ClusterComputeResource], inputs['cluster'])
	network_folder = datacenter.networkFolder
	#Create DV Switch
	dv_switch = create_dvSwitch(si, content, network_folder, cluster)
	#Add port group to this switch
	add_dvPort_group(si, dv_switch) 
Example #21
Source File: vmware_guest2.py    From skylight with GNU General Public License v3.0 6 votes vote down vote up
def get_parent_datacenter(self, obj):
        """ Walk the parent tree to find the objects datacenter """
        if isinstance(obj, vim.Datacenter):
            return obj
        if obj in self.parent_datacenters:
            return self.parent_datacenters[obj]
        datacenter = None
        while True:
            if not hasattr(obj, 'parent'):
                break
            obj = obj.parent
            if isinstance(obj, vim.Datacenter):
                datacenter = obj
                break
        self.parent_datacenters[obj] = datacenter
        return datacenter 
Example #22
Source File: linked_clone.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def get_args():
    parser = cli.build_arg_parser()
    parser.add_argument('-v', '--vm_name',
                        required=True,
                        action='store',
                        help='Name of the new VM')

    parser.add_argument('--template_name',
                        required=True,
                        action='store',
                        help='Name of the template/VM you are cloning from')

    parser.add_argument('--datacenter_name',
                        required=False,
                        action='store',
                        default=None,
                        help='Name of the Datacenter you wish to use.')

    parser.add_argument('--cluster_name',
                        required=False,
                        action='store',
                        default=None,
                        help='Name of the cluster you wish to use')

    parser.add_argument('--host_name',
                        required=False,
                        action='store',
                        default=None,
                        help='Name of the cluster you wish to use')

    args = parser.parse_args()

    cli.prompt_for_password(args)
    return args 
Example #23
Source File: vsphere.py    From ocs-ci with MIT License 5 votes vote down vote up
def get_vm_by_ip(self, ip, dc, vm_search=True):
        """
        Gets the VM using IP address

        Args:
            ip (str): IP address
            dc (str): Datacenter name
            vm_search (bool): Search for VMs if True, Hosts if False

        Returns:
            vim.VirtualMachine: VM instance

        """
        return self.get_search_index.FindByIp(datacenter=self.get_dc(dc), ip=str(ip), vmSearch=vm_search) 
Example #24
Source File: get_vcenter_id.py    From ansible-module-chaperone with Apache License 2.0 5 votes vote down vote up
def core(module):

    vim_type = module.params['vcenter_vim_type']
    vcenter_object_name = module.params['vcenter_object_name']

    vim_rec_type = {
        'cluster': vim.ClusterComputeResource,
        'datacenter': vim.Datacenter,
        'datastore': vim.Datastore,
        'vds': vim.DistributedVirtualSwitch,
        'dvs-port': vim.Network,
        'vm': vim.VirtualMachine
    }

    try:
        vimtype = vim_rec_type[vim_type]
    except KeyError:
        module.fail_json(msg="Please specify valid vim type: cluster, datacenter, datastore, vds, vm")

    si = si_connect(module)

    vcenter_id = get_id(module, si,
                        [vimtype],
                        vcenter_object_name,
                        False, True)

    return False, vcenter_id 
Example #25
Source File: create_folder_in_datacenter.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def main():
    """
    Simple command-line program for creating host and VM folders in a
    datacenter.
    """
    args = GetArgs()
    if args.password:
        password = args.password
    else:
        password = getpass.getpass(prompt='Enter password for host %s and '
                                   'user %s: ' % (args.host, args.user))

    si = SmartConnect(host=args.host,
                      user=args.user,
                      pwd=password,
                      port=int(args.port))
    if not si:
        print("Could not connect to the specified host using specified "
              "username and password")
        return -1

    atexit.register(Disconnect, si)

    content = si.RetrieveContent()
    dc = get_obj(content, [vim.Datacenter], args.datacenter)
    if (get_obj(content, [vim.Folder], args.folder)):
        print("Folder '%s' already exists" % args.folder)
        return 0
    create_folder(content, dc.hostFolder, args.folder)
    print("Successfully created the host folder '%s'" % args.folder)
    create_folder(content, dc.vmFolder, args.folder)
    print("Successfully created the VM folder '%s'" % args.folder)
    return 0

# Start program 
Example #26
Source File: vmware.py    From skylight with GNU General Public License v3.0 5 votes vote down vote up
def get_parent_datacenter(obj):
    """ Walk the parent tree to find the objects datacenter """
    if isinstance(obj, vim.Datacenter):
        return obj
    datacenter = None
    while True:
        if not hasattr(obj, 'parent'):
            break
        obj = obj.parent
        if isinstance(obj, vim.Datacenter):
            datacenter = obj
            break
    return datacenter 
Example #27
Source File: vsphere.py    From ocs-ci with MIT License 5 votes vote down vote up
def get_dc(self, name):
        """
        Gets the Datacenter

        Args:
            name (str): Datacenter name

        Returns:
            vim.Datacenter: Datacenter instance

        """
        for dc in self.get_content.rootFolder.childEntity:
            if dc.name == name:
                return dc 
Example #28
Source File: vsphere.py    From ocs-ci with MIT License 5 votes vote down vote up
def get_cluster(self, name, dc):
        """
        Gets the cluster

        Args:
            name (str): Cluster name
            dc (str): Datacenter name

        Returns:
            vim.ClusterComputeResource: Cluster instance

        """
        for cluster in self.get_dc(dc).hostFolder.childEntity:
            if cluster.name == name:
                return cluster 
Example #29
Source File: vsphere.py    From ocs-ci with MIT License 5 votes vote down vote up
def get_all_vms_in_pool(self, name, dc, cluster):
        """
        Gets all VM's in Resource pool

        Args:
            name (str): Resource pool name
            dc (str): Datacenter name
            cluster (str): Cluster name

        Returns:
            list: VM instances (vim.VirtualMachine)

        """
        rp = self.get_pool(name, dc, cluster)
        return [vm for vm in rp.vm] 
Example #30
Source File: vsphere.py    From ocs-ci with MIT License 5 votes vote down vote up
def is_resource_pool_exist(self, pool, dc, cluster):
        """
        Check whether resource pool exists in cluster or not

        Args:
            pool (str): Resource pool name
            dc (str): Datacenter name
            cluster (str): Cluster name

        Returns:
            bool: True if resource pool exists, otherwise False

        """
        return True if self.get_pool(pool, dc, cluster) else False