Python pyVmomi.vim.Folder() Examples

The following are 30 code examples of pyVmomi.vim.Folder(). 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: folder_utils.py    From ADLES with Apache License 2.0 6 votes vote down vote up
def rename(folder, name):
    """
    Renames a folder.

    :param folder: Folder to rename
    :type folder: vim.Folder
    :param str name: New name for the folder
    """
    logging.debug("Renaming %s to %s", folder.name, name)
    folder.Rename_Task(newName=str(name)).wait()


# Injection of methods into vim.Folder pyVmomi class
#
# These enable "<folder>.create('name')" instead of
# "folder_utils.create_folder(<folder>, 'name')"
#
# This works because the implicit first argument
# to a class method call in Python is the instance
# 
Example #2
Source File: vmware.py    From skylight with GNU General Public License v3.0 6 votes vote down vote up
def compile_folder_path_for_object(vobj):
    """ make a /vm/foo/bar/baz like folder path for an object """

    paths = []
    if isinstance(vobj, vim.Folder):
        paths.append(vobj.name)

    thisobj = vobj
    while hasattr(thisobj, 'parent'):
        thisobj = thisobj.parent
        try:
            moid = thisobj._moId
        except AttributeError:
            moid = None
        if moid in ['group-d1', 'ha-folder-root']:
            break
        if isinstance(thisobj, vim.Folder):
            paths.append(thisobj.name)
    paths.reverse()
    return '/' + '/'.join(paths) 
Example #3
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 #4
Source File: folder_utils.py    From ADLES with Apache License 2.0 6 votes vote down vote up
def get_in_folder(folder, name, recursive=False, vimtype=None):
    """
    Retrieves an item from a datacenter folder.

    :param folder: Folder to search in
    :type folder: vim.Folder
    :param str name: Name of object to find
    :param bool recursive: Recurse into sub-folders
    :param vimtype: Type of object to search for
    :return: The object found
    :rtype: vimtype or None
    """
    item = None
    if name is not None:
        item = find_in_folder(folder, name, recursive=recursive,
                              vimtype=vimtype)

    # Get first found of type if can't find in folder or name isn't specified
    if item is None:
        if len(folder.childEntity) > 0 and vimtype is None:
            return folder.childEntity[0]
        elif len(folder.childEntity) > 0:
            for i in folder.childEntity:
                if isinstance(i, vimtype):
                    return i
            logging.error("Could not find item of type '%s' in folder '%s'",
                          vimtype.__name__, folder.name)
        else:
            logging.error("There are no items in folder %s", folder.name)
    return item 
Example #5
Source File: cluster.py    From vsphere-automation-sdk-python with MIT License 6 votes vote down vote up
def setup_cluster_vapi2(context):
    """Create a cluster from the Folder managed object"""
    cluster1_name = context.testbed.config['CLUSTER1_NAME']

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

    folder_summaries = context.client.vcenter.Folder.list(
        Folder.FilterSpec(type=Folder.Type.HOST, datacenters=set([datacenter])))
    folder = folder_summaries[0].folder

    # Create a managed object from the folder identifier
    folder_mo = vim.Folder(folder, context.soap_stub)
    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 #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: vsphere.py    From KubeOperator with Apache License 2.0 6 votes vote down vote up
def get_templates(self, entity):
        templates = []
        if isinstance(entity, vim.Folder):
            for obj in entity.childEntity:
                if isinstance(obj, vim.VirtualMachine) and obj.config.template:
                    template = {
                        "image_name": obj.name,
                        "guest_id": obj.guest.guestId
                    }
                    templates.append(template)

                if isinstance(obj, vim.Folder):
                    tem = self.get_templates(obj)
                    if len(tem) > 0:
                        templates.extend(tem)
            return templates
        else:
            return [] 
Example #8
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 #9
Source File: vmware.py    From skylight with GNU General Public License v3.0 6 votes vote down vote up
def get_vm_path(content, vm_name):
        """
        Function to find the path of virtual machine.
        Args:
            content: VMware content object
            vm_name: virtual machine managed object

        Returns: Folder of virtual machine if exists, else None

        """
        folder_name = None
        folder = vm_name.parent
        if folder:
            folder_name = folder.name
            fp = folder.parent
            # climb back up the tree to find our path, stop before the root folder
            while fp is not None and fp.name is not None and fp != content.rootFolder:
                folder_name = fp.name + '/' + folder_name
                try:
                    fp = fp.parent
                except BaseException:
                    break
            folder_name = '/' + folder_name
        return folder_name 
Example #10
Source File: create_random_marvel_vms.py    From pyvmomi-community-samples with Apache License 2.0 6 votes vote down vote up
def create_dummy_vm(vm_name, service_instance, vm_folder, resource_pool,
                    datastore):
    """Creates a dummy VirtualMachine with 1 vCpu, 128MB of RAM.

    :param name: String Name for the VirtualMachine
    :param service_instance: ServiceInstance connection
    :param vm_folder: Folder to place the VirtualMachine in
    :param resource_pool: ResourcePool to place the VirtualMachine in
    :param datastore: DataStrore to place the VirtualMachine on
    """
    datastore_path = '[' + datastore + '] ' + vm_name

    # bare minimum VM shell, no disks. Feel free to edit
    vmx_file = vim.vm.FileInfo(logDirectory=None,
                               snapshotDirectory=None,
                               suspendDirectory=None,
                               vmPathName=datastore_path)

    config = vim.vm.ConfigSpec(name=vm_name, memoryMB=128, numCPUs=1,
                               files=vmx_file, guestId='dosGuest',
                               version='vmx-07')

    print("Creating VM {}...".format(vm_name))
    task = vm_folder.CreateVM_Task(config=config, pool=resource_pool)
    tasks.wait_for_tasks(service_instance, [task]) 
Example #11
Source File: deploy_vsphere_template_with_nuage.py    From vspk-examples with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def find_folder(vc, logger, name):
    """
    Find a folder by its name and return it
    """

    content = vc.content
    obj_view = content.viewManager.CreateContainerView(content.rootFolder, [vim.Folder], True)
    folder_list = obj_view.view

    for folder in folder_list:
        logger.debug('Checking folder %s' % folder.name)
        if folder.name == name:
            logger.debug('Found folder %s' % folder.name)
            return folder
    return None 
Example #12
Source File: vm.py    From ADLES with Apache License 2.0 5 votes vote down vote up
def __init__(self, vm=None, name=None, folder=None, resource_pool=None,
                 datastore=None, host=None):
        """
        :param vm: VM instance to use instead of calling :meth:`create`
        :type vm: vim.VirtualMachine
        :param str name: Name of the VM
        :param folder: Folder in inventory to create the VM in
        :type folder: vim.Folder
        :param resource_pool: Resource pool to use for the VM
        :type resource_pool: vim.ResourcePool
        :param datastore: Datastore the VM is stored on
        :type datastore: vim.Datastore
        :param host: Host the VM runs on
        :type host: vim.HostSystem
        """
        self._log = logging.getLogger('VM')
        if vm is not None:
            self._vm = vm
            self.name = vm.name
            self.folder = vm.parent
            self.resource_pool = vm.resourcePool
            self.datastore = vm.datastore[0]
            self.host = vm.summary.runtime.host
            self.network = vm.network
            self.runtime = vm.runtime
            self.summary = vm.summary
        else:
            self._vm = None
            self.name = name
            self.folder = folder  # vim.Folder that will contain the VM
            self.resource_pool = resource_pool  # vim.ResourcePool to use VM
            self.datastore = datastore  # vim.Datastore object to store VM on
            self.host = host  # vim.HostSystem 
Example #13
Source File: vsphere_interface.py    From ADLES with Apache License 2.0 5 votes vote down vote up
def _master_base_folder_gen(self, folder_name, folder_dict, parent):
        """
        Generates base-type Master folders.

        :param str folder_name: Name of the base folder
        :param dict folder_dict: Dict with the base folder tree as in spec
        :param parent: Parent folder
        :type parent: vim.Folder
        """
        # Set the group to apply permissions for
        # if "master-group" in folder_dict:
        #     master_group = self._get_group(folder_dict["master-group"])
        # else:
        #     master_group = self._get_group(folder_dict["group"])

        # Create Master instances
        for sname, sconfig in folder_dict["services"].items():
            if not self._is_vsphere(sconfig["service"]):
                self._log.debug("Skipping non-vsphere service '%s'", sname)
                continue

            self._log.info("Creating Master instance '%s' from service '%s'",
                           sname, sconfig["service"])

            vm = self._create_service(parent, sconfig["service"],
                                      sconfig["networks"])
            if vm is None:
                self._log.error("Failed to create Master instance '%s' "
                                "in folder '%s'", sname, folder_name)
                continue  # Skip to the next service 
Example #14
Source File: folder_utils.py    From ADLES with Apache License 2.0 5 votes vote down vote up
def move_into(folder, entity_list):
    """
    Moves a list of managed entities into the named folder.

    :param folder: Folder to move entities into
    :type folder: vim.Folder
    :param entity_list: Entities to move into the folder
    :type entity_list: list(vim.ManagedEntity)
    """
    logging.debug("Moving a list of %d entities into folder %s",
                  len(entity_list), folder.name)
    folder.MoveIntoFolder_Task(entity_list).wait() 
Example #15
Source File: folder_utils.py    From ADLES with Apache License 2.0 5 votes vote down vote up
def retrieve_items(folder, vm_prefix='', folder_prefix='', recursive=False):
    """
    Retrieves VMs and folders from a folder structure.

    :param folder: Folder to begin search in
    (Note: it is NOT returned in list of folders)
    :type folder: vim.Folder
    :param str vm_prefix: VM prefix to search for
    :param str folder_prefix: Folder prefix to search for
    :param bool recursive: Recursively descend into sub-folders

    .. warning:: This will recurse regardless of folder prefix!

    :return: The VMs and folders found in the folder
    :rtype: tuple(list(vim.VirtualMachine), list(vim.Folder))
    """
    vms = []
    folders = []

    for item in folder.childEntity:  # Iterate through all items in the folder
        if is_vm(item) and str(item.name).startswith(vm_prefix):
            vms.append(item)  # Add matching vm to the list
        elif is_folder(item):
            if str(item.name).startswith(folder_prefix):
                folders.append(item)  # Add matching folder to the list
            if recursive:  # Recurse into sub-folders
                v, f = retrieve_items(item, vm_prefix, folder_prefix, recursive)
                vms.extend(v)
                folders.extend(f)
    return vms, folders 
Example #16
Source File: folder_utils.py    From ADLES with Apache License 2.0 5 votes vote down vote up
def enumerate_folder(folder, recursive=True, power_status=False):
    """
    Enumerates a folder structure and returns the result.

    as a python object with the same structure
    :param folder: Folder to enumerate
    :type folder: vim.Folder
    :param bool recursive: Whether to recurse into any sub-folders
    :param bool power_status: Display the power state of the VMs in the folder
    :return: The nested python object with the enumerated folder structure
    :rtype: list(list, str)
    """
    children = []
    for item in folder.childEntity:
        if is_folder(item):
            if recursive:  # Recurse into sub-folders and append the sub-tree
                children.append(enumerate_folder(item, recursive))
            else:  # Don't recurse, just append the folder
                children.append('- ' + item.name)
        elif is_vm(item):
            if power_status:
                if item.runtime.powerState == \
                        vim.VirtualMachine.PowerState.poweredOn:
                    children.append('* ON  ' + item.name)
                elif item.runtime.powerState == \
                        vim.VirtualMachine.PowerState.poweredOff:
                    children.append('* OFF ' + item.name)
                elif item.runtime.powerState == \
                        vim.VirtualMachine.PowerState.suspended:
                    children.append('* SUS ' + item.name)
                else:
                    logging.error("Invalid power state for VM: %s", item.name)
            else:
                children.append('* ' + item.name)
        else:
            children.append("UNKNOWN ITEM: %s" % str(item))
    return '+ ' + folder.name, children  # Return tuple of parent and children


# Similar to: https://docs.python.org/3/library/pprint.html 
Example #17
Source File: folder_utils.py    From ADLES with Apache License 2.0 5 votes vote down vote up
def find_in_folder(folder, name, recursive=False, vimtype=None):
    """
    Finds and returns an specific object in a folder.

    :param folder: Folder to search in
    :type folder: vim.Folder
    :param str name: Name of the object to find
    :param bool recursive: Recurse into sub-folders
    :param vimtype: Type of object to search for
    :return: The object found
    :rtype: vimtype or None
    """
    # NOTE: Convert to lowercase for case-insensitive comparisons
    item_name = name.lower()
    found = None
    for item in folder.childEntity:
        # Check if the name matches
        if hasattr(item, 'name') and item.name.lower() == item_name:
            if vimtype is not None and not isinstance(item, vimtype):
                continue
            found = item
        elif recursive and is_folder(item):  # Recurse into sub-folders
            found = find_in_folder(item, name=item_name,
                                   recursive=recursive, vimtype=vimtype)
        if found is not None:
            return found
    return None 
Example #18
Source File: folder_utils.py    From ADLES with Apache License 2.0 5 votes vote down vote up
def cleanup(folder, vm_prefix='', folder_prefix='', recursive=False,
            destroy_folders=False, destroy_self=False):
    """
    Cleans a folder by selectively destroying any VMs and folders it contains.

    :param folder: Folder to cleanup
    :type folder: vim.Folder
    :param str vm_prefix: Only destroy VMs with names starting with the prefix
    :param str folder_prefix: Only destroy or search in folders with names
    starting with the prefix
    :param bool recursive: Recursively descend into any sub-folders
    :param bool destroy_folders: Destroy folders in addition to VMs
    :param bool destroy_self: Destroy the folder specified
    """
    logging.debug("Cleaning folder '%s'", folder.name)
    from adles.vsphere.vm import VM

    # TODO: progress bar
    # pbar = tqdm.tqdm(folder.childEntity, desc="Cleaning folder",
    #                  unit="Items", clear=True)
    for item in folder.childEntity:
        # Handle VMs
        if is_vm(item) and str(item.name).startswith(vm_prefix):
            VM(vm=item).destroy()  # Delete the VM from the Datastore

        # Handle folders
        elif is_folder(item) and str(item.name).startswith(folder_prefix):
            if destroy_folders:  # Destroys folder and ALL of it's sub-objects
                cleanup(item, destroy_folders=True, destroy_self=True)
            elif recursive:  # Simply recurses to find more items
                cleanup(item, vm_prefix=vm_prefix,
                        folder_prefix=folder_prefix, recursive=True)

    # Note: UnregisterAndDestroy does NOT delete VM files off the datastore
    # Only use if folder is already empty!
    if destroy_self:
        logging.debug("Destroying folder: '%s'", folder.name)
        folder.UnregisterAndDestroy_Task().wait() 
Example #19
Source File: folder_utils.py    From ADLES with Apache License 2.0 5 votes vote down vote up
def create_folder(folder, folder_name):
    """
    Creates a VM folder in the specified folder.

    :param folder: Folder to create the folder in
    :type folder: vim.Folder
    :param str folder_name: Name of folder to create
    :return: The created folder
    :rtype: vim.Folder or None
    """
    # Check if the folder already exists
    exists = find_in_folder(folder, folder_name)
    if exists:
        logging.warning("Folder '%s' already exists in folder '%s'",
                        folder_name, folder.name)
        return exists  # Return the folder that already existed
    else:
        logging.debug("Creating folder '%s' in folder '%s'",
                      folder_name, folder.name)
        try:
            # Create the folder and return it
            return folder.CreateFolder(folder_name)
        except vim.fault.DuplicateName as dupe:
            logging.error("Could not create folder '%s' in '%s': "
                          "folder already exists as '%s'",
                          folder_name, folder.name, dupe.name)
        except vim.fault.InvalidName as invalid:
            logging.error("Could not create folder '%s' in '%s': "
                          "Invalid folder name '%s'",
                          folder_name, folder.name, invalid.name)
    return None 
Example #20
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 #21
Source File: datacenter.py    From pyvmomi-community-samples with Apache License 2.0 5 votes vote down vote up
def create_datacenter(dcname=None, service_instance=None, folder=None):
    """
    Creates a new datacenter with the given name.
    Any % (percent) character used in this name parameter must be escaped,
    unless it is used to start an escape sequence. Clients may also escape
    any other characters in this name parameter.

    An entity name must be a non-empty string of
    less than 80 characters. The slash (/), backslash (\) and percent (%)
    will be escaped using the URL syntax. For example, %2F

    This can raise the following exceptions:
    vim.fault.DuplicateName
    vim.fault.InvalidName
    vmodl.fault.NotSupported
    vmodl.fault.RuntimeFault
    ValueError raised if the name len is > 79
    https://github.com/vmware/pyvmomi/blob/master/docs/vim/Folder.rst

    Required Privileges
    Datacenter.Create

    :param folder: Folder object to create DC in. If None it will default to
                   rootFolder
    :param dcname: Name for the new datacenter.
    :param service_instance: ServiceInstance connection to a given vCenter
    :return:
    """
    if len(dcname) > 79:
        raise ValueError("The name of the datacenter must be under "
                         "80 characters.")
    if folder is None:
        folder = service_instance.content.rootFolder

    if folder is not None and isinstance(folder, vim.Folder):
        dc_moref = folder.CreateDatacenter(name=dcname)
        return dc_moref 
Example #22
Source File: vmutils.py    From devops with Apache License 2.0 5 votes vote down vote up
def _get_child_folder(parent_folder, folder_name):
    obj = None
    for folder in parent_folder.childEntity:
        if folder.name == folder_name:
            if isinstance(folder, vim.Datacenter):
                obj = folder.vmFolder
            elif isinstance(folder, vim.Folder):
                obj = folder
            else:
                obj = None
            break
    return obj 
Example #23
Source File: __init__.py    From kcli with Apache License 2.0 5 votes vote down vote up
def delete(self, name, snapshots=False):
        si = self.si
        dc = self.dc
        vmFolder = dc.vmFolder
        vm = findvm(si, vmFolder, name)
        if vm is None:
            return {'result': 'failure', 'reason': "VM %s not found" % name}
        plan, image = 'kvirt', None
        vmpath = vm.summary.config.vmPathName.replace('/%s.vmx' % name, '')
        for entry in vm.config.extraConfig:
            if entry.key == 'image':
                image = entry.value
            if entry.key == 'plan':
                plan = entry.value
        if vm.runtime.powerState == "poweredOn":
            t = vm.PowerOffVM_Task()
            waitForMe(t)
        t = vm.Destroy_Task()
        waitForMe(t)
        if image is not None and 'coreos' not in image and 'rhcos' not in image and\
                'fcos' not in image and vmpath.endswith(name):
            deletedirectory(si, dc, vmpath)
        if plan != 'kvirt':
            planfolder = find(si, vmFolder, vim.Folder, plan)
            if planfolder is not None and len(planfolder.childEntity) == 0:
                planfolder.Destroy()
        return {'result': 'success'} 
Example #24
Source File: __init__.py    From kcli with Apache License 2.0 5 votes vote down vote up
def deletefolder(si, parentfolder, folder):
    folder = find(si, parentfolder, vim.Folder, folder)
    if folder is not None:
        folder.Destroy() 
Example #25
Source File: __init__.py    From kcli with Apache License 2.0 5 votes vote down vote up
def createfolder(si, parentfolder, folder):
    if find(si, parentfolder, vim.Folder, folder) is None:
        parentfolder.CreateFolder(folder)
    return None 
Example #26
Source File: virtualcenter.py    From wrapanapi with MIT License 5 votes vote down vote up
def destroy_folder(self, folder_name):
        """Delete a Vm folder under Datacenter

        Args:
            folder_name: Name of Vm Folder
            return: vim.Task
        """
        folder = self._search_folders_for_vm(folder_name)
        return folder.Destroy() 
Example #27
Source File: virtualcenter.py    From wrapanapi with MIT License 5 votes vote down vote up
def create_folder(self, folder_name):
        """Create a Vm folder under Datacenter

        Args:
            folder_name: Name of Vm Folder
            return: vim.Folder
        """
        dc = self.get_obj(vim.Datacenter, "Datacenter")
        folder = dc.vmFolder.CreateFolder(folder_name)
        return folder 
Example #28
Source File: virtualcenter.py    From wrapanapi with MIT License 5 votes vote down vote up
def _search_folders_for_vm(self, name):
        # First get all VM folders
        container = self.content.viewManager.CreateContainerView(
            self.content.rootFolder, [vim.Folder], True)
        folders = container.view
        container.Destroy()

        # Now search each folder for VM
        vm = None
        for folder in folders:
            vm = self.content.searchIndex.FindChild(folder, name)
            if vm:
                break

        return vm 
Example #29
Source File: vmware_exporter.py    From vmware_exporter with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def host_labels(self):

        def _collect(node, level=1, dc=None, folder=None):
            inventory = {}
            if isinstance(node, vim.Folder) and not isinstance(node, vim.StoragePod):
                logging.debug("[Folder    ] {level} {name}".format(level=('-' * level).ljust(7), name=node.name))
                for child in node.childEntity:
                    inventory.update(_collect(child, level + 1, dc))
            elif isinstance(node, vim.Datacenter):
                logging.debug("[Datacenter] {level} {name}".format(level=('-' * level).ljust(7), name=node.name))
                inventory.update(_collect(node.hostFolder, level + 1, node.name))
            elif isinstance(node, vim.ComputeResource):
                logging.debug("[ComputeRes] {level} {name}".format(level=('-' * level).ljust(7), name=node.name))
                for host in node.host:
                    inventory.update(_collect(host, level + 1, dc, node))
            elif isinstance(node, vim.HostSystem):
                logging.debug("[HostSystem] {level} {name}".format(level=('-' * level).ljust(7), name=node.name))
                inventory[node._moId] = [
                    node.summary.config.name.rstrip('.'),
                    dc,
                    folder.name if isinstance(folder, vim.ClusterComputeResource) else ''
                ]
            else:
                logging.debug("[?         ] {level} {node}".format(level=('-' * level).ljust(7), node=node))
            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 #30
Source File: vsphere.py    From KubeOperator with Apache License 2.0 5 votes vote down vote up
def apply_terraform(self, cluster, hosts_dict):
        vars = cluster.plan.mixed_vars
        st = connect.SmartConnectNoSSL(host=vars['vc_host'], user=vars['vc_username'],
                                       pwd=vars['vc_password'], port=vars['vc_port'])
        content = st.RetrieveContent()
        container = content.rootFolder
        dc = get_obj(content, [vim.Datacenter], container, vars['region'])
        folder = get_obj(content, [vim.Folder], container, 'kubeoperator')
        if not folder:
            dc.vmFolder.CreateFolder('kubeoperator')
        return super().apply_terraform(cluster, hosts_dict)