def main(): argument_specs = dict( old_password=dict(type='str', required=True, no_log=True), # Flag to specify priority of old/new password while establishing session with controller. # To handle both Saas and conventional (Entire state in playbook) scenario. force_change=dict(type='bool', default=False)) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule(argument_spec=argument_specs) if not HAS_AVI: return module.fail_json( msg=('Avi python API SDK (avisdk) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) api_creds = AviCredentials() api_creds.update_from_ansible_module(module) old_password = module.params.get('old_password') force_change = module.params.get('force_change', False) data = {'old_password': old_password, 'password': api_creds.password} # First try old password if 'force_change' is set to true if force_change: first_pwd = old_password second_pwd = api_creds.password # First try new password if 'force_change' is set to false or not specified in playbook. else: first_pwd = api_creds.password second_pwd = old_password password_changed = False try: api = ApiSession.get_session(api_creds.controller, api_creds.username, password=first_pwd, timeout=api_creds.timeout, tenant=api_creds.tenant, tenant_uuid=api_creds.tenant_uuid, token=api_creds.token, port=api_creds.port) if force_change: rsp = api.put('useraccount', data=data) if rsp: password_changed = True return ansible_return(module, rsp, True, req=data) password_changed = True return module.exit_json(changed=False, obj=data) except: pass if not password_changed: api = ApiSession.get_session(api_creds.controller, api_creds.username, password=second_pwd, timeout=api_creds.timeout, tenant=api_creds.tenant, tenant_uuid=api_creds.tenant_uuid, token=api_creds.token, port=api_creds.port) if not force_change: rsp = api.put('useraccount', data=data) if rsp: return ansible_return(module, rsp, True, req=data) return module.exit_json(changed=False, obj=data)
def main(): argument_specs = dict( full_name=dict(type='str'), email=dict(type='str'), old_password=dict(type='str', required=True, no_log=True), # Flag to specify priority of old/new password while establishing session with controller. # To handle both Saas and conventional (Entire state in playbook) scenario. force_change=dict(type='bool', default=False)) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule(argument_spec=argument_specs) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) or requests is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) api_creds = AviCredentials() api_creds.update_from_ansible_module(module) full_name = module.params.get('full_name') email = module.params.get('email') old_password = module.params.get('old_password') force_change = module.params.get('force_change', False) data = {'old_password': old_password, 'password': api_creds.password} if full_name: data['full_name'] = full_name if email: data['email'] = email api = None if not force_change: # check if the new password is already set. try: api = ApiSession.get_session(api_creds.controller, api_creds.username, password=api_creds.password, timeout=api_creds.timeout, tenant=api_creds.tenant, tenant_uuid=api_creds.tenant_uuid, token=api_creds.token, port=api_creds.port) data['old_password'] = api_creds.password except Exception: # create a new session using the old password. pass if not api: api = ApiSession.get_session(api_creds.controller, api_creds.username, password=old_password, timeout=api_creds.timeout, tenant=api_creds.tenant, tenant_uuid=api_creds.tenant_uuid, token=api_creds.token, port=api_creds.port) rsp = api.put('useraccount', data=data) return ansible_return(module, rsp, True, req=data)
def test_reuse_api_session(self): api2 = ApiSession.get_session(api.controller_ip, api.username, api.password, tenant=api.tenant, tenant_uuid=api.tenant_uuid, api_version=api.api_version, verify=False) assert api == api2
def set_default_password(controller_ip, username): api = ApiSession.get_session(controller_ip, username, password=os.environ['default_password'], api_version='17.2.8') passData = { "username": "******", "password": "******", "old_password": os.environ['default_password'], 'full_name': 'System Administrator', } resp = api.get('systemconfiguration', tenant='admin') r = resp.json() data = r['portal_configuration']['password_strength_check'] = False sysresp = api.put('systemconfiguration', data=data, tenant='admin') if sysresp.status_code == 200: res = api.put('useraccount', data=passData, tenant='admin') if res.status_code == 200: api.clear_cached_sessions() return else: raise Exception("Controller password updation faild %s" % res.content) else: raise Exception("Failed with error %s" % sysresp.content)
def convert(meta, gslb_config_dict, controller_ip, user_name, password, tenant_name, vs_state, output_dir, version, report_name, vs_level_status): vip_cluster_map = None # If controller ip present then only get configuration from controller. if controller_ip: session = ApiSession.get_session(controller_ip, user_name, password) resp = session.get('configuration/export?full_system=true') avi_config = json.loads(resp.text) sites = avi_config['Gslb'][0]['sites'] vip_cluster_map = get_vip_cluster_map(sites) avi_gslb_config = None try: avi_gslb_config = dict() avi_gslb_config['META'] = meta gslb_vs_converter = GslbVsConverter() avi_config = gslb_vs_converter.convert( gslb_config_dict, avi_gslb_config, vs_state, vip_cluster_map) ns_util.add_complete_conv_status( gslb_config_dict, output_dir, avi_config, report_name, vs_level_status) except: update_count('error') LOG.error('Error in config conversion', exc_info=True) return avi_gslb_config
def is_connected(self): ''' To check for successful authentication :return: True: Success or False: Failed ''' self.api = ApiSession.get_session(self.controller_ip, self.username, self.password, tenant="*", api_version=self.get_version())
def main(): argument_specs = dict() argument_specs.update(avi_common_argument_spec()) module = AnsibleModule(argument_spec=argument_specs) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) or requests is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) try: api_creds = AviCredentials() api_creds.update_from_ansible_module(module) api = ApiSession.get_session(api_creds.controller, api_creds.username, password=api_creds.password, timeout=api_creds.timeout, tenant=api_creds.tenant, tenant_uuid=api_creds.tenant_uuid, token=api_creds.token, port=api_creds.port) remote_api_version = api.remote_api_version remote = {} for key in remote_api_version.keys(): remote[key.lower()] = remote_api_version[key] api.close() module.exit_json(changed=False, obj=remote) except Exception as e: module.fail_json(msg=("Unable to get an AVI session. %s" % e))
def upload_config_to_controller(avi_config_dict, controller_ip, username, password, tenant, api_version='17.2.1'): LOG.debug("Uploading config to controller") session = ApiSession.get_session(controller_ip, username, password=password, tenant=tenant, api_version=api_version) try: d = {'configuration': avi_config_dict} path = 'configuration/import' resp = session.post(path, data=d, timeout=7200) if resp.status_code < 300: LOG.info("Config uploaded to controller successfully") else: LOG.error("Upload error response:" + resp.text) raise Exception("Upload error response:" + resp.text) except Exception as e: LOG.error("Failed config upload", exc_info=True) print "Error" raise Exception(e)
def avi_vs_check(avi_controller, avi_username, avi_password,fh, tenant="*"): api = ApiSession.get_session(avi_controller, avi_username, avi_password, tenant=tenant) #api = ApiSession.get_session(avi_controller,avi_username,avi_password) avi_virtual_service = api.get('/virtualservice?join_subresources=runtime',params={'page_size':999},tenant='*') if avi_virtual_service.status_code != 200: print ('Error! API responded with:{}'.format(api.status_code),file=fh) return virtual_service = avi_virtual_service.json() num_of_vs = virtual_service['count'] if num_of_vs == 0: print ("No Virtual Services Configured",file=fh) else: print ("Number of Virtual Services Configured:",virtual_service['count'],file=fh) print ('--------------------------------------------------',file=fh) i = 0 num_of_vs = len(virtual_service['results']) while num_of_vs > i: if virtual_service['results'][i]['runtime']['oper_status']['state'] == 'OPER_UP': if i == num_of_vs: break else: i += 1 else: print ("Virtual Services Name:",virtual_service['results'][i]['name'] + "\tStatus:",virtual_service['results'][i]['runtime']['oper_status']['state'],file=fh) if i == num_of_vs: break else: i += 1 #else: # print ("Virtual Services Name:",virtual_service['results'][i]['name'] + "\tStatus:",virtual_service['results'][i]['runtime']['oper_status']['state'],file=fh) # if i == num_of_vs: # break # else: # i += 1 print ('--------------------------------------------------',file=fh)
def avi_alert_check(avi_controller, avi_username, avi_password,fh, tenant="*"): api = ApiSession.get_session(avi_controller, avi_username, avi_password, tenant=tenant) avi_alert = api.get('/alert',tenant="*") if avi_alert.status_code != 200: print ('Error! API responded with:{}'.format(api.status_code),file=fh) return alert = avi_alert.json() if alert['count'] == 0: print ("Threre are no alerts on the Controller",file=fh) else: print ("Number of alerts on Controller are:",alert['count'],file=fh) print ('--------------------------------------------------',file=fh) j = 0 print ("Below are the HIGH Level Alerts",file=fh) while alert['count'] > 0: if alert["results"][j]["level"] == 'ALERT_HIGH': print ("-------------------------------------------------",file=fh) print ("Alert Event",alert['results'][j]['events'],file=fh) j += 1 if j == alert['count']: break else: j += 1 if j == alert['count']: # print ("there are no HIGH Level Alerts",file=fh) break
def main(): argument_specs = dict( idp_class=dict(type=str, required=True, ), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule(argument_spec=argument_specs) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) idp_class = module.params.get("idp_class", None) idp = get_idp_class(idp_class) if not idp: msg = "IDP {} not supported yet.".format(idp_class) return module.fail_json(msg=msg) avi_credentials = AviCredentials() avi_credentials.update_from_ansible_module(module) try: api = ApiSession.get_session( avi_credentials.controller, avi_credentials.username, password=avi_credentials.password, timeout=avi_credentials.timeout, tenant=avi_credentials.tenant, tenant_uuid=avi_credentials.tenant_uuid, port=avi_credentials.port, idp_class=idp) changed = True except (ConnectionError, SSLError, ChunkedEncodingError) as e: msg = "Error during get session {}".format(e.message) return module.fail_json(msg=msg) return ansible_return(module, None, changed, None, api_context=api.get_context())
def read_callback(): ipport = ':'.join([CONFIG['controller_ip'], CONFIG['controller_port']]) try: api = ApiSession.get_session(controller_ip=ipport, username=CONFIG['username'], password=CONFIG['password'], tenant=CONFIG['tenant']) metric_config = { 'cluster/runtime': dispatch_cluster_runtime, 'serviceengine-inventory': partial(dispatch_inventory, plugin='avi_serviceengine'), 'virtualservice-inventory': partial(dispatch_inventory, plugin='avi_virtualservice'), } for endpoint, dispatch_fn in metric_config.iteritems(): resp = api.get(endpoint) if resp.status_code != 200: collectd.error('failed to collect %s stats: %s', endpoint, resp.text) continue dispatch_fn(data=resp.json()) except Exception as e: collectd.warning(str(e)) return
def main(args): api = ApiSession.get_session(args.controller, args.username, args.password, tenant="*") if args.vs: get_config_logs_for_vs(api, args.vs) else: get_config_logs_for_all_vses(api)
def test_get_key_token(self): api1 = ApiSession(avi_credentials=api.avi_credentials, verify=False) api2 = ApiSession.get_session(avi_credentials=api.avi_credentials, verify=False) assert api1.keystone_token == api2.keystone_token
def delete_vs(self, ctrlr_inst_info, pool_inst_info): tenant = ctrlr_inst_info.get('tenant', 'admin') avi_api = ApiSession.get_session(ctrlr_inst_info['api_endpoint'], ctrlr_inst_info['username'], ctrlr_inst_info['password'], tenant=tenant) vs_name = ctrlr_inst_info.get('virtualservice', 'perf-vs') try: rsp = avi_api.delete_by_name('virtualservice', vs_name) except: pass else: self.log.info('Delete rsp %s', rsp) pool_name = pool_inst_info.get('name', 'perf-pool') try: rsp = avi_api.delete_by_name('pool', pool_name) except: pass else: self.log.info('Delete rsp %s', rsp) ds_name = ctrlr_inst_info.get('datascript', 'perf-vs-datascript') try: rsp = avi_api.delete_by_name('vsdatascriptset', ds_name) except: pass else: self.log.info('Delete rsp %s', rsp)
def test_get_controller_ip(self): api1 = ApiSession(avi_credentials=api.avi_credentials, verify=False) api2 = ApiSession.get_session(avi_credentials=api.avi_credentials, verify=False) assert api1.controller_ip == api2.controller_ip
def main(args): if args: # If not specified on the command-line, prompt the user for the # controller IP address and/or password controller_ip = args.controller user = args.user password = args.password api = ApiSession.get_session(controller_ip, user, password, tenant=args.tenant, api_version=args.api_version) cloud = args.cloud switchto_cloud(api, cloud) all_vs = get_all_vs(api) alb_rule_count = {} for vs in all_vs: az = vs.get('azure_availability_set') if az: for service in vs['services']: alb_rule_count[az] = alb_rule_count.get( az, 0) + service['port_range_end'] - service['port'] + 1 print(alb_rule_count)
def test_tenant(self): api1 = ApiSession(avi_credentials=api.avi_credentials, verify=False) api2 = ApiSession.get_session(avi_credentials=api.avi_credentials, verify=False) assert api1.tenant == api2.tenant
def test_get_api_version(self): api1 = ApiSession(avi_credentials=api.avi_credentials, verify=False) api2 = ApiSession.get_session(avi_credentials=api.avi_credentials, verify=False) assert api1.api_version == api2.api_version
def __init__(self, controller_ip, user='******', passwd='avi123', tenant='admin'): sdk_path = avi.sdk.__path__[0] with open(sdk_path + '/samples/certs/server.crt') as f: self.server_crt = f.read() with open(sdk_path + '/samples/certs/server.key') as f: self.server_key = f.read() with open(sdk_path + '/samples/certs/cakey.pem') as f: self.ca_key = f.read() with open(sdk_path + '/samples/certs/cacert.pem') as f: self.ca_cert = f.read() self.sess = ApiSession.get_session(controller_ip, user, passwd, tenant=tenant) try: ApiUtils(self.sess).import_ssl_certificate('MyCert', self.server_key, self.server_crt) except: pass self.tenant = tenant
def main(args): if args: # If not specified on the command-line, prompt the user for the # controller IP address and/or password controller_ip = args.controller user = args.user password = args.password api = ApiSession.get_session( controller_ip, user, password, tenant=args.tenant, api_version=args.api_version) cloud = args.cloud switchto_cloud(api, cloud) all_vs = get_all_vs(api) alb_rule_count = {} for vs in all_vs: az = vs.get('azure_availability_set') if az: for service in vs['services']: alb_rule_count[az] = alb_rule_count.get(az, 0) + service['port_range_end'] - service['port'] + 1 print alb_rule_count
def create_avi_endpoint(tenant): controller_config = get_avi_controller_config() print ('Connecting to Avi Controller %s...'%(controller_config['ip'])) print ('User : %s Tenant : %s' %(controller_config['username'],tenant)) return ApiSession.get_session(controller_config['ip'], controller_config['username'], controller_config['password'], tenant=tenant)
def setup(): global API API = ApiSession.get_session('127.0.0.1', 'admin', 'avi123', tenant='admin') ApiUtils(API).import_ssl_certificate('MyCert', server_key, server_cert)
def get_avi_config(avi_controller, avi_username, avi_password, tenant="admin"): api = ApiSession.get_session(avi_controller, avi_username, avi_password, tenant=tenant) resp = api.get('configuration/export?include_name=true&uuid_refs=true') return resp.json()
def test_get_username(self): api1 = ApiSession(avi_credentials=api.avi_credentials, verify=False) api2 = ApiSession.get_session(avi_credentials=api.avi_credentials, verify=False) assert api1.username == api2.username
def test_get_port(self): api1 = ApiSession(avi_credentials=api.avi_credentials, verify=False) api2 = ApiSession.get_session(avi_credentials=api.avi_credentials, verify=False) assert api1.port == api2.port
def convert(meta, gslb_config_dict, controller_ip, user_name, password, tenant_name, vs_state, output_dir, version, report_name, vs_level_status): vip_cluster_map = None # If controller ip present then only get configuration from controller. if controller_ip: session = ApiSession.get_session(controller_ip, user_name, password) resp = session.get('configuration/export?full_system=true') avi_config = json.loads(resp.text) sites = avi_config['Gslb'][0]['sites'] vip_cluster_map = get_vip_cluster_map(sites) avi_gslb_config = None try: avi_gslb_config = dict() avi_gslb_config['META'] = meta gslb_vs_converter = GslbVsConverter() avi_config = gslb_vs_converter.convert(gslb_config_dict, avi_gslb_config, vs_state, vip_cluster_map) ns_util.add_complete_conv_status(gslb_config_dict, output_dir, avi_config, report_name, vs_level_status) except: update_count('error') LOG.error('Error in config conversion', exc_info=True) return avi_gslb_config
def avi_cloud_uuid(avi_controller, avi_username, avi_password, tenant="admin"): print('Connecting to Avi Controller Cluster:{}'.format(avi_controller)) print('Authenticating to Avi Control Cluster,username:{}'.format( avi_username)) api = ApiSession.get_session(avi_controller, avi_username, avi_password, tenant=tenant) avi_cloud = api.get('/cloud') if avi_cloud.status_code != 200: print('Error! API responded with:{}'.format(api.status_code)) return cloud = avi_cloud.json() if cloud['count'] == 0: print "There are no Clouds Configured" else: print "Number of Clouds Configured:", cloud['count'] i = 0 while cloud['count'] > i: print(separator) print "Cloud UUID:", cloud['results'][i]['uuid'] cloud_uuid = cloud['results'][i]['uuid'] network_subnet_list = api.get("/networksubnetlist/?cloud_uuid=" + cloud_uuid + '', params={'page_size': 999}) network_subnet_list_new = network_subnet_list.json() if network_subnet_list_new['count'] == 0: print("Networks not found......") else: print "Total number of Networks:", network_subnet_list_new['count'] print "Networks found are:", json.dumps( network_subnet_list_new['results'], indent=4) i += 1 print(separator)
def create_segroup(controller_ip, username, password, segroup_name): session = ApiSession.get_session(controller_ip, username, password) data = {"name": segroup_name} json_data = json.dumps(data) path = "/serviceenginegroup" rsp1 = session.post(path, data=json_data) print rsp1 return rsp1
def create_avi_endpoint(tenant): controller_config = get_avi_controller_config() print('Connecting to Avi Controller %s...' % (controller_config['ip'])) print('User : %s Tenant : %s' % (controller_config['username'], tenant)) return ApiSession.get_session(controller_config['ip'], controller_config['username'], controller_config['password'], tenant=tenant)
def create_vrf_context(controller_ip, username, password, vrf_name): session = ApiSession.get_session(controller_ip, username, password) data = {"name": vrf_name} json_data = json.dumps(data) path = "/vrfcontext" rsp1 = session.post(path, data=json_data) print rsp1 return rsp1
def test_set_port(self): api1 = ApiSession(avi_credentials=api.avi_credentials, verify=False) api2 = ApiSession.get_session(avi_credentials=api.avi_credentials, verify=False) api1.port = '9993' assert api1.port == api2.port api1.port = login_info.get("port")
def test_set_tenant(self): api1 = ApiSession(avi_credentials=api.avi_credentials, verify=False) api2 = ApiSession.get_session(avi_credentials=api.avi_credentials, verify=False) api1.tenant == 'vmware' assert api1.tenant == api2.tenant api1.tenant = login_info.get("tenant", "admin")
def test_set_password(self): api1 = ApiSession(avi_credentials=api.avi_credentials, verify=False) api2 = ApiSession.get_session(avi_credentials=api.avi_credentials, verify=False) api1.password = '******' assert api1.password == api2.password api1.password = login_info.get("password", "fr3sca$%^")
def test_set_tenant_uuid(self): api1 = ApiSession(avi_credentials=api.avi_credentials, verify=False) api2 = ApiSession.get_session(avi_credentials=api.avi_credentials, verify=False) api1.tenant_uuid = "Xyssdd123YYY-test" assert api1.tenant_uuid == api2.tenant_uuid api1.tenant_uuid = login_info.get("tenant_uuid", None)
def test_set_api_version(self): api1 = ApiSession(avi_credentials=api.avi_credentials, verify=False) api2 = ApiSession.get_session(avi_credentials=api.avi_credentials, verify=False) api1.api_version = "17.2.2" assert api1.api_version == api2.api_version api1.api_version = login_info.get("api_version", gapi_version)
def test_set_username(self): api1 = ApiSession(avi_credentials=api.avi_credentials, verify=False) api2 = ApiSession.get_session(avi_credentials=api.avi_credentials, verify=False) api1.username = '******' assert api1.username == api2.username api1.username = login_info.get("username", "admin")
def setupApiSession(self): self.api = None api = ApiSession.get_session(self.controller_ip, self.user, self.password, tenant=self.tenant) server_cert, server_key, _, _ = get_sample_ssl_params() ApiUtils(api).import_ssl_certificate('MyCert', server_key, server_cert) self.api = api return api
def getAviApiSession(): """ create session to avi controller """ global API if not API: API = ApiSession.get_session( '127.0.0.1', 'admin', 'avi123', tenant='admin') return API
def getAviApiSession(tenant='admin'): """ create session to avi controller """ token = os.environ.get('API_TOKEN') user = os.environ.get('USER') # tenant=os.environ.get('TENANT') return ApiSession.get_session("localhost", user, token=token, tenant=tenant)
def get_vip_cluster_map(sites): vip_map=dict() for site in sites: session = ApiSession.get_session( site['ip_addresses'][0]['addr'], site['username'], site['password']) resp = session.get('virtualservice', api_version='17.1.1') vs_list = json.loads(resp.text)['results'] for vs in vs_list: vip_map.update(create_map_for_vs(vs, vip_map, site)) return vip_map
def main(): argument_specs = dict( old_password=dict(type='str', required=True, no_log=True) ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule(argument_spec=argument_specs) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) api_creds = AviCredentials() api_creds.update_from_ansible_module(module) password_updated = False old_password = module.params.get('old_password') data = { 'old_password': old_password, 'password': api_creds.password } password_changed = False try: api = ApiSession.get_session( api_creds.controller, api_creds.username, password=api_creds.password, timeout=api_creds.timeout, tenant=api_creds.tenant, tenant_uuid=api_creds.tenant_uuid, token=api_creds.token, port=api_creds.port) password_changed = True return ansible_return(module, None, False, req=data) except: pass if not password_changed: api = ApiSession.get_session( api_creds.controller, api_creds.username, password=old_password, timeout=api_creds.timeout, tenant=api_creds.tenant, tenant_uuid=api_creds.tenant_uuid, token=api_creds.token, port=api_creds.port) rsp = api.put('useraccount', data=data) if rsp: return ansible_return(module, rsp, True, req=data) return module.exit_json(changed=False, obj=data)
def create_tenant(controller_ip, username, password, name): """" Create non default tenant on the given Controller. """ session = ApiSession.get_session (controller_ip, username, password) data = {'local': True, 'name': name} json_data = json.dumps (data) path = "/tenant?" rsp = session.post (path, data=json_data) print rsp return
def create_cloud(controller_ip, username, password, cloud_name): """" Create non default cloud name on the given Controller. """ session = ApiSession.get_session (controller_ip, username, password) data = {"vtype": "CLOUD_NONE","name": cloud_name} json_data = json.dumps (data) path = "/cloud?include_name" rsp1 = session.post (path, data=json_data) print rsp1 return json.loads (rsp1.content)
def download_gslb_from_controller(controller_ip, username, password, tenant='admin'): """ Function to download the gslb configuration from controller """ LOG.debug("Downloading gslb config from the controller") session = ApiSession.get_session(controller_ip, username, password, tenant="admin") try: path = 'gslb' resp = session.get(path) return resp.text except Exception as e: LOG.error("Failed gslb config download", exec_info=True) print "Error in Downloading gslb config" raise Exception(e)
def verify_controller_is_up(controller_ip, username, password): """"" Verify the given Controller is running by getting it's CLUSTER_UP_HA_ACTIVE, CLUSTER_UP_NO_HA states using AVI API. """ session = ApiSession.get_session (controller_ip, username, password) cluster_up_states = ["CLUSTER_UP_HA_ACTIVE", "CLUSTER_UP_NO_HA"] data = session.get('cluster/runtime') data = json.loads (data.content) if data['cluster_state']['state'] in cluster_up_states: print "Node is active. We can use controller for further process." return True return False
def reset_connection(self): login_info = gSAMPLE_CONFIG["User2"] old_password = login_info["password"] api2 = ApiSession.get_session( api.controller_ip, login_info["username"], old_password, tenant=api.tenant, tenant_uuid=api.tenant_uuid, verify=False) user_obj = api.get_object_by_name("user", login_info["name"]) new_password = "******" if login_info["password"] == new_password: new_password = "******" user_obj["password"] = new_password api.put("user/"+user_obj["uuid"], data=json.dumps(user_obj)) user_obj["password"] = old_password api.put_by_name("user", user_obj["name"], data=json.dumps(user_obj)) resp = api2.get("pool") assert resp.status_code < 300
def setUpModule(): cfg_file = open('test_api.cfg', 'r') cfg = cfg_file.read() global gSAMPLE_CONFIG gSAMPLE_CONFIG = json.loads(cfg) log.debug(' read cofig %s', gSAMPLE_CONFIG) global login_info login_info = gSAMPLE_CONFIG["LoginInfo"] global api api = ApiSession.get_session( login_info["controller_ip"], login_info.get("username", "admin"), login_info.get("password", "avi123"), tenant=login_info.get("tenant", "admin"), tenant_uuid=login_info.get("tenant_uuid", None), verify=False)
def test_multi_tenant(args, tenants): ''' 1. get list of tenants 2. create API for each tenant 3. call virtual service get on each tenant ''' t_apis = [] for tenant in tenants: api = ApiSession.get_session(args.controller_ip, args.user, args.password, tenant=tenant) t_apis.append(api) print ' created api for teant %s api %s' % (tenant, api) for _ in xrange(5): for api in t_apis: r = api.get('virtualservice') results = json.loads(r.text)['results'] logger.debug(' tenant %s num vs %d', api.tenant, len(results))
def get_object_from_controller(object_type, object_name, controller_ip, username, password, tenant): """ This function defines that it get the object from controller or raise exception if object status code is less than 299 :param uri: URI to get the object :param controller_ip: ip of controller :param username: usename of controller :param password: password of controller :param tenant: tenant of controller :return: response status_code and content """ # Create new session session = ApiSession.get_session(controller_ip, username, password=password, tenant=tenant) try: resp = session.get_object_by_name(object_type, object_name) return resp except: raise Exception("Failed get %s" % object_name, exc_info=True)
def clean_reboot(controller_ip, username, password, version, licensefile_path): """"" Clean Reboot the given Controller by using AVI API and polls the controller status till the cluster up. """ session = ApiSession.get_session (controller_ip, username, password) res = session.post('cluster/reboot/', data=json.dumps ({'mode': 'REBOOT_CLEAN'}), auth=(username, password)) if res.status_code < 300: wait_until_node_ready (session) if version > "16.5.4" : session.clear_cached_sessions() set_default_password(controller_ip, username) else: raise Exception("Failed with error %s" % res.content) with open(licensefile_path, 'r') as license: license_text = license.read() licensefile = json.dumps({"license_text": license_text}) upload_license(session, licensefile)
def main(): module = AnsibleModule(argument_spec=avi_common_argument_spec()) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) try: api_creds = AviCredentials() api_creds.update_from_ansible_module(module) api = ApiSession.get_session( api_creds.controller, api_creds.username, password=api_creds.password, timeout=api_creds.timeout, tenant=api_creds.tenant, tenant_uuid=api_creds.tenant_uuid, token=api_creds.token, port=api_creds.port) remote_api_version = api.remote_api_version remote = {} for key in remote_api_version.keys(): remote[key.lower()] = remote_api_version[key] api.close() module.exit_json(changed=False, obj=remote) except Exception as e: module.fail_json(msg="Unable to get an AVI session. {}".format(e))
tenant=tenant) t_apis.append(api) print ' created api for teant %s api %s' % (tenant, api) for _ in xrange(5): for api in t_apis: r = api.get('virtualservice') results = json.loads(r.text)['results'] logger.debug(' tenant %s num vs %d', api.tenant, len(results)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-c', '--controller_ip', help='controller ip') parser.add_argument('-u', '--user', default='admin', help='controller ip') parser.add_argument('-p', '--password', default='avi123', help='controller ip') tenants = [] args = parser.parse_args() logger.debug('parsed args %s', args) api = ApiSession.get_session(args.controller_ip, username=args.user, password=args.password, tenant='admin') resp = api.get('tenant') logger.debug('resp code %d txt %s', resp.status_code, resp.text) tenants = (json.loads(resp.text))['results'] tnames = [tenant['name'] for tenant in tenants] test_multi_tenant(args, tnames)
def avi_ansible_api(module, obj_type, sensitive_fields): """ This converts the Ansible module into AVI object and invokes APIs :param module: Ansible module :param obj_type: string representing Avi object type :param sensitive_fields: sensitive fields to be excluded for comparison purposes. Returns: success: module.exit_json with obj=avi object faliure: module.fail_json """ api = ApiSession.get_session( module.params['controller'], module.params['username'], module.params['password'], tenant=module.params['tenant']) state = module.params['state'] # Get the api version. api_version = module.params.get('api_version', '16.4') name = module.params.get('name', None) check_mode = module.check_mode obj_path = None if name is None: obj_path = '%s/' % obj_type obj = deepcopy(module.params) obj.pop('state', None) obj.pop('controller', None) obj.pop('username', None) obj.pop('password', None) # pop avi_version obj.pop('api_version', None) # Special code to handle situation where object has a field # named username. This is used in case of api/user # The following code copies the username and password # from the obj_username and obj_password fields. if 'obj_username' in obj: obj['username'] = obj['obj_username'] obj.pop('obj_username') if 'obj_password' in obj: obj['password'] = obj['obj_password'] obj.pop('obj_password') tenant = obj.pop('tenant', '') tenant_uuid = obj.pop('tenant_uuid', '') # obj.pop('cloud_ref', None) purge_optional_fields(obj, module) log.info('passed object %s ', obj) if name is not None: params = {'include_refs': '', 'include_name': ''} if obj.get('cloud_ref', None): # this is the case when gets have to be scoped with cloud cloud = obj['cloud_ref'].split('name=')[1] params['cloud_ref.name'] = cloud existing_obj = api.get_object_by_name( obj_type, name, tenant=tenant, tenant_uuid=tenant_uuid, params=params, api_version=api_version) else: # added api version to avi api call. existing_obj = api.get(obj_path, tenant=tenant, tenant_uuid=tenant_uuid, params={'include_refs': '', 'include_name': ''}, api_version=api_version).json() if state == 'absent': try: if check_mode: if existing_obj: return module.exit_json(changed=True, obj=existing_obj) else: return module.exit_json(changed=False, obj=None) if name is not None: # added api version to avi api call. rsp = api.delete_by_name( obj_type, name, tenant=tenant, tenant_uuid=tenant_uuid, api_version=api_version) else: # added api version to avi api call. rsp = api.delete(obj_path, tenant=tenant, tenant_uuid=tenant_uuid, api_version=api_version) except ObjectNotFound: return module.exit_json(changed=False) if rsp.status_code == 204: return module.exit_json(changed=True) return module.fail_json(msg=rsp.text) changed = False rsp = None req = None if existing_obj: # this is case of modify as object exists. should find out # if changed is true or not changed = not avi_obj_cmp(obj, existing_obj, sensitive_fields) obj = cleanup_absent_fields(obj) if changed: log.debug('EXISTING OBJ %s', existing_obj) log.debug('NEW OBJ %s', obj) if name is not None: obj_uuid = existing_obj['uuid'] obj_path = '%s/%s' % (obj_type, obj_uuid) req = obj if check_mode: # No need to process any further. rsp = AviCheckModeResponse(obj=existing_obj) else: rsp = api.put(obj_path, data=req, tenant=tenant, tenant_uuid=tenant_uuid, api_version=api_version) elif check_mode: rsp = AviCheckModeResponse(obj=existing_obj) else: changed = True req = obj if check_mode: rsp = AviCheckModeResponse(obj=None) else: rsp = api.post(obj_type, data=obj, tenant=tenant, tenant_uuid=tenant_uuid, api_version=api_version) if rsp is None: return module.exit_json(changed=changed, obj=existing_obj) else: return ansible_return(module, rsp, changed, req, existing_obj=existing_obj)
default="OktaSAMLApiSession") parser.add_argument( '-s', '--server_ips', help='Pool Server IPs comma separated Eg. 1.1.1.1,2.2.2.2', default='1.1.1.1,1.1.1.2') parser.add_argument('-u', '--idp_user', help='IDP username', default='*****@*****.**') parser.add_argument('-p', '--idp_password', help='IDP user password', default='foo123') parser.add_argument('-t', '--tenant', help='tenant name', default=None) parser.add_argument('--tenant-uuid', help='tenant uuid', default=None) parser.add_argument('-c', '--controller_ip', help='controller ip') parser.add_argument('-i', '--vip', help='VIP address') args = parser.parse_args() print('parsed args', args) idp_cls = SAMLExample.get_idp_class(args.idp_class) # SAML authentication with given IDP and get the controller session api = ApiSession.get_session(args.controller_ip, args.idp_user, args.idp_password, tenant=args.tenant, tenant_uuid=args.tenant_uuid, idp_class=idp_cls) servers = [server.strip() for server in args.server_ips.split(',')] vse = SAMLExample(api) # Create basic VS vip = args.vip if args.vip else '10.10.42.2' vse.create_basic_vs('basic-vs', vip, servers)
def create_avi_endpoint(): token=os.environ.get('API_TOKEN') user=os.environ.get('USER') # tenant=os.environ.get('TENANT') return ApiSession.get_session("localhost", user, token=token, tenant='admin')
def main(args): if args: # If not specified on the command-line, prompt the user for the # controller IP address and/or password controller_ip = args.controller user = args.user password = args.password while not controller_ip: controller_ip = input('Controller:') while not password: password = getpass.getpass('Password for %s@%s:' % (user, controller_ip)) api = ApiSession.get_session( controller_ip, user, password, tenant=args.tenant, api_version=args.api_version) cloud = args.cloud from_segrp = args.fromsegroup to_segrp = args.tosegroup switchto_cloud(api, cloud) dry_run_mode = args.dryrun suffix = args.suffix enabled = args.enable all_vs = get_all_vs(api) print(all_vs) old_se_grp_uuid = api.get('serviceenginegroup?name=%s' % from_segrp).json()[ 'results'][0]['uuid'] print('se_grp_uuid : %s' % old_se_grp_uuid) new_se_grp = api.get('serviceenginegroup?name=%s' % to_segrp).json()['results'][0] print('new_se_grp_uuid : %s' % new_se_grp['uuid']) c_vs_vips = {} all_vsvips = {} all_nw_policies = [] all_vses = [] all_http_pols = [] for vs in all_vs: shared_vip = False vs_uuid = vs['uuid'] vs_api = 'virtualservice/%s?join_subresources=runtime&page_size=1000' % vs_uuid vs = api.get(vs_api).json() vs_segid = vs['se_group_ref'].split('/')[-1] if vs_segid != old_se_grp_uuid: #print('Skipping VS as it does not belong to se group %s: %s' % # (args.fromsegroup, vs['name'])) continue print('Cloning VS %s to segrp %s' % (vs['name'], args.tosegroup)) vs.pop('runtime') vs.pop('vip_runtime') #if not vs.has_key('vsvip_ref'): if not ('vsvip_ref' in vs): continue old_vsvip_ref = vs['vsvip_ref'] #if c_vs_vips.has_key(old_vsvip_ref): if old_vsvip_ref in c_vs_vips: shared_vip = True else: c_vs_vips[old_vsvip_ref] = True vsvip = api.get('vsvip/%s' % old_vsvip_ref.split('/')[-1]).json() vsvip['vip'][0].pop('ip_address') if 'floating_ip' in vsvip['vip'][0]: #if vsvip['vip'][0].has_key('floating_ip'): vsvip['vip'][0].pop('floating_ip') vsvip['name'] = vsvip['name'] + suffix vsvip.pop('uuid') if 'use_standard_alb' in new_se_grp: vsvip['use_standard_alb'] = new_se_grp['use_standard_alb'] vsvip_post = None if not dry_run_mode: if shared_vip: vsvip_post = api.get_object_by_name('vsvip', vsvip['name']) else: try: vsvip_post = api.post('vsvip', vsvip).json() except APIError as e: if e.rsp.status_code == 409: vsvip_post = api.get_object_by_name('vsvip', vsvip['name']) else: raise e except Exception as e: raise e vsvip_ref = api.get_obj_ref(vsvip_post) print(vsvip_post) else: vsvip_ref = get_ref_url_by_name( controller_ip, vsvip['name'], 'vsvip', tenant=tenant) all_vsvips[vsvip_ref] = vsvip #if vs.has_key('http_policies'): if 'http_policies' in vs: http_policies = vs['http_policies'] if http_policies: for pol in http_policies: pol_obj = api.get( 'httppolicyset/%s' % pol['http_policy_set_ref'].split('/')[-1]).json() pol_obj['name'] = pol_obj['name'] + suffix pol_obj.pop('uuid') if not dry_run_mode: try: new_pol_obj = api.post('httppolicyset', pol_obj) except APIError as e: if e.rsp.status_code == 409: new_pol_obj = api.get_object_by_name('httppolicyset', pol_obj['name']) pass else: raise e http_pol_ref = api.get_obj_ref(new_pol_obj) else: http_pol_ref = get_ref_url_by_name( controller_ip, pol_obj['name'], 'httppolicyset') all_http_pols.append(pol_obj) pol['http_policy_set_ref'] = http_pol_ref #if vs.has_key('network_security_policy_ref'): if 'network_security_policy_ref' in vs: netw_sec_pol_ref = vs['network_security_policy_ref'] netw_sec_pol = api.get('networksecuritypolicy/%s' % netw_sec_pol_ref.split('/')[-1]).json() netw_sec_pol.pop('uuid') netw_sec_pol['name'] = netw_sec_pol['name'] + suffix netw_sec_pol_post = None if not dry_run_mode: try: netw_sec_pol_post = api.post( 'networksecuritypolicy', netw_sec_pol).json() except APIError as e: if e.rsp.status_code == 409: netw_sec_pol_post = api.get_object_by_name('networksecuritypolicy', netw_sec_pol['name']) pass else: raise e nw_pol_ref = api.get_obj_ref(netw_sec_pol_post) else: nw_pol_ref = get_ref_url_by_name( controller_ip, netw_sec_pol['name'], 'networksecuritypolicy') all_nw_policies.append(netw_sec_pol) else: nw_pol_ref = None vs['name'] = vs['name'] + suffix vs['vsvip_ref'] = vsvip_ref vs['enabled'] = enabled if not dry_run_mode: vs['vip'][0]['ip_address']['addr'] = vsvip_post['vip'][0]['ip_address']['addr'] vs['network_security_policy_ref'] = nw_pol_ref vs['se_group_ref'] = api.get_obj_ref(new_se_grp) vs.pop('uuid') if not dry_run_mode: try: time.sleep(0.5) vs_post = api.post('virtualservice', vs).json() except APIError as e: if e.rsp.status_code == 409: pass else: raise e all_vses.append(vs) for vs in all_vs: vs_uuid = vs['uuid'] vs_api = 'virtualservice/%s?join_subresources=runtime&page_size=1000' % vs_uuid vs = api.get(vs_api).json() vs.pop('runtime') vs.pop('vip_runtime') #if vs.has_key('vsvip_ref'): if 'vsvip_ref' in vs: #print('Skipping VS %s as it has its own VIP' % vs['name']) continue if vs['type'] != 'VS_TYPE_VH_CHILD': #print('%s is not child vs' % vs['name']) continue parent_vs = api.get('virtualservice/%s' % vs['vh_parent_vs_ref'].split('/')[-1]).json() vs_segid = parent_vs['se_group_ref'].split('/')[-1] if vs_segid != old_se_grp_uuid: #print('Skipping VS %s as it does not belong to se group %s' % # (vs['name'], args.fromsegroup)) continue print('checking vs %s' % vs['name']) new_parent = parent_vs['name'] + suffix vs['name'] = vs['name'] + suffix vs.pop('uuid') vs['enabled'] = enabled #if vs.has_key('http_policies'): if 'http_policies' in vs: http_policies = vs['http_policies'] if http_policies: for pol in http_policies: pol_obj = api.get( 'httppolicyset/%s' % pol['http_policy_set_ref'].split('/')[-1]).json() pol_obj['name'] = pol_obj['name'] + suffix pol_obj.pop('uuid') if not dry_run_mode: try: new_pol_obj = api.post('httppolicyset', pol_obj) except APIError as e: if e.rsp.status_code == 409: new_pol_obj = api.get_object_by_name('httppolicyset', pol_obj['name']) pass else: raise e http_pol_ref = api.get_obj_ref(new_pol_obj) else: http_pol_ref = get_ref_url_by_name( controller_ip, pol_obj['name'], 'httppolicyset') all_http_pols.append(pol_obj) pol['http_policy_set_ref'] = http_pol_ref #if vs.has_key('network_security_policy_ref'): if 'network_security_policy_ref' in vs: netw_sec_pol_ref = vs['network_security_policy_ref'] netw_sec_pol = api.get('networksecuritypolicy/%s' % netw_sec_pol_ref.split('/')[-1]).json() netw_sec_pol.pop('uuid') netw_sec_pol['name'] = netw_sec_pol['name'] + suffix netw_sec_pol_post = None if not dry_run_mode: try: netw_sec_pol_post = api.post( 'networksecuritypolicy', netw_sec_pol).json() except APIError as e: if e.rsp.status_code == 409: netw_sec_pol_post = api.get_object_by_name('networksecuritypolicy', netw_sec_pol['name']) pass else: raise e nw_pol_ref = api.get_obj_ref(netw_sec_pol_post) else: nw_pol_ref = get_ref_url_by_name( controller_ip, netw_sec_pol['name'], 'networksecuritypolicy') vs['network_security_policy_ref'] = nw_pol_ref all_nw_policies.append(netw_sec_pol) else: nw_pol_ref = None if not dry_run_mode: new_parent_vs = api.get('virtualservice?name=%s' % new_parent).json()[ 'results'][0] parent_vs_ref = api.get_obj_ref(new_parent_vs) vs['vh_parent_vs_ref'] = parent_vs_ref try: vs_post = api.post('virtualservice', vs) except APIError as e: if e.rsp.status_code == 409: pass else: raise e print('posted vs %s' % vs_post) else: parent_vs_ref = get_ref_url_by_name( controller_ip, new_parent, 'virtualservice') vs['vh_parent_vs_ref'] = parent_vs_ref all_vses.append(vs) with open('vsvip.json', mode='w') as outfile: # json.dump(all_vsvips.values(), outfile, indent=4, sort_keys=True) json.dump(all_vsvips, outfile, indent=4, sort_keys=True) with open('nwpolicies.json', mode='w') as outfile: json.dump(all_nw_policies, outfile, indent=4, sort_keys=True) with open('httppolicies.json', mode='w') as outfile: json.dump(all_http_pols, outfile, indent=4, sort_keys=True) with open('vs.json', mode='w') as outfile: json.dump(all_vses, outfile, indent=4, sort_keys=True)
obj['certificate']['subject_alt_names'] = alt_names return obj def get_all_sslkeyandcertificate_w_alt_names(api): r = api.get('sslkeyandcertificate?page_size=1000').json() ssl_certs = r['results'] for ssl_cert_obj in ssl_certs: get_sslkeyandcertificate_w_alt_names(api, ssl_cert_obj['name'], obj=ssl_cert_obj) return ssl_certs if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-u', '--user', help='controller user', default='admin') parser.add_argument('-p', '--password', help='controller user password', default='avi123') parser.add_argument('-t', '--tenant', help='tenant name', default='admin') parser.add_argument('-c', '--controller_ip', help='controller ip') args = parser.parse_args() api = ApiSession.get_session(args.controller_ip, args.user, args.password, tenant=args.tenant) ssl_certs = get_all_sslkeyandcertificate_w_alt_names(api) for ssl_cert in ssl_certs: print(ssl_cert['name']) print(' Alternate Subject Names:', ssl_cert['certificate'].get('subject_alt_names', []))