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
Esempio n. 2
0
 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
Esempio n. 3
0
 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
Esempio n. 4
0
    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))

        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