예제 #1
0
    def get_vm(self):
        """
        Find unique virtual machine either by UUID or Name.
        Returns: virtual machine object if found, else None.

        """
        vms = []
        if self.vm_uuid:
            if not self.use_instance_uuid:
                vm_obj = find_vm_by_id(self.content, vm_id=self.params['vm_uuid'], vm_id_type="uuid")
            elif self.use_instance_uuid:
                vm_obj = find_vm_by_id(self.content, vm_id=self.params['vm_uuid'], vm_id_type="instance_uuid")
            vms = [vm_obj]
        elif self.vm_name:
            objects = self.get_managed_objects_properties(vim_type=vim.VirtualMachine, properties=['name'])
            for temp_vm_object in objects:
                if len(temp_vm_object.propSet) != 1:
                    continue
                if temp_vm_object.obj.name == self.vm_name:
                    vms.append(temp_vm_object.obj)
                    break
        elif self.moid:
            vm_obj = VmomiSupport.templateOf('VirtualMachine')(self.moid, self.si._stub)
            if vm_obj:
                vms.append(vm_obj)

        if len(vms) > 1:
            self.module.fail_json(msg="Multiple virtual machines with same name %s found."
                                      " Please specify vm_uuid instead of vm_name." % self.vm_name)

        if vms:
            self.vm = vms[0]
    def _get_vm(self):
        vms = []

        if self.uuid:
            if self.use_instance_uuid:
                vm_obj = find_vm_by_id(self.content, vm_id=self.uuid, vm_id_type="instance_uuid")
            else:
                vm_obj = find_vm_by_id(self.content, vm_id=self.uuid, vm_id_type="uuid")
            if vm_obj is None:
                self.module.fail_json(msg="Failed to find the virtual machine with UUID : %s" % self.uuid)
            vms = [vm_obj]

        elif self.name:
            objects = self.get_managed_objects_properties(vim_type=vim.VirtualMachine, properties=['name'])
            for temp_vm_object in objects:
                if temp_vm_object.obj.name == self.name:
                    vms.append(temp_vm_object.obj)

        elif self.moid:
            vm_obj = VmomiSupport.templateOf('VirtualMachine')(self.module.params['moid'], self.si._stub)
            if vm_obj:
                vms.append(vm_obj)

        if vms:
            if self.params.get('name_match') == 'first':
                self.vm = vms[0]
            elif self.params.get('name_match') == 'last':
                self.vm = vms[-1]
        else:
            self.module.fail_json(msg="Failed to find virtual machine using %s" % (self.name or self.uuid))
예제 #3
0
    def getvm_folder_paths(self):
        results = []
        vms = []

        if self.uuid:
            if self.use_instance_uuid:
                vm_obj = find_vm_by_id(self.content,
                                       vm_id=self.uuid,
                                       vm_id_type="instance_uuid")
            else:
                vm_obj = find_vm_by_id(self.content,
                                       vm_id=self.uuid,
                                       vm_id_type="uuid")
            if vm_obj is None:
                self.module.fail_json(
                    msg="Failed to find the virtual machine with UUID : %s" %
                    self.uuid)
            vms = [vm_obj]

        elif self.name:
            objects = self.get_managed_objects_properties(
                vim_type=vim.VirtualMachine, properties=['name'])
            for temp_vm_object in objects:
                if temp_vm_object.obj.name == self.name:
                    vms.append(temp_vm_object.obj)

        for vm in vms:
            folder_path = self.get_vm_path(self.content, vm)
            results.append(folder_path)

        return results
예제 #4
0
    def __init__(self, module):
        super(VMwareShellManager, self).__init__(module)
        datacenter_name = module.params['datacenter']
        cluster_name = module.params['cluster']
        folder = module.params['folder']
        try:
            self.pm = self.content.guestOperationsManager.processManager
        except vmodl.fault.ManagedObjectNotFound:
            pass
        self.timeout = self.params.get('timeout', 3600)
        self.wait_for_pid = self.params.get('wait_for_process', False)

        datacenter = None
        if datacenter_name:
            datacenter = find_datacenter_by_name(self.content, datacenter_name)
            if not datacenter:
                module.fail_json(
                    changed=False,
                    msg="Unable to find %(datacenter)s datacenter" %
                    module.params)

        cluster = None
        if cluster_name:
            cluster = find_cluster_by_name(self.content, cluster_name,
                                           datacenter)
            if not cluster:
                module.fail_json(changed=False,
                                 msg="Unable to find %(cluster)s cluster" %
                                 module.params)

        if module.params['vm_id_type'] == 'inventory_path':
            vm = find_vm_by_id(self.content,
                               vm_id=module.params['vm_id'],
                               vm_id_type="inventory_path",
                               folder=folder)
        else:
            vm = find_vm_by_id(self.content,
                               vm_id=module.params['vm_id'],
                               vm_id_type=module.params['vm_id_type'],
                               datacenter=datacenter,
                               cluster=cluster)

        if not vm:
            module.fail_json(msg='Unable to find virtual machine.')

        tools_status = vm.guest.toolsStatus
        if tools_status in ['toolsNotInstalled', 'toolsNotRunning']:
            self.module.fail_json(
                msg=
                "VMwareTools is not installed or is not running in the guest."
                " VMware Tools are necessary to run this module.")

        try:
            self.execute_command(vm, module.params)
        except vmodl.RuntimeFault as runtime_fault:
            module.fail_json(changed=False, msg=to_native(runtime_fault.msg))
        except vmodl.MethodFault as method_fault:
            module.fail_json(changed=False, msg=to_native(method_fault.msg))
        except Exception as e:
            module.fail_json(changed=False, msg=to_native(e))
    def __init__(self, module):
        super(VmwareGuestFileManager, self).__init__(module)
        datacenter_name = module.params['datacenter']
        cluster_name = module.params['cluster']
        folder = module.params['folder']

        datacenter = None
        if datacenter_name:
            datacenter = find_datacenter_by_name(self.content, datacenter_name)
            if not datacenter:
                module.fail_json(
                    msg="Unable to find %(datacenter)s datacenter" %
                    module.params)

        cluster = None
        if cluster_name:
            cluster = find_cluster_by_name(self.content, cluster_name,
                                           datacenter)
            if not cluster:
                module.fail_json(msg="Unable to find %(cluster)s cluster" %
                                 module.params)

        if module.params['vm_id_type'] == 'inventory_path':
            vm = find_vm_by_id(self.content,
                               vm_id=module.params['vm_id'],
                               vm_id_type="inventory_path",
                               folder=folder)
        else:
            vm = find_vm_by_id(self.content,
                               vm_id=module.params['vm_id'],
                               vm_id_type=module.params['vm_id_type'],
                               datacenter=datacenter,
                               cluster=cluster)

        if not vm:
            module.fail_json(msg='Unable to find virtual machine.')

        self.vm = vm
        try:
            result = dict(changed=False)
            if module.params['directory']:
                result = self.directory()
            if module.params['copy']:
                result = self.copy()
            if module.params['fetch']:
                result = self.fetch()
            module.exit_json(**result)
        except vmodl.RuntimeFault as runtime_fault:
            module.fail_json(msg=to_native(runtime_fault.msg))
        except vmodl.MethodFault as method_fault:
            module.fail_json(msg=to_native(method_fault.msg))
        except Exception as e:
            module.fail_json(msg=to_native(e))
예제 #6
0
    def _set_vm_obj_list(self, vm_list=None, cluster_obj=None):
        """
        Populate vm object list from list of vms
        Args:
            vm_list: List of vm names

        Returns: None

        """

        if vm_list is None:
            vm_list = self._vm_list

        if cluster_obj is None:
            cluster_obj = self._cluster_obj

        if vm_list is not None:
            for vm in vm_list:
                if self.module.check_mode is False:
                    # Get host data
                    vm_obj = find_vm_by_id(content=self.content, vm_id=vm,
                                           vm_id_type='vm_name', cluster=cluster_obj)
                    if vm_obj is None:
                        raise Exception("VM %s does not exist in cluster %s" % (vm,
                                                                                self._cluster_name))
                    self._vm_obj_list.append(vm_obj)
    def get_all_vms_info(self, vms_list=None):
        """
        Get all VM objects using name from given cluster
        Args:
            vms_list: List of VM names

        Returns: List of VM managed objects

        """
        vm_obj_list = []
        if vms_list is None:
            vms_list = self.vm_list

        for vm_name in vms_list:
            vm_obj = find_vm_by_id(content=self.content, vm_id=vm_name,
                                   vm_id_type='vm_name', cluster=self.cluster_obj)
            if vm_obj is None:
                self.module.fail_json(msg="Failed to find the virtual machine %s "
                                          "in given cluster %s" % (vm_name,
                                                                   self.cluster_name))
            vm_obj_list.append(vm_obj)
        return vm_obj_list
예제 #8
0
    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
예제 #9
0
    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