Example #1
0
    def get_all_objs(self, content, types, confine_to_datacenter=True):
        """ Wrapper around get_all_objs to set datacenter context """
        objects = get_all_objs(content, types)
        if confine_to_datacenter:
            if hasattr(objects, 'items'):
                # resource pools come back as a dictionary
                for k, v in tuple(objects.items()):
                    parent_dc = get_parent_datacenter(k)
                    if parent_dc.name != self.dc_name:
                        del objects[k]
            else:
                # everything else should be a list
                objects = [x for x in objects if get_parent_datacenter(x).name == self.dc_name]

        return objects
Example #2
0
    def generate_http_access_url(self, file_path):
        # e.g., file_path is like this format: [datastore0] test_vm/test_vm-1.png
        # from file_path generate URL
        url_path = None
        if not file_path:
            return url_path

        path = "/folder/%s" % quote(file_path.split()[1])
        params = dict(dsName=file_path.split()[0].strip('[]'))
        if not self.is_vcenter():
            datacenter = 'ha-datacenter'
        else:
            datacenter = get_parent_datacenter(self.current_vm_obj).name.replace('&', '%26')
        params['dcPath'] = datacenter
        url_path = "https://%s%s?%s" % (self.params['hostname'], path, urlencode(params))

        return url_path
    def gather_cluster_info(self):
        """
        Gather information about cluster
        """
        results = dict(changed=False, clusters=dict())

        if self.schema == 'summary':
            for cluster in self.cluster_objs:
                # Default values
                ha_failover_level = None
                ha_restart_priority = None
                ha_vm_tools_monitoring = None
                ha_vm_min_up_time = None
                ha_vm_max_failures = None
                ha_vm_max_failure_window = None
                ha_vm_failure_interval = None
                enabled_vsan = False
                vsan_auto_claim_storage = False
                hosts = []

                # Hosts
                for host in cluster.host:
                    hosts.append({
                        'name':
                        host.name,
                        'folder':
                        self.get_vm_path(self.content, host),
                    })

                # HA
                das_config = cluster.configurationEx.dasConfig
                if das_config.admissionControlPolicy:
                    ha_failover_level = das_config.admissionControlPolicy.failoverLevel
                if das_config.defaultVmSettings:
                    ha_restart_priority = das_config.defaultVmSettings.restartPriority,
                    ha_vm_tools_monitoring = das_config.defaultVmSettings.vmToolsMonitoringSettings.vmMonitoring,
                    ha_vm_min_up_time = das_config.defaultVmSettings.vmToolsMonitoringSettings.minUpTime,
                    ha_vm_max_failures = das_config.defaultVmSettings.vmToolsMonitoringSettings.maxFailures,
                    ha_vm_max_failure_window = das_config.defaultVmSettings.vmToolsMonitoringSettings.maxFailureWindow,
                    ha_vm_failure_interval = das_config.defaultVmSettings.vmToolsMonitoringSettings.failureInterval,

                # DRS
                drs_config = cluster.configurationEx.drsConfig

                # VSAN
                if hasattr(cluster.configurationEx, 'vsanConfigInfo'):
                    vsan_config = cluster.configurationEx.vsanConfigInfo
                    enabled_vsan = vsan_config.enabled
                    vsan_auto_claim_storage = vsan_config.defaultConfig.autoClaimStorage

                tag_info = []
                if self.params.get('show_tag'):
                    vmware_client = VmwareRestClient(self.module)
                    tag_info = vmware_client.get_tags_for_cluster(
                        cluster_mid=cluster._moId)

                resource_summary = self.to_json(cluster.GetResourceUsage())
                if '_vimtype' in resource_summary:
                    del resource_summary['_vimtype']

                results['clusters'][unquote(cluster.name)] = dict(
                    hosts=hosts,
                    enable_ha=das_config.enabled,
                    ha_failover_level=ha_failover_level,
                    ha_vm_monitoring=das_config.vmMonitoring,
                    ha_host_monitoring=das_config.hostMonitoring,
                    ha_admission_control_enabled=das_config.
                    admissionControlEnabled,
                    ha_restart_priority=ha_restart_priority,
                    ha_vm_tools_monitoring=ha_vm_tools_monitoring,
                    ha_vm_min_up_time=ha_vm_min_up_time,
                    ha_vm_max_failures=ha_vm_max_failures,
                    ha_vm_max_failure_window=ha_vm_max_failure_window,
                    ha_vm_failure_interval=ha_vm_failure_interval,
                    enabled_drs=drs_config.enabled,
                    drs_enable_vm_behavior_overrides=drs_config.
                    enableVmBehaviorOverrides,
                    drs_default_vm_behavior=drs_config.defaultVmBehavior,
                    drs_vmotion_rate=drs_config.vmotionRate,
                    enabled_vsan=enabled_vsan,
                    vsan_auto_claim_storage=vsan_auto_claim_storage,
                    tags=tag_info,
                    resource_summary=resource_summary,
                    moid=cluster._moId,
                    datacenter=get_parent_datacenter(cluster).name)
        else:
            for cluster in self.cluster_objs:
                results['clusters'][unquote(cluster.name)] = self.to_json(
                    cluster, self.properties)

        self.module.exit_json(**results)
Example #4
0
    def sanitize_network_params(self):
        network_list = []
        valid_state = ['new', 'present', 'absent']
        if len(self.params['networks']) != 0:
            for network in self.params['networks']:
                if 'state' not in network or network['state'].lower(
                ) not in valid_state:
                    self.module.fail_json(
                        msg=
                        "Network adapter state not specified or invalid: '%s', valid values: "
                        "%s" % (network.get('state', ''), valid_state))
                # add new network adapter but no name specified
                if network['state'].lower(
                ) == 'new' and 'name' not in network and 'vlan' not in network:
                    self.module.fail_json(
                        msg=
                        "Please specify at least network name or VLAN name for adding new network adapter."
                    )
                if network['state'].lower() == 'new' and 'mac' in network:
                    self.module.fail_json(
                        msg=
                        "networks.mac is used for vNIC reconfigure, but networks.state is set to 'new'."
                    )
                if network['state'].lower(
                ) == 'present' and 'mac' not in network and 'label' not in network and 'device_type' not in network:
                    self.module.fail_json(
                        msg=
                        "Should specify 'mac', 'label' or 'device_type' parameter to reconfigure network adapter"
                    )
                if 'connected' in network:
                    if not isinstance(network['connected'], bool):
                        self.module.fail_json(
                            msg=
                            "networks.connected parameter should be boolean.")
                    if network['state'].lower(
                    ) == 'new' and not network['connected']:
                        network['start_connected'] = False
                if 'start_connected' in network:
                    if not isinstance(network['start_connected'], bool):
                        self.module.fail_json(
                            msg=
                            "networks.start_connected parameter should be boolean."
                        )
                    if network['state'].lower(
                    ) == 'new' and not network['start_connected']:
                        network['connected'] = False
                # specified network does not exist
                if 'name' in network and not self.network_exists_by_name(
                        network['name']):
                    self.module.fail_json(
                        msg="Network '%(name)s' does not exist." % network)
                elif 'vlan' in network:
                    objects = get_all_objs(
                        self.content, [vim.dvs.DistributedVirtualPortgroup])
                    dvps = [
                        x for x in objects
                        if to_text(get_parent_datacenter(x).name) == to_text(
                            self.params['datacenter'])
                    ]
                    for dvp in dvps:
                        if hasattr(dvp.config.defaultPortConfig, 'vlan') and \
                                isinstance(dvp.config.defaultPortConfig.vlan.vlanId, int) and \
                                str(dvp.config.defaultPortConfig.vlan.vlanId) == str(network['vlan']):
                            network['name'] = dvp.config.name
                            break
                        if 'dvswitch_name' in network and \
                                dvp.config.distributedVirtualSwitch.name == network['dvswitch_name'] and \
                                dvp.config.name == network['vlan']:
                            network['name'] = dvp.config.name
                            break
                        if dvp.config.name == network['vlan']:
                            network['name'] = dvp.config.name
                            break
                    else:
                        self.module.fail_json(
                            msg="VLAN '%(vlan)s' does not exist." % network)

                if 'device_type' in network and network[
                        'device_type'] not in list(
                            self.nic_device_type.keys()):
                    self.module.fail_json(
                        msg="Device type specified '%s' is invalid. "
                        "Valid types %s " %
                        (network['device_type'],
                         list(self.nic_device_type.keys())))

                if ('mac' in network and not is_mac(network['mac'])) or \
                        ('manual_mac' in network and not is_mac(network['manual_mac'])):
                    self.module.fail_json(
                        msg=
                        "Device MAC address '%s' or manual set MAC address %s is invalid. "
                        "Please provide correct MAC address." %
                        (network['mac'], network['manual_mac']))

                network_list.append(network)

        return network_list
Example #5
0
    def get_virtual_machines(self):
        """
        Get one/all virtual machines and related configurations information.
        """
        folder = self.params.get('folder')
        folder_obj = None
        if folder:
            folder_obj = self.content.searchIndex.FindByInventoryPath(folder)
            if not folder_obj:
                self.module.fail_json(msg="Failed to find folder specified by %(folder)s" % self.params)

        vm_name = self.params.get('vm_name')
        if vm_name:
            virtual_machine = find_vm_by_name(self.content, vm_name=vm_name, folder=folder_obj)
            if not virtual_machine:
                self.module.fail_json(msg="Failed to find virtual machine %s" % vm_name)
            else:
                virtual_machines = [virtual_machine]
        else:
            virtual_machines = get_all_objs(self.content, [vim.VirtualMachine], folder=folder_obj)
        _virtual_machines = []

        for vm in virtual_machines:
            _ip_address = ""
            summary = vm.summary
            if summary.guest is not None:
                _ip_address = summary.guest.ipAddress
                if _ip_address is None:
                    _ip_address = ""
            _mac_address = []
            all_devices = _get_vm_prop(vm, ('config', 'hardware', 'device'))
            if all_devices:
                for dev in all_devices:
                    if isinstance(dev, vim.vm.device.VirtualEthernetCard):
                        _mac_address.append(dev.macAddress)

            net_dict = {}
            vmnet = _get_vm_prop(vm, ('guest', 'net'))
            if vmnet:
                for device in vmnet:
                    net_dict[device.macAddress] = dict()
                    net_dict[device.macAddress]['ipv4'] = []
                    net_dict[device.macAddress]['ipv6'] = []
                    for ip_addr in device.ipAddress:
                        if "::" in ip_addr:
                            net_dict[device.macAddress]['ipv6'].append(ip_addr)
                        else:
                            net_dict[device.macAddress]['ipv4'].append(ip_addr)

            esxi_hostname = None
            esxi_parent = None
            if summary.runtime.host:
                esxi_hostname = summary.runtime.host.summary.config.name
                esxi_parent = summary.runtime.host.parent

            cluster_name = None
            if esxi_parent and isinstance(esxi_parent, vim.ClusterComputeResource):
                cluster_name = summary.runtime.host.parent.name

            vm_attributes = dict()
            if self.module.params.get('show_attribute'):
                vm_attributes = self.get_vm_attributes(vm)

            vm_tags = list()
            if self.module.params.get('show_tag'):
                vm_tags = self.get_tag_info(vm)

            vm_folder = PyVmomi.get_vm_path(content=self.content, vm_name=vm)
            datacenter = get_parent_datacenter(vm)
            datastore_url = list()
            datastore_attributes = ('name', 'url')
            if vm.config.datastoreUrl:
                for entry in vm.config.datastoreUrl:
                    datastore_url.append({key: getattr(entry, key) for key in dir(entry) if key in datastore_attributes})
            virtual_machine = {
                "guest_name": summary.config.name,
                "guest_fullname": summary.config.guestFullName,
                "power_state": summary.runtime.powerState,
                "ip_address": _ip_address,  # Kept for backward compatibility
                "mac_address": _mac_address,  # Kept for backward compatibility
                "uuid": summary.config.uuid,
                "vm_network": net_dict,
                "esxi_hostname": esxi_hostname,
                "datacenter": datacenter.name,
                "cluster": cluster_name,
                "attributes": vm_attributes,
                "tags": vm_tags,
                "folder": vm_folder,
                "moid": vm._moId,
                "datastore_url": datastore_url,
            }

            vm_type = self.module.params.get('vm_type')
            is_template = _get_vm_prop(vm, ('config', 'template'))
            if vm_type == 'vm' and not is_template:
                _virtual_machines.append(virtual_machine)
            elif vm_type == 'template' and is_template:
                _virtual_machines.append(virtual_machine)
            elif vm_type == 'all':
                _virtual_machines.append(virtual_machine)
        return _virtual_machines