示例#1
0
    def deploy(self):
        facts = {}

        if self.params['power_on']:
            facts = set_vm_power_state(self.content, self.entity, 'poweredon', force=False)
            if self.params['wait_for_ip_address']:
                _facts = wait_for_vm_ip(self.content, self.entity)
                if not _facts:
                    self.module.fail_json(msg='Waiting for IP address timed out')

        if not facts:
            facts.update(gather_vm_facts(self.content, self.entity))

        return facts
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(
        state=dict(type='str', default='present',
                   choices=['present', 'powered-off', 'powered-on', 'reboot-guest', 'restarted', 'shutdown-guest', 'suspended']),
        name=dict(type='str'),
        name_match=dict(type='str', choices=['first', 'last'], default='first'),
        uuid=dict(type='str'),
        moid=dict(type='str'),
        use_instance_uuid=dict(type='bool', default=False),
        folder=dict(type='str'),
        force=dict(type='bool', default=False),
        scheduled_at=dict(type='str'),
        schedule_task_name=dict(),
        schedule_task_description=dict(),
        schedule_task_enabled=dict(type='bool', default=True),
        state_change_timeout=dict(type='int', default=0),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=False,
        mutually_exclusive=[
            ['name', 'uuid', 'moid'],
        ],
    )

    result = dict(changed=False,)

    pyv = PyVmomi(module)

    # Check if the VM exists before continuing
    vm = pyv.get_vm()

    if vm:
        # VM already exists, so set power state
        scheduled_at = module.params.get('scheduled_at', None)
        if scheduled_at:
            if not pyv.is_vcenter():
                module.fail_json(msg="Scheduling task requires vCenter, hostname %s "
                                     "is an ESXi server." % module.params.get('hostname'))
            powerstate = {
                'present': vim.VirtualMachine.PowerOn,
                'powered-off': vim.VirtualMachine.PowerOff,
                'powered-on': vim.VirtualMachine.PowerOn,
                'reboot-guest': vim.VirtualMachine.RebootGuest,
                'restarted': vim.VirtualMachine.Reset,
                'shutdown-guest': vim.VirtualMachine.ShutdownGuest,
                'suspended': vim.VirtualMachine.Suspend,
            }
            dt = ''
            try:
                dt = datetime.strptime(scheduled_at, '%d/%m/%Y %H:%M')
            except ValueError as e:
                module.fail_json(msg="Failed to convert given date and time string to Python datetime object,"
                                     "please specify string in 'dd/mm/yyyy hh:mm' format: %s" % to_native(e))
            schedule_task_spec = vim.scheduler.ScheduledTaskSpec()
            schedule_task_name = module.params['schedule_task_name'] or 'task_%s' % str(randint(10000, 99999))
            schedule_task_desc = module.params['schedule_task_description']
            if schedule_task_desc is None:
                schedule_task_desc = 'Schedule task for vm %s for ' \
                                     'operation %s at %s' % (vm.name, module.params['state'], scheduled_at)
            schedule_task_spec.name = schedule_task_name
            schedule_task_spec.description = schedule_task_desc
            schedule_task_spec.scheduler = vim.scheduler.OnceTaskScheduler()
            schedule_task_spec.scheduler.runAt = dt
            schedule_task_spec.action = vim.action.MethodAction()
            schedule_task_spec.action.name = powerstate[module.params['state']]
            schedule_task_spec.enabled = module.params['schedule_task_enabled']

            try:
                pyv.content.scheduledTaskManager.CreateScheduledTask(vm, schedule_task_spec)
                # As this is async task, we create scheduled task and mark state to changed.
                module.exit_json(changed=True)
            except vim.fault.InvalidName as e:
                module.fail_json(msg="Failed to create scheduled task %s for %s : %s" % (module.params.get('state'),
                                                                                         vm.name,
                                                                                         to_native(e.msg)))
            except vim.fault.DuplicateName as e:
                module.exit_json(changed=False, details=to_native(e.msg))
            except vmodl.fault.InvalidArgument as e:
                module.fail_json(msg="Failed to create scheduled task %s as specifications "
                                     "given are invalid: %s" % (module.params.get('state'),
                                                                to_native(e.msg)))
        else:
            result = set_vm_power_state(pyv.content, vm, module.params['state'], module.params['force'], module.params['state_change_timeout'])
    else:
        id = module.params.get('uuid') or module.params.get('moid') or module.params.get('name')
        module.fail_json(msg="Unable to set power state for non-existing virtual machine : '%s'" % id)

    if result.get('failed') is True:
        module.fail_json(**result)

    module.exit_json(**result)
示例#3
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