def main(): argument_spec = vmware_argument_spec() argument_spec.update( dict( vm_name=dict(required=True, aliases=['vm'], type='str'), destination_host=dict(required=True, aliases=['destination'], type='str'), ) ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if not HAS_PYVMOMI: module.fail_json(msg='pyVmomi is required for this module') content = connect_to_api(module=module) vm_object = find_vm_by_name(content=content, vm_name=module.params['vm_name']) host_object = find_hostsystem_by_name(content=content, hostname=module.params['destination_host']) # Setup result result = { 'changed': False } # Check if we could find the VM or Host if not vm_object: module.fail_json(msg='Cannot find virtual machine') if not host_object: module.fail_json(msg='Cannot find host') # Make sure VM isn't already at the destination if vm_object.runtime.host.name == module.params['destination_host']: module.exit_json(**result) if not module.check_mode: # Migrate VM and get Task object back task_object = migrate_vm(vm_object=vm_object, host_object=host_object) # Wait for task to complete wait_for_task(task_object) # If task was a success the VM has moved, update running_host and complete module if task_object.info.state == vim.TaskInfo.State.success: vm_object = find_vm_by_name(content=content, vm_name=module.params['vm_name']) result['running_host'] = vm_object.runtime.host.name result['changed'] = True module.exit_json(**result) else: if task_object.info.error is None: module.fail_json(msg='Unable to migrate VM due to an error, please check vCenter') else: module.fail_json(msg='Unable to migrate VM due to an error: %s' % task_object.info.error) else: # If we are in check mode return a result as if move was performed result['running_host'] = module.params['destination_host'] result['changed'] = True module.exit_json(**result)