def __init__(self, module):
        super(VmwreClusterInfoManager, self).__init__(module)
        datacenter = self.params.get('datacenter')
        cluster_name = self.params.get('cluster_name')
        self.schema = self.params.get('schema')
        self.properties = self.params.get('properties')
        self.cluster_objs = []
        if datacenter:
            datacenter_obj = find_datacenter_by_name(
                self.content, datacenter_name=datacenter)
            if datacenter_obj is None:
                self.module.fail_json(msg="Failed to find datacenter '%s'" %
                                      datacenter)
            self.cluster_objs = self.get_all_cluster_objs(
                parent=datacenter_obj)
        elif cluster_name:
            cluster_obj = find_cluster_by_name(self.content,
                                               cluster_name=cluster_name)
            if cluster_obj is None:
                self.module.fail_json(msg="Failed to find cluster '%s'" %
                                      cluster_name)

            self.cluster_objs = [cluster_obj]
        else:
            self.cluster_objs = []
            datacenters = self.get_datacenter_info()
            for datacenter in datacenters:
                datacenter_obj = find_datacenter_by_name(
                    self.content, datacenter_name=datacenter['name'])
                [
                    self.cluster_objs.append(x)
                    for x in self.get_all_cluster_objs(parent=datacenter_obj)
                ]
Exemple #2
0
 def lookup_datastore_by_cluster(self):
     """ Get datastore(s) per cluster """
     cluster = find_cluster_by_name(self.content, self.params['cluster'])
     if not cluster:
         self.module.fail_json(msg='Failed to find cluster "%(cluster)s"' % self.params)
     c_dc = cluster.datastore
     return c_dc
    def state_add_rp(self):
        changed = True

        rp_spec = vim.ResourceConfigSpec()
        cpu_alloc = vim.ResourceAllocationInfo()
        cpu_alloc.expandableReservation = self.cpu_expandable_reservations
        cpu_alloc.limit = int(self.cpu_limit)
        cpu_alloc.reservation = int(self.cpu_reservation)
        cpu_alloc_shares = vim.SharesInfo()
        cpu_alloc_shares.level = self.cpu_shares
        cpu_alloc.shares = cpu_alloc_shares
        rp_spec.cpuAllocation = cpu_alloc
        mem_alloc = vim.ResourceAllocationInfo()
        mem_alloc.limit = int(self.mem_limit)
        mem_alloc.expandableReservation = self.mem_expandable_reservations
        mem_alloc.reservation = int(self.mem_reservation)
        mem_alloc_shares = vim.SharesInfo()
        mem_alloc_shares.level = self.mem_shares
        mem_alloc.shares = mem_alloc_shares
        rp_spec.memoryAllocation = mem_alloc

        self.dc_obj = find_datacenter_by_name(self.content, self.datacenter)
        if self.dc_obj is None:
            self.module.fail_json(msg="Unable to find datacenter with name %s" % self.datacenter)

        self.cluster_obj = find_cluster_by_name(self.content, self.cluster, datacenter=self.dc_obj)
        if self.cluster_obj is None:
            self.module.fail_json(msg="Unable to find cluster with name %s" % self.cluster)
        rootResourcePool = self.cluster_obj.resourcePool
        rootResourcePool.CreateResourcePool(self.resource_pool, rp_spec)

        self.module.exit_json(changed=changed)
Exemple #4
0
    def __init__(self, module):
        super(VMwareResourcePool, self).__init__(module)
        self.datacenter = module.params['datacenter']
        self.resource_pool = module.params['resource_pool']
        self.hostname = module.params['hostname']
        self.username = module.params['username']
        self.password = module.params['password']
        self.state = module.params['state']
        self.mem_shares = module.params['mem_shares']
        self.mem_allocation_shares = module.params['mem_allocation_shares']
        self.mem_limit = module.params['mem_limit']
        self.mem_reservation = module.params['mem_reservation']
        self.mem_expandable_reservations = module.params[
            'mem_expandable_reservations']
        self.cpu_shares = module.params['cpu_shares']
        self.cpu_allocation_shares = module.params['cpu_allocation_shares']
        self.cpu_limit = module.params['cpu_limit']
        self.cpu_reservation = module.params['cpu_reservation']
        self.cpu_expandable_reservations = module.params[
            'cpu_expandable_reservations']
        self.resource_pool_obj = None

        self.dc_obj = find_datacenter_by_name(self.content, self.datacenter)
        if self.dc_obj is None:
            self.module.fail_json(msg="Unable to find datacenter with name %s" % self.datacenter)

        if module.params['cluster']:
            self.compute_resource_obj = find_cluster_by_name(self.content, module.params['cluster'], datacenter=self.dc_obj)
            if self.compute_resource_obj is None:
                self.module.fail_json(msg="Unable to find cluster with name %s" % module.params['cluster'])

        if module.params['esxi_hostname']:
            self.compute_resource_obj = find_object_by_name(self.content, module.params['esxi_hostname'], [vim.ComputeResource], folder=self.dc_obj.hostFolder)
            if self.compute_resource_obj is None:
                self.module.fail_json(msg="Unable to find host with name %s" % module.params['esxi_hostname'])
    def __init__(self, module):
        """
        Doctring: Init
        """

        super(VmwareVmHostRuleDrs, self).__init__(module)

        self.__datacenter_name = module.params.get('datacenter', None)
        self.__datacenter_obj = None
        self.__cluster_name = module.params['cluster_name']
        self.__cluster_obj = None
        self.__vm_group_name = module.params.get('vm_group_name', None)
        self.__host_group_name = module.params.get('host_group_name', None)
        self.__rule_name = module.params['drs_rule_name']
        self.__enabled = module.params['enabled']
        self.__mandatory = module.params['mandatory']
        self.__affinity_rule = module.params['affinity_rule']
        self.__msg = 'Nothing to see here...'
        self.__result = dict()
        self.__changed = False

        if self.__datacenter_name is not None:

            self.__datacenter_obj = find_datacenter_by_name(self.content, self.__datacenter_name)

            if self.__datacenter_obj is None and module.check_mode is False:
                raise Exception("Datacenter '%s' not found" % self.__datacenter_name)

        self.__cluster_obj = find_cluster_by_name(content=self.content,
                                                  cluster_name=self.__cluster_name,
                                                  datacenter=self.__datacenter_obj)

        # Throw error if cluster does not exist
        if self.__cluster_obj is None and module.check_mode is False:
            raise Exception("Cluster '%s' not found" % self.__cluster_name)
Exemple #6
0
 def __init__(self, module):
     super(VmwareDatastoreMaintenanceMgr, self).__init__(module)
     datastore_name = self.params.get('datastore')
     cluster_name = self.params.get('cluster_name')
     datastore_cluster = self.params.get('datastore_cluster')
     self.datastore_objs = []
     if datastore_name:
         ds = self.find_datastore_by_name(datastore_name=datastore_name)
         if not ds:
             self.module.fail_json(msg='Failed to find datastore "%(datastore)s".' % self.params)
         self.datastore_objs = [ds]
     elif cluster_name:
         cluster = find_cluster_by_name(self.content, cluster_name)
         if not cluster:
             self.module.fail_json(msg='Failed to find cluster "%(cluster_name)s".' % self.params)
         self.datastore_objs = cluster.datastore
     elif datastore_cluster:
         datastore_cluster_obj = get_all_objs(self.content, [vim.StoragePod])
         if not datastore_cluster_obj:
             self.module.fail_json(msg='Failed to find datastore cluster "%(datastore_cluster)s".' % self.params)
         for datastore in datastore_cluster_obj.childEntity:
             self.datastore_objs.append(datastore)
     else:
         self.module.fail_json(msg="Please select one of 'cluster_name', 'datastore' or 'datastore_cluster'.")
     self.state = self.params.get('state')
    def state_add_rp(self):
        changed = True
        if self.module.check_mode:
            self.module.exit_json(changed=changed)

        self.dc_obj = find_datacenter_by_name(self.content, self.datacenter)
        if self.dc_obj is None:
            self.module.fail_json(
                msg="Unable to find datacenter with name %s" % self.datacenter)

        self.cluster_obj = find_cluster_by_name(self.content,
                                                self.cluster,
                                                datacenter=self.dc_obj)
        if self.cluster_obj is None:
            self.module.fail_json(msg="Unable to find cluster with name %s" %
                                  self.cluster)

        rp_spec = self.generate_rp_config()
        rootResourcePool = self.cluster_obj.resourcePool

        rootResourcePool.CreateResourcePool(self.resource_pool, rp_spec)

        resource_pool_config = self.generate_rp_config_return_value(True)
        self.module.exit_json(changed=changed,
                              resource_pool_config=resource_pool_config)
Exemple #8
0
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(cluster_name=dict(required=True, type='str'),
                         fetch_from_cache=dict(required=False,
                                               type='bool',
                                               default=False))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    if not HAS_PYVMOMI:
        module.fail_json(msg=missing_required_lib('PyVmomi'),
                         exception=PYVMOMI_IMP_ERR)

    if not HAS_VSANPYTHONSDK:
        module.fail_json(
            msg=missing_required_lib('vSAN Management SDK for Python'),
            exception=VSANPYTHONSDK_IMP_ERR)

    if not HAS_PYVMOMIJSON:
        module.fail_json(
            msg=
            'The installed version of pyvmomi lacks JSON output support; need pyvmomi>6.7.1'
        )

    try:
        si, content = connect_to_api(module, True, True)
    except Exception as e:
        module.fail_json(msg=e.msg)

    client_stub = si._GetStub()
    ssl_context = client_stub.schemeArgs.get('context')

    cluster = find_cluster_by_name(content, module.params['cluster_name'])

    if not cluster:
        module.fail_json(msg="Failed to find cluster %s" %
                         module.params['cluster_name'])

    apiVersion = vsanapiutils.GetLatestVmodlVersion(module.params['hostname'])
    vcMos = vsanapiutils.GetVsanVcMos(client_stub,
                                      context=ssl_context,
                                      version=apiVersion)

    vsanClusterHealthSystem = vcMos['vsan-cluster-health-system']

    try:
        clusterHealth = vsanClusterHealthSystem.VsanQueryVcClusterHealthSummary(
            cluster=cluster, fetchFromCache=module.params['fetch_from_cache'])
    except vmodl.fault.NotFound as not_found:
        module.fail_json(msg=not_found.msg)
    except vmodl.fault.RuntimeFault as runtime_fault:
        module.fail_json(msg=runtime_fault.msg)

    health = json.dumps(clusterHealth,
                        cls=VmomiSupport.VmomiJSONEncoder,
                        sort_keys=True,
                        strip_dynamic=True)

    module.exit_json(changed=False, vsan_health_info=health)
    def __init__(self, module):
        super(VMwareShellManager, self).__init__(module)
        datacenter_name = module.params['datacenter']
        cluster_name = module.params['cluster']
        folder = module.params['folder']
        try:
            self.pm = self.content.guestOperationsManager.processManager
        except vmodl.fault.ManagedObjectNotFound:
            pass
        self.timeout = self.params.get('timeout', 3600)
        self.wait_for_pid = self.params.get('wait_for_process', False)

        datacenter = None
        if datacenter_name:
            datacenter = find_datacenter_by_name(self.content, datacenter_name)
            if not datacenter:
                module.fail_json(
                    changed=False,
                    msg="Unable to find %(datacenter)s datacenter" %
                    module.params)

        cluster = None
        if cluster_name:
            cluster = find_cluster_by_name(self.content, cluster_name,
                                           datacenter)
            if not cluster:
                module.fail_json(changed=False,
                                 msg="Unable to find %(cluster)s cluster" %
                                 module.params)

        if module.params['vm_id_type'] == 'inventory_path':
            vm = find_vm_by_id(self.content,
                               vm_id=module.params['vm_id'],
                               vm_id_type="inventory_path",
                               folder=folder)
        else:
            vm = find_vm_by_id(self.content,
                               vm_id=module.params['vm_id'],
                               vm_id_type=module.params['vm_id_type'],
                               datacenter=datacenter,
                               cluster=cluster)

        if not vm:
            module.fail_json(msg='Unable to find virtual machine.')

        tools_status = vm.guest.toolsStatus
        if tools_status in ['toolsNotInstalled', 'toolsNotRunning']:
            self.module.fail_json(
                msg=
                "VMwareTools is not installed or is not running in the guest."
                " VMware Tools are necessary to run this module.")

        try:
            self.execute_command(vm, module.params)
        except vmodl.RuntimeFault as runtime_fault:
            module.fail_json(changed=False, msg=to_native(runtime_fault.msg))
        except vmodl.MethodFault as method_fault:
            module.fail_json(changed=False, msg=to_native(method_fault.msg))
        except Exception as e:
            module.fail_json(changed=False, msg=to_native(e))
    def __init__(self, module):
        super(VmwareGuestFileManager, self).__init__(module)
        datacenter_name = module.params['datacenter']
        cluster_name = module.params['cluster']
        folder = module.params['folder']

        datacenter = None
        if datacenter_name:
            datacenter = find_datacenter_by_name(self.content, datacenter_name)
            if not datacenter:
                module.fail_json(
                    msg="Unable to find %(datacenter)s datacenter" %
                    module.params)

        cluster = None
        if cluster_name:
            cluster = find_cluster_by_name(self.content, cluster_name,
                                           datacenter)
            if not cluster:
                module.fail_json(msg="Unable to find %(cluster)s cluster" %
                                 module.params)

        if module.params['vm_id_type'] == 'inventory_path':
            vm = find_vm_by_id(self.content,
                               vm_id=module.params['vm_id'],
                               vm_id_type="inventory_path",
                               folder=folder)
        else:
            vm = find_vm_by_id(self.content,
                               vm_id=module.params['vm_id'],
                               vm_id_type=module.params['vm_id_type'],
                               datacenter=datacenter,
                               cluster=cluster)

        if not vm:
            module.fail_json(msg='Unable to find virtual machine.')

        self.vm = vm
        try:
            result = dict(changed=False)
            if module.params['directory']:
                result = self.directory()
            if module.params['copy']:
                result = self.copy()
            if module.params['fetch']:
                result = self.fetch()
            module.exit_json(**result)
        except vmodl.RuntimeFault as runtime_fault:
            module.fail_json(msg=to_native(runtime_fault.msg))
        except vmodl.MethodFault as method_fault:
            module.fail_json(msg=to_native(method_fault.msg))
        except Exception as e:
            module.fail_json(msg=to_native(e))
Exemple #11
0
    def __init__(self, module):
        super(VmwreClusterInfoManager, self).__init__(module)
        datacenter = self.params.get('datacenter')
        cluster_name = self.params.get('cluster_name')
        self.cluster_objs = []
        if datacenter:
            datacenter_obj = find_datacenter_by_name(self.content, datacenter_name=datacenter)
            if datacenter_obj is None:
                self.module.fail_json(msg="Failed to find datacenter '%s'" % datacenter)
            self.cluster_objs = self.get_all_cluster_objs(parent=datacenter_obj)
        elif cluster_name:
            cluster_obj = find_cluster_by_name(self.content, cluster_name=cluster_name)
            if cluster_obj is None:
                self.module.fail_json(msg="Failed to find cluster '%s'" % cluster_name)

            self.cluster_objs = [cluster_obj]
    def __init__(self, module):
        super(VmwareDrs, self).__init__(module)
        self.vm_list = module.params['vms']
        self.cluster_name = module.params['cluster_name']
        self.rule_name = module.params['drs_rule_name']
        self.enabled = module.params['enabled']
        self.mandatory = module.params['mandatory']
        self.affinity_rule = module.params['affinity_rule']
        self.state = module.params['state']

        # Sanity check for cluster
        self.cluster_obj = find_cluster_by_name(content=self.content,
                                                cluster_name=self.cluster_name)
        if self.cluster_obj is None:
            self.module.fail_json(msg="Failed to find the cluster %s" % self.cluster_name)
        # Sanity check for virtual machines
        self.vm_obj_list = []
        if self.state == 'present':
            # Get list of VMs only if state is present
            self.vm_obj_list = self.get_all_vms_info()
    def execute(self):
        result = dict(changed=False)

        datacenter = self.find_datacenter_by_name(self.datacenter)
        if not datacenter:
            self.module.fail_json(msg="Cannot find the specified Datacenter: %s" % self.datacenter)

        dcpath = compile_folder_path_for_object(datacenter)
        if not dcpath.endswith("/"):
            dcpath += "/"

        if(self.folder in [None, "", "/"]):
            self.module.fail_json(msg="Please specify folder path other than blank or '/'")
        elif(self.folder.startswith("/vm")):
            fullpath = "%s%s%s" % (dcpath, self.datacenter, self.folder)
        else:
            fullpath = "%s%s" % (dcpath, self.folder)

        folder_obj = self.content.searchIndex.FindByInventoryPath(inventoryPath="%s" % fullpath)
        if not folder_obj:
            details = {
                'datacenter': datacenter.name,
                'datacenter_path': dcpath,
                'folder': self.folder,
                'full_search_path': fullpath,
            }
            self.module.fail_json(msg="No folder %s matched in the search path : %s" % (self.folder, fullpath),
                                  details=details)

        if self.state == "present":
            if self.get_vm():
                self.module.exit_json(**result)

            if self.esxi_hostname:
                host_obj = self.find_hostsystem_by_name(self.esxi_hostname)
                if not host_obj:
                    self.module.fail_json(msg="Cannot find the specified ESXi host: %s" % self.esxi_hostname)
            else:
                host_obj = None

            if self.cluster:
                cluster_obj = find_cluster_by_name(self.content, self.cluster, datacenter)
                if not cluster_obj:
                    self.module.fail_json(msg="Cannot find the specified cluster name: %s" % self.cluster)

                resource_pool_obj = cluster_obj.resourcePool
            elif self.resource_pool:
                resource_pool_obj = find_resource_pool_by_name(self.content, self.resource_pool)
                if not resource_pool_obj:
                    self.module.fail_json(msg="Cannot find the specified resource pool: %s" % self.resource_pool)
            else:
                resource_pool_obj = host_obj.parent.resourcePool

            task = folder_obj.RegisterVM_Task(path=self.path, name=self.name, asTemplate=self.template,
                                              pool=resource_pool_obj, host=host_obj)

            changed = False
            try:
                changed, info = wait_for_task(task)
            except Exception as task_e:
                self.module.fail_json(msg=to_native(task_e))

            result.update(changed=changed)
            self.module.exit_json(**result)

        if self.state == "absent":
            vm_obj = self.get_vm()
            if vm_obj:
                try:
                    vm_obj.UnregisterVM()
                    result.update(changed=True)
                except Exception as exc:
                    self.module.fail_json(msg=to_native(exc))

            self.module.exit_json(**result)
Exemple #14
0
    def __init__(self,
                 module,
                 cluster_name,
                 group_name,
                 state,
                 datacenter_name=None,
                 vm_list=None,
                 host_list=None):
        """
        Init
        """

        super(VmwareDrsGroupManager, self).__init__(module)

        self.__datacenter_name = datacenter_name
        self.__datacenter_obj = None
        self.__cluster_name = cluster_name
        self.__cluster_obj = None
        self.__group_name = group_name
        self.__group_obj = None
        self.__operation = None
        self.__vm_list = vm_list
        self.__vm_obj_list = []
        self.__host_list = host_list
        self.__host_obj_list = []
        self.__msg = 'Nothing to see here...'
        self.__result = dict()
        self.__changed = False
        self.__state = state

        if datacenter_name is not None:

            self.__datacenter_obj = find_datacenter_by_name(
                self.content, self.__datacenter_name)

            if self.__datacenter_obj is None:
                raise Exception("Datacenter '%s' not found" %
                                self.__datacenter_name)

        self.__cluster_obj = find_cluster_by_name(
            content=self.content,
            cluster_name=self.__cluster_name,
            datacenter=self.__datacenter_obj)

        # Throw error if cluster does not exist
        if self.__cluster_obj is None:
            if not module.check_mode:
                raise Exception("Cluster '%s' not found" % self.__cluster_name)
        else:
            # get group
            self.__group_obj = self.__get_group_by_name()
            # Set result here. If nothing is to be updated, result is already set
            self.__set_result(self.__group_obj)

        # Do not populate lists if we are deleting group
        if state == 'present':

            if self.__group_obj:
                self.__operation = 'edit'
            else:
                self.__operation = 'add'

            if self.__vm_list is not None:
                self.__set_vm_obj_list(vm_list=self.__vm_list)

            if self.__host_list is not None:
                self.__set_host_obj_list(host_list=self.__host_list)
        else:
            self.__operation = 'remove'