Ejemplo n.º 1
0
    def get_objects(self):
        self.datastore = find_datastore_by_name(self.si,
                                                self.params['datastore'])
        if not self.datastore:
            self.module.fail_json(msg='%(datastore)s could not be located' %
                                  self.params)

        self.datacenter = find_datacenter_by_name(self.si,
                                                  self.params['datacenter'])
        if not self.datacenter:
            self.module.fail_json(msg='%(datacenter)s could not be located' %
                                  self.params)

        self.resource_pool = find_resource_pool_by_name(
            self.si, self.params['resource_pool'])
        if not self.resource_pool:
            self.module.fail_json(
                msg='%(resource_pool)s could not be located' % self.params)

        for key, value in self.params['networks'].items():
            network = find_network_by_name(self.si, value)
            if not network:
                self.module.fail_json(msg='%(network)s could not be located' %
                                      self.params)
            network_mapping = vim.OvfManager.NetworkMapping()
            network_mapping.name = key
            network_mapping.network = network
            self.network_mappings.append(network_mapping)

        return self.datastore, self.datacenter, self.resource_pool, self.network_mappings
Ejemplo n.º 2
0
    def reset_sp_vm(self):
        profiles = self.spbmclient.get_profiles()
        if not profiles:
            self.module.fail_json(
                changed=False,
                msg=
                "Could not retrieve Storage Profile Information from vCenter")
        else:
            vm = find_vm_by_name(content=self.content, vm_name=self.vmname)
            if vm is None:
                self.module.fail_json(
                    changed=False,
                    msg="Did not find VM {} in vCenter".format(self.vmname))

            # Find Where VM Home is Residing
            vmPathName = vm.config.files.vmPathName
            vmx_datastore = vmPathName.partition(']')[0].replace('[', '')
            vmx_profile = self.spbmclient.get_ds_default_profile(
                find_datastore_by_name(content=self.content,
                                       datastore_name=vmx_datastore))

            disks = []
            devices = vm.config.hardware.device
            for device in devices:
                if device:
                    if device and isinstance(device,
                                             vim.vm.device.VirtualDisk):
                        disks.append(device)
            device_change = []
            for disk in disks:
                datastore_profile = self.spbmclient.get_ds_default_profile(
                    disk.backing.datastore)
                profile = vim.VirtualMachineDefinedProfileSpec(
                    profileId=datastore_profile.uniqueId)
                device_change.append(
                    vim.VirtualDeviceConfigSpec(
                        device=disk,
                        operation=vim.VirtualDeviceConfigSpecOperation.edit,
                        profile=[profile]))
            profile = vim.VirtualMachineDefinedProfileSpec(
                profileId=vmx_profile.uniqueId)
            vmSpec = vim.VirtualMachineConfigSpec(vmProfile=[profile],
                                                  deviceChange=device_change)
            state, error = wait_for_task(vm.ReconfigVM_Task(spec=vmSpec))
            if state:
                self.module.exit_json(
                    changed=True,
                    msg="Detached Profile {} from VM {}".format(
                        self.profilename, self.vmname))
            else:
                self.module.fail_json(
                    changed=False,
                    msg="Failed to Detach Profile from VM {}. Error {}".format(
                        self.vmname, error))
Ejemplo n.º 3
0
 def umount_datastore_host(self):
     ds = find_datastore_by_name(self.content, self.datastore_name)
     if not ds:
         self.module.fail_json(msg="No datastore found with name %s" % self.datastore_name)
     error_message_umount = "Cannot umount datastore %s from host %s" % (self.datastore_name, self.esxi_hostname)
     try:
         self.esxi.configManager.datastoreSystem.RemoveDatastore(ds)
     except (vim.fault.NotFound, vim.fault.HostConfigFault, vim.fault.ResourceInUse) as fault:
         self.module.fail_json(msg="%s: %s" % (error_message_umount, to_native(fault.msg)))
     except Exception as e:
         self.module.fail_json(msg="%s: %s" % (error_message_umount, to_native(e)))
     self.module.exit_json(changed=True, result="Datastore %s on host %s" % (self.datastore_name, self.esxi_hostname))
Ejemplo n.º 4
0
    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
Ejemplo n.º 5
0
    def get_objects(self):
        self.datastore = find_datastore_by_name(self.si,
                                                self.params['datastore'])
        if not self.datastore:
            self.module.fail_json(msg='%(datastore)s could not be located' %
                                  self.params)

        self.datacenter = find_datacenter_by_name(self.si,
                                                  self.params['datacenter'])
        if not self.datacenter:
            self.module.fail_json(msg='%(datacenter)s could not be located' %
                                  self.params)


#        self.vm = find_vm_by_name(self.si, self.params['name'])
#        if not self.vm:
#            self.module.fail_json(msg='%(name)s could not be located' % self.params)

        self.resource_pool = find_resource_pool_by_name(
            self.si, self.params['resource_pool'])
        if not self.resource_pool:
            self.module.fail_json(
                msg='%(resource_pool)s could not be located' % self.params)

        for key, value in self.params['ovf_networks'].items():
            network = find_network_by_name(self.si, value)
            if not network:
                self.module.fail_json(
                    msg='%(ovf_network)s could not be located' % self.params)
            network_mapping = vim.OvfManager.NetworkMapping()
            network_mapping.name = key
            network_mapping.network = network
            self.network_mappings.append(network_mapping)

        if self.params['property_map']:
            for key, value in self.params['property_map'].items():
                property_map = vim.KeyValue()
                property_map.key = key
                property_map.value = value
                self.property_mappings.append(property_map)

        return self.datastore, self.datacenter, self.resource_pool, self.network_mappings, self.property_mappings
    def __init__(self, module):
        super(VMwareHostDatastore, self).__init__(module)

        self.vswp_files = []
        self.vcenter = module.params['hostname']
        self.datacenter = module.params['datacenter']
        self.datastore = module.params['datastore']

        self.dc = find_datacenter_by_name(self.content, self.datacenter)
        if self.dc is None:
            self.module.fail_json(msg="Failed to find Datacenter %s " %
                                  self.datacenter)

        self.ds = find_datastore_by_name(self.content, self.datastore)
        if self.ds is None:
            self.module.fail_json(msg="Failed to find Datastore %s " %
                                  self.datastore)

        self.find_vswp_files()

        if len(self.vswp_files) > 0:
            self.delete_vswp_files()
        else:
            self.module.exit_json(changed=False)
Ejemplo n.º 7
0
    def __init__(self, module):
        super(VmotionManager, self).__init__(module)
        self.vm = None
        self.vm_uuid = self.params.get('vm_uuid', None)
        self.vm_name = self.params.get('vm_name', None)
        result = dict()

        self.get_vm()
        if self.vm is None:
            self.module.fail_json(msg="Failed to find the virtual"
                                      " machine with %s" % (self.vm_uuid or self.vm_name))

        # Get Destination Host System if specified by user
        dest_host_name = self.params.get('destination_host', None)
        self.host_object = None
        if dest_host_name is not None:
            self.host_object = find_hostsystem_by_name(content=self.content,
                                                       hostname=dest_host_name)

        # Get Destination Datastore if specified by user
        dest_datastore = self.params.get('destination_datastore', None)
        self.datastore_object = None
        if dest_datastore is not None:
            self.datastore_object = find_datastore_by_name(content=self.content,
                                                           datastore_name=dest_datastore)

        # Atleast one of datastore, host system is required to migrate
        if self.datastore_object is None and self.host_object is None:
            self.module.fail_json(msg="Unable to find destination datastore"
                                      " and destination host system.")

        # Check if datastore is required, this check is required if destination
        # and source host system does not share same datastore.
        host_datastore_required = []
        for vm_datastore in self.vm.datastore:
            if self.host_object and vm_datastore not in self.host_object.datastore:
                host_datastore_required.append(True)
            else:
                host_datastore_required.append(False)

        if any(host_datastore_required) and dest_datastore is None:
            msg = "Destination host system does not share" \
                  " datastore ['%s'] with source host system ['%s'] on which" \
                  " virtual machine is located.  Please specify destination_datastore" \
                  " to rectify this problem." % ("', '".join([ds.name for ds in self.host_object.datastore]),
                                                 "', '".join([ds.name for ds in self.vm.datastore]))

            self.module.fail_json(msg=msg)

        storage_vmotion_needed = True
        change_required = True

        if self.host_object and self.datastore_object:
            # We have both host system and datastore object
            if not self.datastore_object.summary.accessible:
                # Datastore is not accessible
                self.module.fail_json(msg='Destination datastore %s is'
                                          ' not accessible.' % dest_datastore)

            if self.datastore_object not in self.host_object.datastore:
                # Datastore is not associated with host system
                self.module.fail_json(msg="Destination datastore %s provided"
                                          " is not associated with destination"
                                          " host system %s. Please specify"
                                          " datastore value ['%s'] associated with"
                                          " the given host system." % (dest_datastore,
                                                                       dest_host_name,
                                                                       "', '".join([ds.name for ds in self.host_object.datastore])))

            if self.vm.runtime.host.name == dest_host_name and dest_datastore in [ds.name for ds in self.vm.datastore]:
                change_required = False

        if self.host_object and self.datastore_object is None:
            if self.vm.runtime.host.name == dest_host_name:
                # VM is already located on same host
                change_required = False

            storage_vmotion_needed = False

        elif self.datastore_object and self.host_object is None:
            if self.datastore_object in self.vm.datastore:
                # VM is already located on same datastore
                change_required = False

            if not self.datastore_object.summary.accessible:
                # Datastore is not accessible
                self.module.fail_json(msg='Destination datastore %s is'
                                          ' not accessible.' % dest_datastore)

        if module.check_mode:
            result['running_host'] = module.params['destination_host']
            result['changed'] = True
            module.exit_json(**result)

        if change_required:
            # Migrate VM and get Task object back
            task_object = self.migrate_vm()
            # Wait for task to complete
            try:
                wait_for_task(task_object)
            except TaskError as task_error:
                self.module.fail_json(msg=to_native(task_error))
            # If task was a success the VM has moved, update running_host and complete module
            if task_object.info.state == vim.TaskInfo.State.success:
                # The storage layout is not automatically refreshed, so we trigger it to get coherent module return values
                if storage_vmotion_needed:
                    self.vm.RefreshStorageInfo()
                result['running_host'] = module.params['destination_host']
                result['changed'] = True
                module.exit_json(**result)
            else:
                msg = 'Unable to migrate virtual machine due to an error, please check vCenter'
                if task_object.info.error is not None:
                    msg += " : %s" % task_object.info.error
                module.fail_json(msg=msg)
        else:
            try:
                host = self.vm.summary.runtime.host
                result['running_host'] = host.summary.config.name
            except vim.fault.NoPermission:
                result['running_host'] = 'NA'
            result['changed'] = False
            module.exit_json(**result)
Ejemplo n.º 8
0
 def select_host(self, datastore_name):
     # given a datastore, find an attached host (just pick the first one)
     datastore = find_datastore_by_name(self.content, datastore_name)
     for host_mount in datastore.host:
         return host_mount.key