def sanitize_params(self): ''' this method is used to verify user provided parameters ''' self.vm_obj = self.get_vm() if self.vm_obj is None: vm_id = self.vm_uuid or self.vm_name or self.moid self.module.fail_json( msg="Failed to find the VM/template with %s" % vm_id) # connect to destination VC self.destination_content = connect_to_api( self.module, hostname=self.destination_vcenter, username=self.destination_vcenter_username, password=self.destination_vcenter_password, port=self.destination_vcenter_port, validate_certs=self.destination_vcenter_validate_certs) # Check if vm name already exists in the destination VC vm = find_vm_by_name(content=self.destination_content, vm_name=self.params['destination_vm_name']) if vm: self.module.exit_json( changed=False, msg="A VM with the given name already exists") datastore_name = self.params['destination_datastore'] datastore_cluster = find_obj(self.destination_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 self.destination_datastore = find_datastore_by_name( content=self.destination_content, datastore_name=datastore_name) if self.destination_datastore is None: self.module.fail_json(msg="Destination datastore not found.") self.destination_host = find_hostsystem_by_name( content=self.destination_content, hostname=self.params['destination_host']) if self.destination_host is None: self.module.fail_json(msg="Destination host not found.") if self.params['destination_resource_pool']: self.destination_resource_pool = find_resource_pool_by_name( content=self.destination_content, resource_pool_name=self.params['destination_resource_pool']) else: self.destination_resource_pool = self.destination_host.parent.resourcePool
def get_vm_port(self, vm_name, nic_label): """Finds the port of the VM Returns ------- str the port number as a string, or None if the NIC couldnt be found """ vm = find_vm_by_name(self.content, vm_name) if vm is None: self.module.fail_json(msg="There is no VM with the name: {0:s}.".format(vm_name)) for hardware in vm.config.hardware.device: if isinstance(hardware, vim.vm.device.VirtualVmxnet3): if hardware.deviceInfo.label == nic_label: return hardware.backing.port.portKey return None
def get_new_vm_info(self, vm): # to check if vm has been cloned in the destination vc # query for the vm in destination vc # get the host and datastore info info = {} vm_obj = find_vm_by_name(content=self.destination_content, vm_name=vm) if vm_obj is None: self.module.fail_json( msg="Newly Instant cloned VM is not found in the VCenter") vm_facts = self.gather_facts(vm_obj) info['vm_name'] = vm info['vcenter'] = self.hostname info['host'] = vm_facts['hw_esxi_host'] info['datastore'] = vm_facts['hw_datastores'] info['vm_folder'] = vm_facts['hw_folder'] return info
def get_new_vm_info(self, vm): # to check if vm has been cloned in the destination vc # query for the vm in destination vc # get the host and datastore info # get the power status of the newly cloned vm info = {} vm_obj = find_vm_by_name(content=self.destination_content, vm_name=vm) if vm_obj is None: self.module.fail_json(msg="Newly cloned VM is not found in the destination VCenter") else: vm_facts = gather_vm_facts(self.destination_content, vm_obj) info['vm_name'] = vm info['vcenter'] = self.destination_vcenter info['host'] = vm_facts['hw_esxi_host'] info['datastore'] = vm_facts['hw_datastores'] info['vm_folder'] = vm_facts['hw_folder'] info['power_on'] = vm_facts['hw_power_status'] return info
def get_lease(self): datastore, datacenter, resource_pool, network_mappings = self.get_objects() params = { 'diskProvisioning': self.params['disk_provisioning'], } if self.params['name']: params['entityName'] = self.params['name'] if network_mappings: params['networkMapping'] = network_mappings if self.params['deployment_option']: params['deploymentOption'] = self.params['deployment_option'] if self.params['properties']: params['propertyMapping'] = [] for key, value in self.params['properties'].items(): property_mapping = vim.KeyValue() property_mapping.key = key property_mapping.value = str(value) if isinstance(value, bool) else value params['propertyMapping'].append(property_mapping) if self.params['folder']: folder = self.content.searchIndex.FindByInventoryPath(self.params['folder']) if not folder: self.module.fail_json(msg="Unable to find the specified folder %(folder)s" % self.params) else: folder = datacenter.vmFolder spec_params = vim.OvfManager.CreateImportSpecParams(**params) ovf_descriptor = self.get_ovf_descriptor() self.import_spec = self.content.ovfManager.CreateImportSpec( ovf_descriptor, resource_pool, datastore, spec_params ) errors = [to_native(e.msg) for e in getattr(self.import_spec, 'error', [])] if self.params['fail_on_spec_warnings']: errors.extend( (to_native(w.msg) for w in getattr(self.import_spec, 'warning', [])) ) if errors: self.module.fail_json( msg='Failure validating OVF import spec: %s' % '. '.join(errors) ) for warning in getattr(self.import_spec, 'warning', []): self.module.warn('Problem validating OVF import spec: %s' % to_native(warning.msg)) name = self.params.get('name') if not self.params['allow_duplicates']: name = self.import_spec.importSpec.configSpec.name match = find_vm_by_name(self.content, name, folder=folder) if match: self.module.exit_json(instance=gather_vm_facts(self.content, match), changed=False) if self.module.check_mode: self.module.exit_json(changed=True, instance={'hw_name': name}) try: self.lease = resource_pool.ImportVApp( self.import_spec.importSpec, folder ) except vmodl.fault.SystemError as e: self.module.fail_json( msg='Failed to start import: %s' % to_native(e.msg) ) while self.lease.state != vim.HttpNfcLease.State.ready: time.sleep(0.1) self.entity = self.lease.info.entity return self.lease, self.import_spec
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
def sanitize_params(self): ''' Verify user-provided parameters ''' # connect to host/VC self.destination_content = connect_to_api( self.module, hostname=self.hostname, username=self.username, password=self.password, port=self.port, validate_certs=self.validate_certs) use_instance_uuid = self.params.get('use_instance_uuid') or False if 'parent_vm' in self.params and self.params['parent_vm']: self.vm_obj = find_vm_by_name(content=self.destination_content, vm_name=self.parent_vm) elif 'uuid' in self.params and self.params['uuid']: if not use_instance_uuid: self.vm_obj = find_vm_by_id(content=self.destination_content, vm_id=self.params['uuid'], vm_id_type="uuid") elif use_instance_uuid: self.vm_obj = find_vm_by_id(content=self.destination_content, vm_id=self.params['uuid'], vm_id_type="instance_uuid") elif 'moid' in self.params and self.params['moid']: self.vm_obj = vim.VirtualMachine(self.params['moid'], self.si._stub) if self.vm_obj is None: vm_id = self.parent_vm or self.uuid or self.moid self.module.fail_json( msg="Failed to find the VM/template with %s" % vm_id) vm = find_vm_by_name(content=self.destination_content, vm_name=self.params['name']) if vm: self.module.exit_json( changed=False, msg="A VM with the given name already exists") self.datacenter = self.find_datacenter_by_name( self.params['datacenter']) # datacentre check if self.datacenter is None: self.module.fail_json(msg="Datacenter not found.") datastore_name = self.params['datastore'] datastore_cluster = find_obj(self.destination_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 check self.datastore = self.find_datastore_by_name( datastore_name=datastore_name) if self.datastore is None: self.module.fail_json(msg="Datastore not found.") if self.params['folder']: self.folder = self.find_folder_by_name( folder_name=self.params['folder']) if self.folder is None: self.module.fail_json(msg="Folder not found.") else: self.folder = self.datacenter.vmFolder self.host = self.find_hostsystem_by_name(host_name=self.params['host']) if self.host is None: self.module.fail_json(msg="Host not found.") if self.params['resource_pool']: self.resource_pool = self.find_resource_pool_by_name( resource_pool_name=self.params['resource_pool']) if self.resource_pool is None: self.module.fail_json(msg="Resource Pool not found.") else: self.resource_pool = self.host.parent.resourcePool
def Instant_clone(self): # clone the vm on VC if self.vm_obj is None: vm_id = self.parent_vm or self.uuid or self.moid self.module.fail_json( msg="Failed to find the VM/template with %s" % vm_id) try: task = self.vm_obj.InstantClone_Task(spec=self.instant_clone_spec) wait_for_task(task) vm_info = self.get_new_vm_info(self.vm_name) result = {'changed': True, 'failed': False, 'vm_info': vm_info} except TaskError as task_e: self.module.fail_json(msg=to_native(task_e)) self.destination_content = connect_to_api( self.module, hostname=self.hostname, username=self.username, password=self.password, port=self.port, validate_certs=self.validate_certs) vm_IC = find_vm_by_name(content=self.destination_content, vm_name=self.params['name']) if vm_IC and self.params.get('guestinfo_vars'): guest_custom_mng = self.destination_content.guestCustomizationManager # Make an object for authentication in a guest OS auth_obj = vim.vm.guest.NamePasswordAuthentication() guest_user = self.params.get('vm_username') guest_password = self.params.get('vm_password') auth_obj.username = guest_user auth_obj.password = guest_password guestinfo_vars = self.params.get('guestinfo_vars') # Make a spec object to customize Guest OS customization_spec = vim.vm.customization.Specification() customization_spec.globalIPSettings = vim.vm.customization.GlobalIPSettings( ) customization_spec.globalIPSettings.dnsServerList = [ guestinfo_vars[0]['dns'] ] # Make an identity object to do linux prep # The params are reflected the specified following after rebooting OS customization_spec.identity = vim.vm.customization.LinuxPrep() customization_spec.identity.domain = guestinfo_vars[0]['domain'] customization_spec.identity.hostName = vim.vm.customization.FixedName( ) customization_spec.identity.hostName.name = guestinfo_vars[0][ 'hostname'] customization_spec.nicSettingMap = [] adapter_mapping_obj = vim.vm.customization.AdapterMapping() adapter_mapping_obj.adapter = vim.vm.customization.IPSettings() adapter_mapping_obj.adapter.ip = vim.vm.customization.FixedIp() adapter_mapping_obj.adapter.ip.ipAddress = guestinfo_vars[0][ 'ipaddress'] adapter_mapping_obj.adapter.subnetMask = guestinfo_vars[0][ 'netmask'] adapter_mapping_obj.adapter.gateway = [ guestinfo_vars[0]['gateway'] ] customization_spec.nicSettingMap.append(adapter_mapping_obj) try: task_guest = guest_custom_mng.CustomizeGuest_Task( vm_IC, auth_obj, customization_spec) wait_for_task(task_guest) vm_info = self.get_new_vm_info(self.vm_name) result = {'changed': True, 'failed': False, 'vm_info': vm_info} except TaskError as task_e: self.module.fail_json(msg=to_native(task_e)) # Should require rebooting to reflect customization parameters to instant clone vm. instant_vm_obj = find_vm_by_id(content=self.content, vm_id=vm_info['instance_uuid'], vm_id_type='instance_uuid') set_vm_power_state(content=self.content, vm=instant_vm_obj, state='rebootguest', force=False) if self.wait_vm_tools: interval = 15 # Wait vm tools is started after rebooting. while self.wait_vm_tools_timeout > 0: if instant_vm_obj.guest.toolsRunningStatus != 'guestToolsRunning': break self.wait_vm_tools_timeout -= interval time.sleep(interval) while self.wait_vm_tools_timeout > 0: if instant_vm_obj.guest.toolsRunningStatus == 'guestToolsRunning': break self.wait_vm_tools_timeout -= interval time.sleep(interval) if self.wait_vm_tools_timeout <= 0: self.module.fail_json( msg= "Timeout has been reached for waiting to start the vm tools." ) return result