def main(): module = AnsibleModule(argument_spec=dict(display_name=dict(required=True, type='str'), vlan_logical_switches=dict( required=True, type='str'), vmks=dict(required=True, type='str'), pnics=dict(required=False, type='dict'), nsx_manager=dict(required=True, type='str'), nsx_username=dict(required=True, type='str'), nsx_passwd=dict(required=True, type='str', no_log=True)), supports_check_mode=False) if not HAS_PYNSXT: module.fail_json(msg='pynsxt is required for this module') session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( module.params["nsx_username"], module.params["nsx_passwd"]) connector.set_security_context(security_context) requests.packages.urllib3.disable_warnings() migrateVmks(module, stub_config)
def run(self): """ Converges the external PSC into the Management Node without shutting down the Platform Services Controller. """ session = get_unverified_session() if self.skipverification else None sec_ctx = create_user_password_security_context( self.username, self.password) # TODO The following line to be deleted when API is changed to # @Release type. As of now this is only for testing app_ctx = ApplicationContext({SHOW_UNRELEASED_APIS: "True"}) connector = get_requests_connector( session=session, msg_protocol='json', url='https://{0}:5480/api'.format(self.server), provider_filter_chain=[ LegacySecurityContextFilter( security_context=sec_ctx)]) connector.set_application_context(app_ctx) stub_config = StubConfigurationFactory.new_std_configuration(connector) deployment_type = DeploymentType(stub_config) """ Running convergence task precheck. Remove the line ", only_precheck = True" to perform convergence. """ convergence_task = deployment_type.convert_to_vcsa_embedded_task( DeploymentType.ConvergenceSpec(DeploymentType.PscInfo( sso_admin_username=self.sso_admin_username, sso_admin_password=self.sso_admin_password), only_precheck=True)) print('Converge operation started with task ID: \n{0}'.format( convergence_task.get_task_id()))
def run(self): """ Decommissions a PSC node from a Management Node """ session = get_unverified_session() if self.skipverification else None sec_ctx = create_user_password_security_context( self.username, self.password) # TODO The following line to be deleted when API is changed to # @Release type. As of now this is only for testing app_ctx = ApplicationContext({SHOW_UNRELEASED_APIS: "True"}) connector = get_requests_connector(session=session, msg_protocol='json', url='https://{0}:5480/api'.format( self.server)) connector.set_security_context(sec_ctx) connector.set_application_context(app_ctx) stub_config = StubConfigurationFactory.new_std_configuration(connector) pscs_obj = Pscs(stub_config) """ Running decommission task precheck. Remove the line ", only_precheck = True" to perform decommission. """ decommission_task = pscs_obj.decommission_task( self.psc_hostname, Pscs.DecommissionSpec(sso_admin_username=self.sso_admin_username, sso_admin_password=self.sso_admin_password), only_precheck=True) print('Decommission operation started with task ID: \n%s', decommission_task.get_task_id())
def main(): session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % ("<NSX MANAGER IP>", 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context("<USERNAME>", "<PASSWORD>") connector.set_security_context(security_context) urllib3.disable_warnings() tz_list = [] tz_svc = TransportZones(stub_config) tz_list = tz_svc.list() r = tz_list.results start_row = 1 for i in r: tz = i.convert_to(TransportZone) sheet1.write(start_row, 0, tz.display_name) sheet1.write(start_row, 1, tz.description) sheet1.write(start_row, 2, tz.id) sheet1.write(start_row, 3, tz.resource_type) sheet1.write(start_row, 4, tz.host_switch_id) sheet1.write(start_row, 5, tz.host_switch_mode) sheet1.write(start_row, 6, tz.host_switch_name) sheet1.write(start_row, 7, tz.is_default) sheet1.write(start_row, 8, tz.nested_nsx) sheet1.write(start_row, 9, tz.transport_type) sheet1.write(start_row, 10,tz.uplink_teaming_policy_names) start_row += 1 ls_wkbk.save('Transport Zones.xls')
def _vApiInit(self, host, user, password, proto='https', msg_type='json'): """ The authenticated stub configuration object can be used to issue requests against vCenter. The _config object stores the session identifier that can be used to issue authenticated requests against vCenter. """ session = requests.Session() session.verify = False api_url = '{0}://{1}/api'.format(proto, host) self._connector = get_requests_connector(session=session, url=api_url) self._config = StubConfigurationFactory.new_std_configuration( self._connector) # Creating security context loging for vAPI endpoint authentication sec_context_login = create_user_password_security_context( user, password) self._config.connector.set_security_context(sec_context_login) # Create the stub for the session service and login by creating a session. session_svc = Session(self._config) session_id = session_svc.create() # Successful authentication. Store the session identifier in the security # context of the stub config and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) self._config.connector.set_security_context(session_security_context)
def _login_vapi(self): """ Login to vCenter API using REST call Returns: connection object """ session = requests.Session() session.verify = self.validate_certs if not self.validate_certs: # Disable warning shown at stdout requests.packages.urllib3.disable_warnings() vcenter_url = "https://%s/api" % self.hostname # Get request connector connector = get_requests_connector(session=session, url=vcenter_url) # Create standard Configuration stub_config = StubConfigurationFactory.new_std_configuration(connector) # Use username and password in the security context to authenticate security_context = create_user_password_security_context(self.username, self.password) # Login stub_config.connector.set_security_context(security_context) # Create the stub for the session service and login by creating a session. session_svc = Session(stub_config) session_id = session_svc.create() # After successful authentication, store the session identifier in the security # context of the stub and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) if stub_config is None: raise AnsibleError("Failed to login to %s using %s" % (self.hostname, self.username)) return stub_config
def stub_connect(host, username, password, verify=False): """ Connect to the vCenter using the REST API """ from com.vmware.cis_client import Session from vmware.vapi.lib.connect import get_requests_connector from vmware.vapi.security.session import create_session_security_context from vmware.vapi.security.user_password import create_user_password_security_context from vmware.vapi.stdlib.client.factories import StubConfigurationFactory url = "https://{}/api".format(host) session = requests.Session() session.verify = verify connector = get_requests_connector(session=session, url=url) stub_config = StubConfigurationFactory.new_std_configuration(connector) # Pass user credentials (user/password) in the security context to authenticate. # login to vAPI endpoint user_password_security_context = create_user_password_security_context( username, password) stub_config.connector.set_security_context(user_password_security_context) session_svc = Session(stub_config) session_id = session_svc.create() session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) return stub_config
def main(): # Read the command-line arguments. The args object will contain # 4 properties, args.nsx_host, args.tcp_port, args.user, and # args.password. args = getargs.getargs() # Create a session using the requests library. For more information on # requests, see http://docs.python-requests.org/en/master/ session = requests.session() # If your NSX API server is using its default self-signed certificate, # you will need the following line, otherwise the python ssl layer # will reject the server certificate. THIS IS UNSAFE and you should # normally verify the server certificate. session.verify = False # Set up the API connector and security context nsx_url = 'https://%s:%s' % (args.nsx_host, args.tcp_port) connector = connect.get_requests_connector( session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( args.user, args.password) connector.set_security_context(security_context) # Now any API calls we make should authenticate to NSX using # HTTP Basic Authentication. Let's get a list of all Transport Zones. transportzones_svc = TransportZones(stub_config) tzs = transportzones_svc.list() # Create a pretty printer to make the output look nice. pp = PrettyPrinter() pp.pprint(tzs)
def get_configuration(server, username, password, skipVerification): session = get_unverified_session() if skipVerification else None if not session: session = requests.Session() host_url = "https://{}/api".format(server) sec_ctx = create_user_password_security_context(username, password) session_svc = Session( StubConfigurationFactory.new_std_configuration( get_requests_connector( session=session, url=host_url, provider_filter_chain=[ LegacySecurityContextFilter(security_context=sec_ctx) ]))) session_id = session_svc.create() print("Session ID : ", session_id) sec_ctx = create_session_security_context(session_id) stub_config = StubConfigurationFactory.new_std_configuration( get_requests_connector( session=session, url=host_url, provider_filter_chain=[ LegacySecurityContextFilter(security_context=sec_ctx) ])) return stub_config
def __init__(self, session, server, username, password, bearer_token, hok_token, private_key): """ Initialize VsphereClient by creating a parent stub factory instance of all vSphere components. :type session: :class:`requests.Session` :param session: Requests HTTP session instance. If not specified, then one is automatically created and used :type server: :class:`str` :param server: vCenter host name or IP address :type username: :class:`str` :param username: Name of the user :type password: :class:`str` :param password: Password of the user :type bearer_token: :class:`str` :param bearer_token: SAML Bearer Token :type hok_token: :class:`str` :param hok_token: SAML Hok Token :type private_key: :class:`str` :param private_key: Absolute file path of the private key of the user """ if not session: self.session = session = requests.Session() host_url = "https://" + server + JSON_RPC_ENDPOINT if username is not None and password is not None and \ not bearer_token and not hok_token: sec_ctx = create_user_password_security_context(username, password) elif bearer_token and not username and not hok_token: sec_ctx = create_saml_bearer_security_context(bearer_token) elif hok_token and private_key and not bearer_token and not username: sec_ctx = create_saml_security_context(hok_token, private_key) else: raise ValueError('Please provide exactly one of the following ' 'authentication scheme: username/password, ' 'bear_token or hok_token/private_key') session_svc = Session( StubConfigurationFactory.new_std_configuration( get_requests_connector( session=session, url=host_url, provider_filter_chain=[ LegacySecurityContextFilter(security_context=sec_ctx) ]))) session_id = session_svc.create() sec_ctx = create_session_security_context(session_id) stub_config = StubConfigurationFactory.new_std_configuration( get_requests_connector( session=session, url=host_url, provider_filter_chain=[ LegacySecurityContextFilter(security_context=sec_ctx) ])) self.session_svc = Session(stub_config) stub_factory = StubFactory(stub_config) ApiClient.__init__(self, stub_factory)
def automationSDKConnect(vcenter=None, username=None, password=None, insecure=None): """Creates stub_config with connection object for advanced features like VM Tagging present in vsphere-automation-sdk-python library, which is required to be installed: https://github.com/vmware/vsphere-automation-sdk-python""" vcenter = vcenter or conf.VCENTER username = username or conf.USERNAME password = password or conf.PASSWORD insecure = insecure or conf.INSECURE_CONNECTION if not HAS_AUTOMAT_SDK_INSTALLED: raise VmCLIException( 'Required vsphere-automation-sdk-python not installed. Exiting...') sys.exit(1) if (vcenter and username) and not password: password = getpass.getpass() elif not (vcenter and username and password): logger.error('No authentication credentials provided!') sys.exit(1) if not vcenter.startswith('http'): vcenter = 'https://{}/api'.format(vcenter) session = requests.Session() if insecure: requests.packages.urllib3.disable_warnings( requests.packages.urllib3.exceptions.InsecureRequestWarning) session.verify = False connector = get_requests_connector(session=session, url=vcenter) stub_config = StubConfigurationFactory.new_std_configuration(connector) # Pass user credentials (user/password) in the security context to authenticate. # login to vAPI endpoint user_password_security_context = create_user_password_security_context( username, password) stub_config.connector.set_security_context(user_password_security_context) # Create the stub for the session service and login by creating a session. session_svc = Session(stub_config) try: session_id = session_svc.create() except Unauthenticated: logger.error('Unable to connect. Check your credentials!') sys.exit(1) # Successful authentication. Store the session identifier in the security # context of the stub and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) return stub_config
def main(): module = AnsibleModule( argument_spec=dict( display_name=dict(required=True, type='str'), description=dict(required=False, type='str', default=None), form_factor=dict(required=False, type='str', default='MEDIUM', choices=['SMALL', 'MEDIUM', 'LARGE']), vsphere_cluster=dict(required=True, type='str'), host_id=dict(required=False, type='str', default=None), data_network_ids=dict(required=True, type='list'), default_gateway_addresses=dict(required=True, type='list'), hostname=dict(required=True, type='str'), management_network_id=dict(required=True, type='str'), management_port_subnet=dict(required=True, type='str'), management_port_prefix=dict(required=True, type='int'), storage_id=dict(required=True, type='str'), vc_id=dict(required=True, type='str'), cli_password=dict(required=True, type='str', no_log=True), root_password=dict(required=True, type='str', no_log=True), state=dict(required=False, type='str', default="present", choices=['present', 'absent']), nsx_manager=dict(required=True, type='str'), nsx_username=dict(required=True, type='str'), nsx_passwd=dict(required=True, type='str', no_log=True) ), supports_check_mode=True ) if not HAS_PYNSXT: module.fail_json(msg='pynsxt is required for this module') session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443) connector = connect.get_requests_connector( session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context(module.params["nsx_username"], module.params["nsx_passwd"]) connector.set_security_context(security_context) requests.packages.urllib3.disable_warnings() node = getEdheNodeByName(module, stub_config) if module.params['state'] == "present": if node: module.exit_json(changed=False, id=node.id, msg="Edge with name %s already exists!" % (module.params['display_name'])) elif not node: createEdge(module, stub_config) elif module.params['state'] == "absent": if node: nodes_svc = Nodes(stub_config) nodes_svc.delete(node.id) module.exit_json(changed=True, object_name=module.params['display_name'], message="Node with name %s deleted"%(module.params['display_name'])) elif not node: module.exit_json(changed=False, object_name=module.params['display_name'], message="Node with name %s does not exists"%(module.params['display_name']))
def __init__(self, sddc=None, verbose=False): self.sddc = sddc if not self.sddc: raise ValueError('You must supply a valid SDDC() object') self.org = sddc.org self.vmc = self.org.vmc self.vc_url = self.sddc.sddc.resource_config.vc_url self.vc_host = re.sub(r'https://(.*)/', r'\1', self.vc_url) self.vc_username = self.sddc.sddc.resource_config.cloud_username self.vc_password = self.sddc.sddc.resource_config.cloud_password session = requests.Session() connector = get_requests_connector(session=session, url='https://' + self.vc_host + '/api') user_password_security_context = create_user_password_security_context( self.vc_username, self.vc_password) context = ssl._create_unverified_context() self.stub_config = StubConfigurationFactory.new_std_configuration( connector) self.stub_config.connector.set_security_context( user_password_security_context) session_svc = Session(self.stub_config) session_id = session_svc.create() session_security_context = create_session_security_context(session_id) self.stub_config.connector.set_security_context( session_security_context) self.library_stub = content_client.Library(self.stub_config) self.subscribed_library_stub = content_client.SubscribedLibrary( self.stub_config) self.si = SmartConnect(host=self.vc_host, user=self.vc_username, pwd=self.vc_password, sslContext=context) self.content = self.si.RetrieveContent() self.references = {} self.referenceTypes = { 'datastores': [vim.Datastore], 'resourcePools': [vim.ClusterComputeResource], 'folders': [vim.Folder], 'VMs': [vim.VirtualMachine] } for referenceName in self.referenceTypes: self.refreshReference(referenceName)
def connect_to_rest(self): """ Connect to server using username and password """ session = requests.Session() session.verify = self.params.get('validate_certs') username = self.params.get('username', None) password = self.params.get('password', None) protocol = self.params.get('protocol', 'https') hostname = self.params.get('hostname') if not all([self.params.get('hostname', None), username, password]): self.module.fail_json( msg= "Missing one of the following : hostname, username, password." " Please read the documentation for more information.") vcenter_url = "%s://%s/api" % (protocol, hostname) # Get request connector connector = get_requests_connector(session=session, url=vcenter_url) # Create standard Configuration stub_config = StubConfigurationFactory.new_std_configuration(connector) # Use username and password in the security context to authenticate security_context = create_user_password_security_context( username, password) # Login stub_config.connector.set_security_context(security_context) # Create the stub for the session service and login by creating a session. session_svc = Session(stub_config) session_id = None try: session_id = session_svc.create() except OSError as os_err: self.module.fail_json(msg="Failed to login to %s: %s" % (hostname, to_native(os_err))) if session_id is None: self.module.fail_json( msg="Failed to create session using provided credentials." " Please check hostname, username and password.") # After successful authentication, store the session identifier in the security # context of the stub and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) if stub_config is None: self.module.fail_json(msg="Failed to login to %s" % hostname) return stub_config
def automationSDKConnect(vcenter=None, username=None, password=None, insecure=None): """Creates stub_config with connection object for advanced features like VM Tagging present in vsphere-automation-sdk-python library, which is required to be installed: https://github.com/vmware/vsphere-automation-sdk-python""" vcenter = vcenter or conf.VCENTER username = username or conf.USERNAME password = password or conf.PASSWORD insecure = insecure or conf.INSECURE_CONNECTION if not HAS_AUTOMAT_SDK_INSTALLED: raise VmCLIException('Required vsphere-automation-sdk-python not installed. Exiting...') sys.exit(1) if (vcenter and username) and not password: password = getpass.getpass() elif not (vcenter and username and password): logger.error('No authentication credentials provided!') sys.exit(1) if not vcenter.startswith('http'): vcenter = 'https://{}/api'.format(vcenter) session = requests.Session() if insecure: requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning) session.verify = False connector = get_requests_connector(session=session, url=vcenter) stub_config = StubConfigurationFactory.new_std_configuration(connector) # Pass user credentials (user/password) in the security context to authenticate. # login to vAPI endpoint user_password_security_context = create_user_password_security_context(username, password) stub_config.connector.set_security_context(user_password_security_context) # Create the stub for the session service and login by creating a session. session_svc = Session(stub_config) try: session_id = session_svc.create() except Unauthenticated: logger.error('Unable to connect. Check your credentials!') sys.exit(1) # Successful authentication. Store the session identifier in the security # context of the stub and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) return stub_config
def __init__(self, ipaddr, username, password): session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (ipaddr, 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) self.stub_config = StubConfigurationFactory.new_std_configuration( connector) security_context = create_user_password_security_context( username, password) connector.set_security_context(security_context)
def create_api_connection(): session = requests.session() session.proxies.update(PROXY) session.verify = False nsx_url = 'https://%s:%s' % (NSX_HOST, TCP_PORT) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( USER, os.popen("gopass " + GOPASS_CREDENTIAL).read()) connector.set_security_context(security_context) return stub_config
def stub_configuration(nsx_ip, nsx_user, nsx_pass): stub_config = None try: session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (nsx_ip, 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( nsx_user, nsx_pass) connector.set_security_context(security_context) except Exception, e: stub_config = None raise Exception("Could not get Stub for NSX %s" % nsx_ip)
def connect_to_rest(self): """ Function to connect to server using username and password """ session = requests.Session() session.verify = self.params.get('validate_certs') username = self.params.get('username', None) password = self.params.get('password', None) if not all([self.params.get('hostname', None), username, password]): self.module.fail_json(msg="Missing one of the following : hostname, username, password." " Please read the documentation for more information.") vcenter_url = "%(protocol)s://%(hostname)s/api" % self.params # Get request connector connector = get_requests_connector(session=session, url=vcenter_url) # Create standard Configuration stub_config = StubConfigurationFactory.new_std_configuration(connector) # Use username and password in the security context to authenticate security_context = create_user_password_security_context(username, password) # Login stub_config.connector.set_security_context(security_context) # Create the stub for the session service and login by creating a session. session_svc = Session(stub_config) session_id = None try: session_id = session_svc.create() except OSError as os_err: self.module.fail_json(msg="Failed to login to %s: %s" % (self.params['hostname'], to_native(os_err))) if session_id is None: self.module.fail_json(msg="Failed to create session using provided credentials." " Please check hostname, username and password.") # After successful authentication, store the session identifier in the security # context of the stub and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) if stub_config is None: self.module.fail_json(msg="Failed to login to %(hostname)s" % self.params) return stub_config
def main(): session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % ("<NSX-T MANAGER FQDN>", 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( "<USERNAME>", "<PASSWORD>") connector.set_security_context(security_context) urllib3.disable_warnings() ls_list = [] ls_svc = LogicalSwitches(stub_config) ls_list = ls_svc.list() # print(ls_list) tz_list = [] tz_svc = TransportZones(stub_config) tz_list = tz_svc.list() start_row = 1 for vs in ls_list.results: ls = vs.convert_to(LogicalSwitch) sheet1.write(start_row, 0, ls.display_name) sheet1.write(start_row, 1, ls.vni, style_alignleft) sheet1.write(start_row, 2, ls.vlan, style_alignleft) sheet1.write(start_row, 4, ls.transport_zone_id) sheet1.write(start_row, 6, ls.replication_mode) sheet1.write(start_row, 7, ls.admin_state) # print(ls.resource_type) newlist = [] for i in range(len(ls.tags)): newlist.append(ls.tags[i].tag) sheet1.write(start_row, 8, (str(newlist[0]))) if len(newlist) > 1: sheet1.write(start_row, 9, (str(newlist.pop()))) x = len(tz_list.results) for i in range(0, x): if ls.transport_zone_id == tz_list.results[i].id: sheet1.write(start_row, 3, tz_list.results[i].display_name) sheet1.write(start_row, 5, tz_list.results[i].transport_type) start_row += 1 ls_wkbk.save('Logical Switches.xls')
def get_basic_auth_stub_config(user, password, nsx_host, tcp_port=443): """ Create a stub configuration that uses HTTP basic authentication. """ session = requests.session() # Since the NSX manager default certificate is self-signed, # we disable verification. This is dangerous and real code # should verify that it is talking to a valid server. session.verify = False requests.packages.urllib3.disable_warnings() nsx_url = 'https://%s:%s' % (nsx_host, tcp_port) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context(user, password) connector.set_security_context(security_context) return stub_config
def test_username_security_context(self): input_val = StructValue(name='operation-input', values={}) user, password = '******', 'pwd' sec_ctx = create_user_password_security_context(user, password) _, actual_headers, actual_body, _ = RestSerializer.serialize_request( input_value=input_val, ctx=ExecutionContext(security_context=sec_ctx), rest_metadata=None, is_vapi_rest=True) expected_body = '{}' if six.PY2: b64_credentials = base64.b64encode('%s:%s' % (user, password)) authorization_val = 'Basic %s' % b64_credentials else: b64_credentials = base64.b64encode( bytes('%s:%s' % (user, password), 'utf-8')) authorization_val = b'Basic ' + b64_credentials expected_headers = {'Authorization': authorization_val} self.assertEqual(expected_headers, actual_headers) self.assertEqual(expected_body, actual_body)
def login(self, stub_config, user, pwd): """ Create an authenticated session with vCenter. Returns a stub_config that stores the session identifier that can be used to issue authenticated requests against vCenter. """ # Pass user credentials (user/password) in the security context to # authenticate. security_context = create_user_password_security_context(user, pwd) stub_config.connector.set_security_context(security_context) # Create the stub for the session service # and login by creating a session. session_svc = cis_client.Session(stub_config) session_id = session_svc.create() # Store the session identifier in the security # context of the stub and use that for all subsequent remote requests session_security_context = create_session_security_context(session_id) stub_config.connector.set_security_context(session_security_context) return stub_config
def execute(self): logger.info('Connecting to lookup service url: {0}'.format(self.lssoapurl)) lookupservicehelper = LookupServiceHelper(wsdl_url=self.lswsdlurl, soap_url=self.lssoapurl) lookupservicehelper.connect() if self.mgmtinstancename is None: self.mgmtinstancename, self.mgmtnodeid = lookupservicehelper.get_default_mgmt_node() elif self.mgmtnodeid is None: self.mgmtnodeid = lookupservicehelper.get_mgmt_node_id(self.mgmtinstancename) assert self.mgmtnodeid is not None self.vapiurl = lookupservicehelper.find_vapi_url(self.mgmtnodeid) logger.info('vapi_url: {0}'.format(self.vapiurl)) logger.info('Connecting to VAPI endpoint and preparing stub configuration...') connector = connect.get_connector('https', 'json', url=self.vapiurl) self.stub_config = StubConfigurationFactory.new_std_configuration(connector) sec_ctx = create_user_password_security_context(self.ssousername, self.ssopassword) connector.set_security_context(sec_ctx) self.stub_config = StubConfigurationFactory.new_std_configuration(connector) self.session = Session(self.stub_config) logger.info('Login to VAPI endpoint and get the session_id...') self.session_id = self.session.create() logger.info('Update the VAPI connection with session_id...') session_sec_ctx = create_session_security_context(self.session_id) connector.set_security_context(session_sec_ctx) # make sure you can access some of the VAPI services tag_svc = Tag(self.stub_config) logger.info('List all the existing tags user has access to...') tags = tag_svc.list() if len(tags) > 0: for tag in tags: logger.info('Found Tag: {0}'.format(tag)) else: logger.info('No Tag Found...')
def connect_cis(): """Connect to CIS""" import configuration as config import requests import urllib3 from com.vmware.cis_client import Session from vmware.vapi.security.user_password import create_user_password_security_context from vmware.vapi.stdlib.client.factories import StubConfigurationFactory from vmware.vapi.lib.connect import get_requests_connector from vmware.vapi.security.session import create_session_security_context # Create a session object in the client. session = requests.Session() # We don't have valid certificates so... urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) session.verify = False # Create a connection for the session. connector = get_requests_connector( session=session, url='https://' + config.VM_HOSTNAME + '/api' ) # Add username/password security context to the connector. connector.set_security_context( create_user_password_security_context( config.VM_USERNAME, config.VM_PASSWORD ) ) # Create a stub configuration by using the username-password security context. my_stub_config = StubConfigurationFactory.new_std_configuration(connector) # Create a Session stub with username-password security context. session_stub = Session(my_stub_config) # Use the create operation to create an authenticated session. session_id = session_stub.create() # Create a session ID security context. session_id_context = create_session_security_context(session_id) # Update the stub configuration with the session ID security context. my_stub_config.connector.set_security_context(session_id_context) return my_stub_config
def ConnectNSX(auth_list): """ ConnectNSX(list) Connection function to NSX. Can be by certifcates or by authentication. Returns ---------- list with session object and connector object Args ---------- auth : list list must contain login/cert - password/key - Tag (AUTH or CERT) """ YAML_DICT = GetYAMLDict() if auth_list[2] == 'AUTH': session = requests.session() session.verify = False connector = connect.get_requests_connector(session=session, msg_protocol='rest', url='https://' + YAML_DICT['NSX_MGR_IP']) security_context = create_user_password_security_context( auth_list[0], auth_list[1]) connector.set_security_context(security_context) return [session, connector] elif auth_list[2] == 'CERT': session = requests.session() session.verify = False session.cert = (auth_list[0], auth_list[1]) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url='https://' + YAML_DICT['NSX_MGR_IP']) return [session, connector] else: print("Issue on authentication") exit(1)
def main(): module = AnsibleModule( argument_spec=dict( display_name=dict(required=True, type='str'), node_id=dict(required=False, type='str', default=None), node_name=dict(required=False, type='str'), maintenance_mode=dict( required=False, type='str', choices=['DISABLED', 'ENABLED', 'FORCE_ENABLED']), # static_ip_pool_id=dict(required=True, type='str'), # host_switch_name=dict(required=False, type='list'), # transport_zone_endpoints=dict(required=False, type='list'), # pnics=dict(required=False, type='list'), # uplink_profile=dict(required=False, type='str'), host_switch=dict(required=True, type='list'), transport_zone_endpoints=dict(required=False, type='list'), state=dict(required=False, type='str', default="present", choices=['present', 'absent']), nsx_manager=dict(required=True, type='str'), nsx_username=dict(required=True, type='str'), nsx_passwd=dict(required=True, type='str', no_log=True)), supports_check_mode=True) if not HAS_PYNSXT: module.fail_json(msg='pynsxt is required for this module') session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( module.params["nsx_username"], module.params["nsx_passwd"]) connector.set_security_context(security_context) requests.packages.urllib3.disable_warnings() if module.params['node_id'] is None: fab_node = getNodeByName(module, stub_config) module.params['node_id'] = fab_node.id if module.params['state'] == "present": node = getTransportNodeByName(module, stub_config) if node is None: if module.check_mode: module.exit_json(changed=True, debug_out="Transport Node will be created", id="1111") result = createTransportNode(module, stub_config) module.exit_json(changed=True, object_name=module.params['display_name'], id=result.id, body=str(result)) else: changed = False # if module.params["maintenance_mode"]: # if module.params["maintenance_mode"].upper() != node.maintenance_mode: # changed = True # updateMaintenanceMode(module.params["maintenance_mode"], node, stub_config) # changed = updateTransportNode(module, stub_config) if changed: module.exit_json( changed=True, object_name=module.params['display_name'], id=node.id, message="Transport Node with name %s has been modified!" % (module.params['display_name'])) module.exit_json( changed=False, object_name=module.params['display_name'], id=node.id, message="Transport Node with name %s already exists!" % (module.params['display_name'])) elif module.params['state'] == "absent": node = getTransportNodeByName(module, stub_config) if node is None: module.exit_json(changed=False, object_name=module.params['display_name'], message="No Transport Node with name %s" % (module.params['display_name'])) else: if module.check_mode: module.exit_json(changed=True, debug_out=str(node), id=node.id) deleteTransportNode(module, node, stub_config) module.exit_json(changed=True, object_name=module.params['display_name'], message="Transport Node with name %s deleted" % (module.params['display_name']))
def main(): module = AnsibleModule(argument_spec=dict( display_name=dict(required=True, type='str'), server=dict(required=True, type='str'), username=dict(required=False, type='str'), passwd=dict(required=False, type='str', no_log=True), thumbprint=dict(required=False, type='str', default="x", no_log=True), origin_type=dict(required=False, type='str', default='vCenter', choices=['vCenter']), state=dict(required=False, type='str', default="present", choices=['present', 'absent']), nsx_manager=dict(required=True, type='str'), nsx_username=dict(required=True, type='str'), nsx_passwd=dict(required=True, type='str', no_log=True)), supports_check_mode=True) if not HAS_PYNSXT: module.fail_json(msg='pynsxt is required for this module') session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( module.params["nsx_username"], module.params["nsx_passwd"]) connector.set_security_context(security_context) requests.packages.urllib3.disable_warnings() if module.params['state'] == "present": cm = getCMByName(module, stub_config) if cm is None: result = createComputeManager(module, stub_config) module.exit_json(changed=True, id=result.id, object_name=module.params['display_name'], body=str(result)) else: module.exit_json( changed=False, id=cm.id, object_name=module.params['display_name'], message="Compute Manager with name %s already exists!" % (module.params['display_name'])) elif module.params['state'] == "absent": cm = getCMByName(module, stub_config) if cm is None: module.exit_json(changed=False, object_name=module.params['display_name'], message="No Compute Manager with name %s" % (module.params['display_name'])) else: if module.check_mode: module.exit_json(changed=True, debug_out=str(cm), id=cm.id) deleteCm(module, cm, stub_config) module.exit_json(changed=True, object_name=module.params['display_name'], message="Compute Manager with name %s deleted" % (module.params['display_name']))
def main(): module = AnsibleModule( argument_spec=dict( shared_secret=dict(required=True, type='str', no_log=True), vc_id=dict(required=False, type='str', default=None), controllers=dict(required=True, type='list'), state=dict(required=False, type='str', default="present", choices=['present', 'absent']), nsx_manager=dict(required=True, type='str'), nsx_username=dict(required=True, type='str'), nsx_passwd=dict(required=True, type='str', no_log=True) ), supports_check_mode=False ) if not HAS_PYNSXT: module.fail_json(msg='pynsxt is required for this module') session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443) connector = connect.get_requests_connector( session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context(module.params["nsx_username"], module.params["nsx_passwd"]) connector.set_security_context(security_context) requests.packages.urllib3.disable_warnings() d_svc = Deployments(stub_config) dep_list = d_svc.list() ctrl_list = [] if module.params['state'] == "present": isExisting = False for controller in module.params['controllers']: if module.params['vc_id']: controller['vc_id'] = module.params['vc_id'] isExistingTmp = False for deploymentRequest in dep_list.results: dconfig = deploymentRequest.deployment_config.convert_to(VsphereClusterNodeVMDeploymentConfig) if controller['hostname'] == dconfig.hostname: isExistingTmp = True isExisting = True if not isExistingTmp: ctrl_list.append(createController(controller, stub_config)) controlClusteringConfig = ControlClusteringConfig( join_to_existing_cluster=isExisting, shared_secret=module.params['shared_secret'], clustering_type='ControlClusteringConfig' ) addClusterNodeVMInfo = AddClusterNodeVMInfo( clustering_config=controlClusteringConfig, deployment_requests=ctrl_list ) check = 0 if not isExisting: check = len(module.params['controllers'])-1 try: deploy = d_svc.create(addClusterNodeVMInfo) cluster = deploy.convert_to(ClusterNodeVMDeploymentRequestList) status_svc = Status(stub_config) while True: time.sleep(5) node_status = status_svc.get(cluster.results[check].vm_id) status = node_status.convert_to(ClusterNodeVMDeploymentStatusReport) if status.status == 'VM_CLUSTERING_SUCCESSFUL': time.sleep(5) module.exit_json(changed=True, degug=str(cluster), msg="Controll Cluster created") if status.failure_message: module.fail_json(msg="Error: %s " % (status.failure_message)) except Error as ex: api_error = ex.data.convert_to(ApiError) module.fail_json('API Error creating node: %s' % (api_error.error_message)) elif module.params['state'] == "absent": changed = False for controller in module.params['controllers']: isExistingTmp = False for deploymentRequest in dep_list.results: dconfig = deploymentRequest.deployment_config.convert_to(VsphereClusterNodeVMDeploymentConfig) if controller['hostname'] == dconfig.hostname: d_svc.delete(deploymentRequest.vm_id, force_delete=True) changed = True time.sleep(5) time.sleep(40) module.exit_json(changed=changed, message="Deletion of controll cluster nodes")
def main(): module = AnsibleModule( argument_spec=dict( vip_address=dict(required=True, type='str'), enabled=dict(required=False, type='bool', default=True), t0_router=dict(required=True, type='str'), redundant_uplink_port_ids=dict(required=True, type='list'), state=dict(required=False, type='str', default="present", choices=['present', 'absent']), nsx_manager=dict(required=True, type='str'), nsx_username=dict(required=True, type='str'), nsx_passwd=dict(required=True, type='str', no_log=True) ), supports_check_mode=True ) if not HAS_PYNSXT: module.fail_json(msg='pynsxt is required for this module') session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443) connector = connect.get_requests_connector( session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context(module.params["nsx_username"], module.params["nsx_passwd"]) connector.set_security_context(security_context) requests.packages.urllib3.disable_warnings() lr_svc = LogicalRouters(stub_config) lr = getLogicalRouterByName(module, stub_config) subnet_list = [] subnet = module.params['vip_address'].split('/') new_subnet = VIPSubnet(active_vip_addresses=[subnet[0]], prefix_length=int(subnet[1])) subnet_list.append(new_subnet) haVipConfig = [HaVipConfig( enabled=module.params['enabled'], ha_vip_subnets=subnet_list, redundant_uplink_port_ids=module.params['redundant_uplink_port_ids'] )] if module.params['state'] == 'present': if lr.advanced_config.ha_vip_configs is None: lr.advanced_config.ha_vip_configs=haVipConfig if module.check_mode: module.exit_json(changed=True, debug_out=str(lr), id="1111") try: new_lr = lr_svc.update(lr.id, lr) module.exit_json(changed=True, object_name=module.params['vip_address'], id=lr.id, message="VIP for Logical Router with name %s was created!"%(lr.display_name)) except Error as ex: api_error = ex.data.convert_to(ApiError) module.fail_json(msg='API Error creating VIP: %s'%(str(api_error.error_message))) elif lr.advanced_config.ha_vip_configs != haVipConfig: lr.advanced_config.ha_vip_configs=haVipConfig if module.check_mode: module.exit_json(changed=True, debug_out=str(lr), id=lr.id) new_lr = lr_svc.update(lr.id, lr) module.exit_json(changed=True, object_name=module.params['vip_address'], id=lr.id, message="VIP for Logical Router with name %s has been changed!"%(lr.display_name)) module.exit_json(changed=False, object_name=module.params['vip_address'], id=lr.id, message="VIP Logical Router with name %s already exists!"%(lr.display_name)) elif module.params['state'] == "absent": if lr.advanced_config.ha_vip_configs: try: lr.advanced_config.ha_vip_configs=None if module.check_mode: module.exit_json(changed=True, debug_out=str(lr), id=lr.id) new_lr = lr_svc.update(lr.id, lr) module.exit_json(changed=True, object_name=module.params['vip_address'], id=lr.id, message="VIP for Logical Router with name %s was deleted!"%(lr.display_name)) except Error as ex: api_error = ex.date.convert_to(ApiError) module.fail_json(msg='API Error deleting Logical Router VIP: %s'%(api_error.error_message)) module.exit_json(changed=False, object_name=module.params['vip_address'], message="Logical Router VIP %s does not exist!"%(module.params['vip_address']))
def main(): module = AnsibleModule(argument_spec=dict( display_name=dict(required=True, type='str'), description=dict(required=False, type='str', default=None), subnets=dict(required=True, type='list'), tags=dict(required=False, type='dict', default=None), state=dict(required=False, type='str', default="present", choices=['present', 'absent']), nsx_manager=dict(required=True, type='str'), nsx_username=dict(required=True, type='str'), nsx_passwd=dict(required=True, type='str', no_log=True)), supports_check_mode=True) if not HAS_PYNSXT: module.fail_json(msg='pynsxt is required for this module') session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( module.params["nsx_username"], module.params["nsx_passwd"]) connector.set_security_context(security_context) requests.packages.urllib3.disable_warnings() tags = None if module.params['tags'] is not None: tags = [] for key, value in module.params['tags'].items(): tag = Tag(scope=key, tag=value) tags.append(tag) subnet_list = [] for subnet in module.params['subnets']: ip_range_list = [] for iprange in subnet['allocation_ranges']: ipr = iprange.split('-') ip_pool_range = IpPoolRange(start=ipr[0], end=ipr[1]) ip_range_list.append(ip_pool_range) ip_pool_subnet = IpPoolSubnet( allocation_ranges=ip_range_list, cidr=subnet['cidr'], dns_nameservers=subnet['dns_nameservers'], dns_suffix=subnet['dns_suffix'], gateway_ip=subnet['gateway_ip']) subnet_list.append(ip_pool_subnet) ippool_svc = IpPools(stub_config) ippool = getIpPoolByName(module, stub_config) if module.params['state'] == 'present': if ippool is None: if module.params['state'] == "present": new_ippool = IpPool(display_name=module.params['display_name'], description=module.params['description'], subnets=subnet_list, tags=tags) if module.check_mode: module.exit_json(changed=True, debug_out=str(new_ippool), id="1111") new_ippool = ippool_svc.create(new_ippool) module.exit_json(changed=True, object_name=module.params['display_name'], id=new_ippool.id, message="IP POOL with name %s created!" % (module.params['display_name'])) elif ippool: changed = False if tags != ippool.tags: changed = True ippool.tags = tags if ippool.subnets != subnet_list: ippool.subnets = subnet_list changed = True if changed: if module.check_mode: module.exit_json(changed=True, debug_out=str(ippool), id=ippool.id) new_ippool = ippool_svc.update(ippool.id, ippool) module.exit_json(changed=True, object_name=module.params['display_name'], id=ippool.id, msg="IP Pool has been changed") module.exit_json(changed=False, object_name=module.params['display_name'], id=ippool.id, message="IP POOL with name %s already exists!" % (module.params['display_name'])) elif module.params['state'] == "absent": if ippool: if module.check_mode: module.exit_json(changed=True, debug_out=str(ippool), id=ippool.id) ippool_svc.delete(ippool.id) module.exit_json(changed=True, object_name=module.params['display_name'], message="IP POOL with name %s deleted!" % (module.params['display_name'])) module.exit_json(changed=False, object_name=module.params['display_name'], message="IP POOL with name %s does not exist!" % (module.params['display_name']))
def main(): module = AnsibleModule(argument_spec=dict( display_name=dict(required=True, type='str'), description=dict(required=False, type='str', default=None), admin_state=dict(required=False, type='str', default='UP', choices=['UP', 'DOWN']), ip_pool_id=dict(required=False, type='str', default=None), mac_pool_id=dict(required=False, type='str', default=None), replication_mode=dict(required=False, type='str', default='MTEP', choices=['MTEP', 'SOURCE']), switching_profile_ids=dict(required=False, type='list', default=None), transport_zone_id=dict(required=True, type='str'), vlan=dict(required=False, type='int', default=None), tags=dict(required=False, type='dict', default=None), state=dict(required=False, type='str', default="present", choices=['present', 'absent']), nsx_manager=dict(required=True, type='str'), nsx_username=dict(required=True, type='str'), nsx_passwd=dict(required=True, type='str', no_log=True)), supports_check_mode=True) if not HAS_PYNSXT: module.fail_json(msg='pynsxt is required for this module') session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( module.params["nsx_username"], module.params["nsx_passwd"]) connector.set_security_context(security_context) requests.packages.urllib3.disable_warnings() tags = None if module.params['tags'] is not None: tags = [] for key, value in module.params['tags'].items(): tag = Tag(scope=key, tag=value) tags.append(tag) ls_svc = LogicalSwitches(stub_config) ls = getLogicalSwitchByName(module, stub_config) if module.params['state'] == 'present': if ls is None: new_ls = LogicalSwitch( display_name=module.params['display_name'], description=module.params['description'], address_bindings=None, admin_state=module.params['admin_state'], ip_pool_id=module.params['ip_pool_id'], mac_pool_id=module.params['mac_pool_id'], replication_mode=module.params['replication_mode'], switching_profile_ids=None, transport_zone_id=module.params['transport_zone_id'], vlan=module.params['vlan'], tags=tags) if module.check_mode: module.exit_json(changed=True, debug_out=str(new_ls), id="1111") new_ls = ls_svc.create(new_ls) # # TODO: Check the realisation before exiting !!!! # module.exit_json(changed=True, object_name=module.params['display_name'], id=new_ls.id, message="Logical Switch with name %s created!" % (module.params['display_name'])) elif ls: changed = False if tags != ls.tags: changed = True ls.tags = tags if module.check_mode: module.exit_json(changed=True, debug_out=str(ls), id=ls.id) new_ls = ls_svc.update(ls.id, ls) if changed: module.exit_json( changed=True, object_name=module.params['display_name'], id=new_ls.id, message="Logical Switch with name %s has changed tags!" % (module.params['display_name'])) module.exit_json( changed=False, object_name=module.params['display_name'], id=ls.id, message="Logical Switch with name %s already exists!" % (module.params['display_name'])) elif module.params['state'] == "absent": if ls: if module.check_mode: module.exit_json(changed=True, debug_out=str(ls), id=ls.id) ls_svc.delete(ls.id) module.exit_json(changed=True, object_name=module.params['display_name'], message="Logical Switch with name %s deleted!" % (module.params['display_name'])) module.exit_json( changed=False, object_name=module.params['display_name'], message="Logical Switch with name %s does not exist!" % (module.params['display_name']))
def main(): module = AnsibleModule(argument_spec=dict( display_name=dict(required=True, type='str'), description=dict(required=False, type='str', default=None), logical_router_id=dict(required=True, type='str'), service_bindings=dict(required=False, type='str', default=None), linked_logical_switch_port_id=dict(required=True, type='str'), subnets=dict(required=True, type='list'), urpf_mode=dict(required=False, type='str', default='NONE', choices=['NONE', 'STRICT']), tags=dict(required=False, type='dict', default=None), state=dict(required=False, type='str', default="present", choices=['present', 'absent']), nsx_manager=dict(required=True, type='str'), nsx_username=dict(required=True, type='str'), nsx_passwd=dict(required=True, type='str', no_log=True)), supports_check_mode=True) if not HAS_PYNSXT: module.fail_json(msg='pynsxt is required for this module') session = requests.session() session.verify = False nsx_url = 'https://%s:%s' % (module.params['nsx_manager'], 443) connector = connect.get_requests_connector(session=session, msg_protocol='rest', url=nsx_url) stub_config = StubConfigurationFactory.new_std_configuration(connector) security_context = create_user_password_security_context( module.params["nsx_username"], module.params["nsx_passwd"]) connector.set_security_context(security_context) requests.packages.urllib3.disable_warnings() tags = None if module.params['tags'] is not None: tags = [] for key, value in module.params['tags'].items(): tag = Tag(scope=key, tag=value) tags.append(tag) subnet_list = [] for subnet in module.params['subnets']: new_subnet = IPSubnet(ip_addresses=subnet['ip_addresses'], prefix_length=int(subnet['prefix_length'])) subnet_list.append(new_subnet) lrp_svc = LogicalRouterPorts(stub_config) lrp = getLogicalRouterPortByName(module, stub_config) if module.params['state'] == 'present': if lrp is None: new_lrp = LogicalRouterDownLinkPort( display_name=module.params['display_name'], description=module.params['description'], subnets=subnet_list, linked_logical_switch_port_id=ResourceReference( target_id=module.params['linked_logical_switch_port_id']), logical_router_id=module.params['logical_router_id'], service_bindings=None, urpf_mode=module.params['urpf_mode'], tags=tags) if module.check_mode: module.exit_json(changed=True, debug_out=str(new_lrp), id="1111") new_lrp_temp = lrp_svc.create(new_lrp) new_lrp = new_lrp_temp.convert_to(LogicalRouterDownLinkPort) module.exit_json( changed=True, object_name=module.params['display_name'], id=new_lrp.id, message="Logical Router Port with name %s created!" % (module.params['display_name'])) elif lrp: changed = False if tags != lrp.tags: changed = True lrp.tags = tags if subnet_list != lrp.subnets: changed = True lrp.subnets = subnet_list if changed: if module.check_mode: module.exit_json(changed=True, debug_out=str(lrp), id=lrp.id) new_lrp = lrp_svc.update(lrp.id, lrp) module.exit_json( changed=True, object_name=module.params['display_name'], id=lrp.id, message="Logical Router Port with name %s has changed tags!" % (module.params['display_name'])) module.exit_json( changed=False, object_name=module.params['display_name'], id=lrp.id, message="Logical Router Port with name %s already exists!" % (module.params['display_name'])) elif module.params['state'] == "absent": if lrp: if module.check_mode: module.exit_json(changed=True, debug_out=str(lrp), id=lrp.id) lrp_svc.delete(lrp.id) module.exit_json( changed=True, object_name=module.params['display_name'], message="Logical Router Port with name %s deleted!" % (module.params['display_name'])) module.exit_json( changed=False, object_name=module.params['display_name'], message="Logical Router Port with name %s does not exist!" % (module.params['display_name']))