def test_required_params(request, params, msg, fake_ansible_module): """ Test if required params are correct or not""" fake_ansible_module.params = params with pytest.raises(FailJsonException): vmware_module_utils.connect_to_api(fake_ansible_module) assert fake_ansible_module.fail_json.called_once() assert msg in fake_ansible_module.fail_json.call_args[1]['msg']
def main(): argument_spec = vmware_argument_spec() argument_spec.update(dict(change_hostname_to=dict(required=True, type='str'), domainname=dict(required=True, type='str'), dns_servers=dict(required=True, type='list'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') change_hostname_to = module.params['change_hostname_to'] domainname = module.params['domainname'] dns_servers = module.params['dns_servers'] try: content = connect_to_api(module) host = get_all_objs(content, [vim.HostSystem]) if not host: module.fail_json(msg="Unable to locate Physical Host.") host_system = list(host)[0] changed = configure_dns(host_system, change_hostname_to, domainname, dns_servers) module.exit_json(changed=changed) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e))
def __init__(self, module): super(VmwareCategory, self).__init__(module) self.category_service = self.api_client.tagging.Category self.global_categories = dict() self.category_name = self.params.get('category_name') self.get_all_categories() self.content = connect_to_api(self.module, return_si=False)
def main(): argument_spec = vmware_argument_spec() argument_spec.update(dict(cluster_uuid=dict(required=False, type='str'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') new_cluster_uuid = module.params['cluster_uuid'] try: content = connect_to_api(module, False) host = get_all_objs(content, [vim.HostSystem]) if not host: module.fail_json(msg="Unable to locate Physical Host.") host_system = list(host)[0] changed, result, cluster_uuid = create_vsan_cluster( host_system, new_cluster_uuid) module.exit_json(changed=changed, result=result, cluster_uuid=cluster_uuid) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e))
def main(): argument_spec = vmware_argument_spec() argument_spec.update( dict(vmk_name=dict(required=True, type='str'), ip_address=dict(required=True, type='str'), subnet_mask=dict(required=True, type='str'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') vmk_name = module.params['vmk_name'] ip_address = module.params['ip_address'] subnet_mask = module.params['subnet_mask'] try: content = connect_to_api(module, False) host = get_all_objs(content, [vim.HostSystem]) if not host: module.fail_json(msg="Unable to locate Physical Host.") host_system = list(host)[0] changed = configure_vmkernel_ip_address(host_system, vmk_name, ip_address, subnet_mask) module.exit_json(changed=changed) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e))
def main(): argument_spec = vmware_argument_spec() argument_spec.update(cluster_name=dict(required=True, type='str'), fetch_from_cache=dict(required=False, type='bool', default=False)) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if not HAS_PYVMOMI: module.fail_json(msg=missing_required_lib('PyVmomi'), exception=PYVMOMI_IMP_ERR) if not HAS_VSANPYTHONSDK: module.fail_json( msg=missing_required_lib('vSAN Management SDK for Python'), exception=VSANPYTHONSDK_IMP_ERR) if not HAS_PYVMOMIJSON: module.fail_json( msg= 'The installed version of pyvmomi lacks JSON output support; need pyvmomi>6.7.1' ) try: si, content = connect_to_api(module, True, True) except Exception as e: module.fail_json(msg=e.msg) client_stub = si._GetStub() ssl_context = client_stub.schemeArgs.get('context') cluster = find_cluster_by_name(content, module.params['cluster_name']) if not cluster: module.fail_json(msg="Failed to find cluster %s" % module.params['cluster_name']) apiVersion = vsanapiutils.GetLatestVmodlVersion(module.params['hostname']) vcMos = vsanapiutils.GetVsanVcMos(client_stub, context=ssl_context, version=apiVersion) vsanClusterHealthSystem = vcMos['vsan-cluster-health-system'] try: clusterHealth = vsanClusterHealthSystem.VsanQueryVcClusterHealthSummary( cluster=cluster, fetchFromCache=module.params['fetch_from_cache']) except vmodl.fault.NotFound as not_found: module.fail_json(msg=not_found.msg) except vmodl.fault.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) health = json.dumps(clusterHealth, cls=VmomiSupport.VmomiJSONEncoder, sort_keys=True, strip_dynamic=True) module.exit_json(changed=False, vsan_health_info=health)
def __init__(self, module): self.module = module self.host_system = None self.migrate_switch_name = self.module.params['migrate_switch_name'] self.migrate_portgroup_name = self.module.params['migrate_portgroup_name'] self.device = self.module.params['device'] self.esxi_hostname = self.module.params['esxi_hostname'] self.current_portgroup_name = self.module.params['current_portgroup_name'] self.current_switch_name = self.module.params['current_switch_name'] self.content = connect_to_api(module)
def _login(self): """ Login to vCenter or ESXi server Returns: connection object """ return connect_to_api(module=None, disconnect_atexit=True, return_si=True, hostname=self.hostname, username=self.username, password=self.password, port=self.port, validate_certs=self.validate_certs, httpProxyHost=self.proxy_host, httpProxyPort=self.proxy_port)
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
def __init__(self, module): self.module = module self.datacenter = module.params['datacenter'] self.cluster = module.params['cluster'] self.resource_pool = module.params['resource_pool'] self.hostname = module.params['hostname'] self.username = module.params['username'] self.password = module.params['password'] self.state = module.params['state'] self.mem_shares = module.params['mem_shares'] self.mem_limit = module.params['mem_limit'] self.mem_reservation = module.params['mem_reservation'] self.mem_expandable_reservations = module.params[ 'cpu_expandable_reservations'] self.cpu_shares = module.params['cpu_shares'] self.cpu_limit = module.params['cpu_limit'] self.cpu_reservation = module.params['cpu_reservation'] self.cpu_expandable_reservations = module.params[ 'cpu_expandable_reservations'] self.dc_obj = None self.cluster_obj = None self.host_obj = None self.resource_pool_obj = None self.content = connect_to_api(module)
def test_connect_to_api_validate_certs(monkeypatch, fake_ansible_module): monkeypatch.setattr(vmware_module_utils, 'connect', mock.Mock()) def MockSSLContext(proto): ssl_context.proto = proto return ssl_context # New Python with SSLContext + validate_certs=True vmware_module_utils.connect.reset_mock() ssl_context = mock.Mock() monkeypatch.setattr(vmware_module_utils.ssl, 'SSLContext', MockSSLContext) fake_ansible_module.params['validate_certs'] = True vmware_module_utils.connect_to_api(fake_ansible_module) assert ssl_context.proto == ssl.PROTOCOL_SSLv23 assert ssl_context.verify_mode == ssl.CERT_REQUIRED assert ssl_context.check_hostname is True vmware_module_utils.connect.SmartConnect.assert_called_once_with( host='esxi1', port=443, pwd='Esxi@123$%', user='******', sslContext=ssl_context) # New Python with SSLContext + validate_certs=False vmware_module_utils.connect.reset_mock() ssl_context = mock.Mock() monkeypatch.setattr(vmware_module_utils.ssl, 'SSLContext', MockSSLContext) fake_ansible_module.params['validate_certs'] = False vmware_module_utils.connect_to_api(fake_ansible_module) assert ssl_context.proto == ssl.PROTOCOL_SSLv23 assert ssl_context.verify_mode == ssl.CERT_NONE assert ssl_context.check_hostname is False vmware_module_utils.connect.SmartConnect.assert_called_once_with( host='esxi1', port=443, pwd='Esxi@123$%', user='******', sslContext=ssl_context) # Old Python with no SSLContext + validate_certs=True vmware_module_utils.connect.reset_mock() ssl_context = mock.Mock() ssl_context.proto = None monkeypatch.delattr(vmware_module_utils.ssl, 'SSLContext') fake_ansible_module.params['validate_certs'] = True with pytest.raises(FailJsonException): vmware_module_utils.connect_to_api(fake_ansible_module) assert ssl_context.proto is None fake_ansible_module.fail_json.assert_called_once_with( msg=('pyVim does not support changing verification mode with python ' '< 2.7.9. Either update python or use validate_certs=false.')) assert not vmware_module_utils.connect.SmartConnect.called # Old Python with no SSLContext + validate_certs=False vmware_module_utils.connect.reset_mock() ssl_context = mock.Mock() ssl_context.proto = None monkeypatch.delattr(vmware_module_utils.ssl, 'SSLContext', raising=False) fake_ansible_module.params['validate_certs'] = False vmware_module_utils.connect_to_api(fake_ansible_module) assert ssl_context.proto is None vmware_module_utils.connect.SmartConnect.assert_called_once_with( host='esxi1', port=443, pwd='Esxi@123$%', user='******')
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
def __init__(self, module): self.module = module self.content = connect_to_api(module) self.vm = None self.vm_name = module.params['vm_name'] self.dvportgroup_name = module.params['dvportgroup_name']
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
def main(): argument_spec = vmware_argument_spec() argument_spec.update( dict( extension_key=dict(type='str', required=True), version=dict(type='str', required=True), email=dict(type='str', required=False), description=dict(type='str', required=False), company=dict(type='str', required=False), name=dict(type='str', required=False), url=dict(type='str', required=False), ssl_thumbprint=dict(type='str', required=False), client_type=dict(type='str', default='vsphere-client-serenity', required=False), server_type=dict(type='str', default='vsphere-client-serenity', required=False), visible=dict(type='bool', default='True', required=False), state=dict(type='str', default='present', choices=['absent', 'present']), )) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False, required_if=[[ 'state', 'present', [ 'email', 'description', 'company', 'name', 'url', 'ssl_thumbprint', 'server_type', 'client_type' ] ]]) state = module.params['state'] extension_key = module.params['extension_key'] version = module.params['version'] email = module.params['email'] desc = module.params['description'] name = module.params['name'] company = module.params['company'] client_type = module.params['client_type'] server_type = module.params['server_type'] url = module.params['url'] visible = module.params['visible'] thumbprint = module.params['ssl_thumbprint'] content = connect_to_api(module, False) em = content.extensionManager key_check = em.FindExtension(extension_key) results = dict(changed=False, installed=dict()) if state == 'present' and key_check: results['changed'] = False results['installed'] = "'%s' is already installed" % (extension_key) elif state == 'present' and not key_check: extension = vim.Extension() extension.key = extension_key extension.company = company extension.version = version extension.lastHeartbeatTime = datetime.datetime.now() description = vim.Description() description.label = name description.summary = desc extension.description = description extension.shownInSolutionManager = visible client = vim.Extension.ClientInfo() client.company = company client.version = version client.description = description client.type = client_type client.url = url extension.client = [client] server = vim.Extension.ServerInfo() server.company = company server.description = description server.type = server_type server.adminEmail = email server.serverThumbprint = thumbprint server.url = url extension.server = [server] em.RegisterExtension(extension) results['changed'] = True results['installed'] = "'%s' installed." % (extension_key) elif state == 'absent' and key_check: em.UnregisterExtension(extension_key) results['changed'] = True results['installed'] = "'%s' uninstalled." % (extension_key) elif state == 'absent' and not key_check: results['changed'] = False results['installed'] = "'%s' is not installed." % (extension_key) module.exit_json(**results)