def get_object(self):
        # find_obj doesn't include rootFolder
        if self.params['object_type'] == 'Folder' and self.params[
                'object_name'] == 'rootFolder':
            self.current_obj = self.content.rootFolder
            return
        try:
            object_type = getattr(vim, self.params['object_type'])
        except AttributeError:
            self.module.fail_json(msg="Object type %s is not valid." %
                                  self.params['object_type'])
        self.current_obj = find_obj(
            content=self.content,
            vimtype=[getattr(vim, self.params['object_type'])],
            name=self.params['object_name'])

        if self.current_obj is None:
            self.module.fail_json(
                msg="Specified object %s of type %s was not found." %
                (self.params['object_name'], self.params['object_type']))
        if self.params['object_type'] == 'DistributedVirtualSwitch':
            msg = "You are applying permissions to a Distributed vSwitch. " \
                  "This will probably fail, since Distributed vSwitches inherits permissions " \
                  "from the datacenter or a folder level. " \
                  "Define permissions on the datacenter or the folder containing the switch."
            self.module.warn(msg)
    def __init__(self, module):
        super(VmwareHostSnmp, self).__init__(module)

        if self.is_vcenter():
            self.module.fail_json(
                msg="You have to connect directly to the ESXi host. "
                "It's not possible to configure SNMP through a vCenter connection."
            )
        else:
            self.host = find_obj(self.content, [vim.HostSystem], None)
            if self.host is None:
                self.module.fail_json(msg="Failed to find host system.")
    def __init__(self, module):
        super(VMwareHostFactManager, self).__init__(module)
        esxi_host_name = self.params.get('esxi_hostname', None)
        if self.is_vcenter():
            if esxi_host_name is None:
                self.module.fail_json(msg="Connected to a vCenter system without specifying esxi_hostname")
            self.host = self.get_all_host_objs(esxi_host_name=esxi_host_name)
            if len(self.host) > 1:
                self.module.fail_json(msg="esxi_hostname matched multiple hosts")
            self.host = self.host[0]
        else:
            self.host = find_obj(self.content, [vim.HostSystem], None)

        if self.host is None:
            self.module.fail_json(msg="Failed to find host system.")
Exemple #4
0
    def get_object(self):
        # find_obj doesn't include rootFolder
        if self.params['object_type'] == 'Folder' and self.params[
                'object_name'] == 'rootFolder':
            self.current_obj = self.content.rootFolder
            return
        try:
            object_type = getattr(vim, self.params['object_type'])
        except AttributeError:
            self.module.fail_json(msg="Object type %s is not valid." %
                                  self.params['object_type'])
        self.current_obj = find_obj(
            content=self.content,
            vimtype=[getattr(vim, self.params['object_type'])],
            name=self.params['object_name'])

        if self.current_obj is None:
            self.module.fail_json(
                msg="Specified object %s of type %s was not found." %
                (self.params['object_name'], self.params['object_type']))
    def __init__(self, module):
        super(VMwareHostDatastore, self).__init__(module)

        # NOTE: The below parameter is deprecated starting from Ansible v2.11
        self.datacenter_name = module.params['datacenter_name']
        self.datastore_name = module.params['datastore_name']
        self.datastore_type = module.params['datastore_type']
        self.nfs_server = module.params['nfs_server']
        self.nfs_path = module.params['nfs_path']
        self.nfs_ro = module.params['nfs_ro']
        self.vmfs_device_name = module.params['vmfs_device_name']
        self.vmfs_version = module.params['vmfs_version']
        self.esxi_hostname = module.params['esxi_hostname']
        self.state = module.params['state']

        if self.is_vcenter():
            if not self.esxi_hostname:
                self.module.fail_json(msg="esxi_hostname is mandatory with a vcenter")
            self.esxi = self.find_hostsystem_by_name(self.esxi_hostname)
            if self.esxi is None:
                self.module.fail_json(msg="Failed to find ESXi hostname %s" % self.esxi_hostname)
        else:
            self.esxi = find_obj(self.content, [vim.HostSystem], None)
    def sanitize_disk_inputs(self):
        """
        Check correctness of disk input provided by user
        Returns: A list of dictionary containing disk information

        """
        disks_data = list()
        if not self.desired_disks:
            self.module.exit_json(changed=False,
                                  msg="No disks provided for virtual"
                                  " machine '%s' for management." %
                                  self.vm.name)

        for disk_index, disk in enumerate(self.desired_disks):
            # Initialize default value for disk
            current_disk = dict(disk_index=disk_index,
                                state='present',
                                datastore=None,
                                autoselect_datastore=True,
                                disk_unit_number=0,
                                scsi_controller=0)
            # Check state
            if 'state' in disk:
                if disk['state'] not in ['absent', 'present']:
                    self.module.fail_json(
                        msg="Invalid state provided '%s' for disk index [%s]."
                        " State can be either - 'absent', 'present'" %
                        (disk['state'], disk_index))
                else:
                    current_disk['state'] = disk['state']

            if current_disk['state'] == 'present':
                # Select datastore or datastore cluster
                if 'datastore' in disk:
                    if 'autoselect_datastore' in disk:
                        self.module.fail_json(
                            msg="Please specify either 'datastore' "
                            "or 'autoselect_datastore' for disk index [%s]" %
                            disk_index)

                    # Check if given value is datastore or datastore cluster
                    datastore_name = disk['datastore']
                    datastore_cluster = find_obj(self.content,
                                                 [vim.StoragePod],
                                                 datastore_name)
                    if datastore_cluster:
                        # If user specified datastore cluster so get recommended datastore
                        datastore_name = self.get_recommended_datastore(
                            datastore_cluster_obj=datastore_cluster)
                    # Check if get_recommended_datastore or user specified datastore exists or not
                    datastore = find_obj(self.content, [vim.Datastore],
                                         datastore_name)
                    if datastore is None:
                        self.module.fail_json(
                            msg="Failed to find datastore named '%s' "
                            "in given configuration." % disk['datastore'])
                    current_disk['datastore'] = datastore
                    current_disk['autoselect_datastore'] = False
                elif 'autoselect_datastore' in disk:
                    # Find datastore which fits requirement
                    datastores = get_all_objs(self.content, [vim.Datastore])
                    if not datastores:
                        self.module.fail_json(
                            msg="Failed to gather information about"
                            " available datastores in given datacenter.")
                    datastore = None
                    datastore_freespace = 0
                    for ds in datastores:
                        if ds.summary.freeSpace > datastore_freespace:
                            # If datastore field is provided, filter destination datastores
                            datastore = ds
                            datastore_freespace = ds.summary.freeSpace
                    current_disk['datastore'] = datastore

                if 'datastore' not in disk and 'autoselect_datastore' not in disk:
                    self.module.fail_json(
                        msg="Either 'datastore' or 'autoselect_datastore' is"
                        " required parameter while creating disk for "
                        "disk index [%s]." % disk_index)

                if [
                        x for x in disk.keys()
                        if x.startswith('size_') or x == 'size'
                ]:
                    # size, size_tb, size_gb, size_mb, size_kb
                    disk_size_parse_failed = False
                    if 'size' in disk:
                        size_regex = re.compile(
                            r'(\d+(?:\.\d+)?)([tgmkTGMK][bB])')
                        disk_size_m = size_regex.match(disk['size'])
                        if disk_size_m:
                            expected = disk_size_m.group(1)
                            unit = disk_size_m.group(2)
                        else:
                            disk_size_parse_failed = True
                        try:
                            if re.match(r'\d+\.\d+', expected):
                                # We found float value in string, let's typecast it
                                expected = float(expected)
                            else:
                                # We found int value in string, let's typecast it
                                expected = int(expected)
                        except (TypeError, ValueError, NameError):
                            disk_size_parse_failed = True
                    else:
                        # Even multiple size_ parameter provided by user,
                        # consider first value only
                        param = [
                            x for x in disk.keys() if x.startswith('size_')
                        ][0]
                        unit = param.split('_')[-1]
                        disk_size = disk[param]
                        if isinstance(disk_size, (float, int)):
                            disk_size = str(disk_size)

                        try:
                            if re.match(r'\d+\.\d+', disk_size):
                                # We found float value in string, let's typecast it
                                expected = float(disk_size)
                            else:
                                # We found int value in string, let's typecast it
                                expected = int(disk_size)
                        except (TypeError, ValueError, NameError):
                            disk_size_parse_failed = True

                    if disk_size_parse_failed:
                        # Common failure
                        self.module.fail_json(
                            msg="Failed to parse disk size for disk index [%s],"
                            " please review value provided"
                            " using documentation." % disk_index)

                    disk_units = dict(tb=3, gb=2, mb=1, kb=0)
                    unit = unit.lower()
                    if unit in disk_units:
                        current_disk['size'] = expected * (1024**
                                                           disk_units[unit])
                    else:
                        self.module.fail_json(
                            msg=
                            "%s is not a supported unit for disk size for disk index [%s]."
                            " Supported units are ['%s']." %
                            (unit, disk_index, "', '".join(disk_units.keys())))

                else:
                    # No size found but disk, fail
                    self.module.fail_json(
                        msg="No size, size_kb, size_mb, size_gb or size_tb"
                        " attribute found into disk index [%s] configuration."
                        % disk_index)
            # Check SCSI controller key
            if 'scsi_controller' in disk:
                try:
                    temp_disk_controller = int(disk['scsi_controller'])
                except ValueError:
                    self.module.fail_json(
                        msg="Invalid SCSI controller ID '%s' specified"
                        " at index [%s]" %
                        (disk['scsi_controller'], disk_index))
                if temp_disk_controller not in range(0, 4):
                    # Only 4 SCSI controllers are allowed per VM
                    self.module.fail_json(
                        msg="Invalid SCSI controller ID specified [%s],"
                        " please specify value between 0 to 3 only." %
                        temp_disk_controller)
                current_disk['scsi_controller'] = temp_disk_controller
            else:
                self.module.fail_json(
                    msg="Please specify 'scsi_controller' under disk parameter"
                    " at index [%s], which is required while creating disk." %
                    disk_index)
            # Check for disk unit number
            if 'unit_number' in disk:
                try:
                    temp_disk_unit_number = int(disk['unit_number'])
                except ValueError:
                    self.module.fail_json(
                        msg="Invalid Disk unit number ID '%s'"
                        " specified at index [%s]" %
                        (disk['unit_number'], disk_index))
                if temp_disk_unit_number not in range(0, 16):
                    self.module.fail_json(
                        msg=
                        "Invalid Disk unit number ID specified for disk [%s] at index [%s],"
                        " please specify value between 0 to 15"
                        " only (excluding 7)." %
                        (temp_disk_unit_number, disk_index))

                if temp_disk_unit_number == 7:
                    self.module.fail_json(
                        msg=
                        "Invalid Disk unit number ID specified for disk at index [%s],"
                        " please specify value other than 7 as it is reserved"
                        "for SCSI Controller" % disk_index)
                current_disk['disk_unit_number'] = temp_disk_unit_number

            else:
                self.module.fail_json(
                    msg="Please specify 'unit_number' under disk parameter"
                    " at index [%s], which is required while creating disk." %
                    disk_index)

            # Type of Disk
            disk_type = disk.get('type', 'thick').lower()
            if disk_type not in ['thin', 'thick', 'eagerzeroedthick']:
                self.module.fail_json(
                    msg=
                    "Invalid 'disk_type' specified for disk index [%s]. Please specify"
                    " 'disk_type' value from ['thin', 'thick', 'eagerzeroedthick']."
                    % disk_index)
            current_disk['disk_type'] = disk_type

            # SCSI Controller Type
            scsi_contrl_type = disk.get('scsi_type', 'paravirtual').lower()
            if scsi_contrl_type not in self.scsi_device_type.keys():
                self.module.fail_json(
                    msg=
                    "Invalid 'scsi_type' specified for disk index [%s]. Please specify"
                    " 'scsi_type' value from ['%s']" %
                    (disk_index, "', '".join(self.scsi_device_type.keys())))
            current_disk['scsi_type'] = scsi_contrl_type

            disks_data.append(current_disk)
        return disks_data