def test_ssl_vs(self): papi = ApiSession(api.avi_credentials.controller, api.avi_credentials.username, api.avi_credentials.password, api_version=api.avi_credentials.api_version, verify=False, data_log=True) ssl_vs_cfg = gSAMPLE_CONFIG["SSL-VS"] vs_obj = ssl_vs_cfg["vs_obj"] pool_name = gSAMPLE_CONFIG["SSL-VS"]["pool_obj"]["name"] resp = papi.post('pool', data=gSAMPLE_CONFIG["SSL-VS"]["pool_obj"]) assert resp.status_code == 201 pool_ref = papi.get_obj_ref(resp.json()) cert, key, _, _ = get_sample_ssl_params \ (folder_path=os.path.abspath( os.path.join(os.path.dirname(__file__), '..', 'samples')) + os.sep) api_utils = ApiUtils(papi) try: resp = api_utils.import_ssl_certificate("ssl-vs-kc", key, cert) ssl_kc = resp.json() except: ssl_kc = api.get_object_by_name('sslkeyandcertificate', 'ssl-vs-kc') ssl_key_and_cert_ref = [papi.get_obj_ref(ssl_kc)] vs_obj["pool_ref"] = pool_ref vs_obj["ssl_key_and_certificate_refs"] = ssl_key_and_cert_ref resp = papi.post('virtualservice', data=json.dumps(vs_obj)) assert resp.status_code < 300 resp = papi.delete_by_name('virtualservice', vs_obj['name']) assert resp.status_code in (200, 204) resp = papi.delete_by_name("pool", pool_name) assert resp.status_code in (200, 204) resp = api.delete_by_name('sslkeyandcertificate', 'ssl-vs-kc') assert resp.status_code in (200, 204)
def test_ssl_vs(self): papi = ApiSession(api.controller_ip, api.username, api.password, verify=False) ssl_vs_cfg = gSAMPLE_CONFIG["SSL-VS"] vs_obj = ssl_vs_cfg["vs_obj"] pool_name = gSAMPLE_CONFIG["SSL-VS"]["pool_obj"]["name"] resp = papi.post('pool', data=json.dumps(ssl_vs_cfg["pool_obj"])) pool_ref = papi.get_obj_ref(resp.json()) cert, key, _, _ = get_sample_ssl_params(folder_path='../samples/') api_utils = ApiUtils(papi) try: resp = api_utils.import_ssl_certificate("ssl-vs-kc", key, cert) ssl_kc = resp.json() except: ssl_kc = api.get_object_by_name('sslkeyandcertificate', 'ssl-vs-kc') ssl_key_and_cert_ref = [papi.get_obj_ref(ssl_kc)] vs_obj["pool_ref"] = pool_ref vs_obj["ssl_key_and_certificate_refs"] = ssl_key_and_cert_ref resp = papi.post('virtualservice', data=json.dumps(vs_obj)) assert resp.status_code < 300 resp = papi.delete_by_name('virtualservice', vs_obj['name']) assert resp.status_code in (200, 204) resp = papi.delete_by_name("pool", pool_name) assert resp.status_code in (200, 204) resp = api.delete_by_name('sslkeyandcertificate', 'ssl-vs-kc') assert resp.status_code in (200, 204)
def test_ssl_vs(self): papi = ApiSession('10.10.25.42', 'admin', 'avi123', verify=False, api_version="17.2.1") ssl_vs_cfg = gSAMPLE_CONFIG["SSL-VS"] vs_obj = ssl_vs_cfg["vs_obj"] pool_name = gSAMPLE_CONFIG["SSL-VS"]["pool_obj"]["name"] resp = papi.post('pool', data=gSAMPLE_CONFIG["SSL-VS"]["pool_obj"]) assert resp.status_code == 201 pool_ref = papi.get_obj_ref(resp.json()) cert, key, _, _ = get_sample_ssl_params(folder_path='../samples/') api_utils = ApiUtils(papi) try: resp = api_utils.import_ssl_certificate("ssl-vs-kc", key, cert) print resp.text ssl_kc = resp.json() except: ssl_kc = api.get_object_by_name('sslkeyandcertificate', 'ssl-vs-kc') ssl_key_and_cert_ref = [papi.get_obj_ref(ssl_kc)] vs_obj["pool_ref"] = pool_ref vs_obj["ssl_key_and_certificate_refs"] = ssl_key_and_cert_ref resp = papi.post('virtualservice', data=json.dumps(vs_obj)) print resp, resp.text assert resp.status_code < 300 resp = papi.delete_by_name('virtualservice', vs_obj['name']) assert resp.status_code in (200, 204) resp = papi.delete_by_name("pool", pool_name) assert resp.status_code in (200, 204) resp = api.delete_by_name('sslkeyandcertificate', 'ssl-vs-kc') assert resp.status_code in (200, 204)
def metrics(vs_uuid, m_id, tenant, step, limits): mq = { 'metric_id': m_id, 'tenant': 'admin', 'step': step, 'limit': limits, 'entity_uuid': vs_uuid } api_utils = ApiUtils(api) rsp = api_utils.get_metrics_collection(metric_requests=[mq]) total_value = 0 for data in rsp['series'][vs_uuid][0]['data']: total_value += data['value'] return total_value/limits
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 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 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 fetch_data(api_ssn, cloud, tenant, metric_ids): """ :param api_ssn: :param cloud: :param tenant: :param metric_ids: :return: """ api_utils = ApiUtils(api_ssn) api_params = { 'cloud_ref.name': cloud, 'include_name': '', 'metric_id': metric_ids } vs_results = api_ssn.get('virtualservice-inventory', params=api_params, tenant=tenant).json() results = [] for vs in vs_results['results']: config = vs['config'] pool_names = [pool.split('#')[1] for pool in vs.get('pools', [])] pool_refs = vs.get('pools', []) domain_name = config.get('vh_domain_name') vh_parent_vs_ref = config.get('vh_parent_vs_ref', '') vh_parent_vs_name = (vh_parent_vs_ref.split('#')[1] if vh_parent_vs_ref else '') metrics = vs['metrics'] vs_data = VSData(name=config['name'], uuid=config['uuid'], domain_name=domain_name, pool_names=pool_names, pool_refs=pool_refs, vh_parent_vs_name=vh_parent_vs_name, metrics=metrics) results.append(vs_data) return results
'--user', type=str, required=True, help='Username to authenticate against Avi Controller') parser.add_argument('-p', '--password', type=str, required=True, help='Password to authenticate against Avi Controller') args = parser.parse_args() api = ApiSession.get_session(args.controller, args.user, args.password, tenant=args.tenant) api_utils = ApiUtils(api) def get_metrics(entity_type, entity_name, metric_id, step, tenant): try: metrics_dict = api_utils.get_metrics(entity_type, entity_name, metric_id=metric_id, step=step, limit=1, tenant=tenant, timeout=5) return metrics_dict['series'][0]['data'][0]['value'] except: print 'Error in getting %s metric for %s name: %s' % ( metric_id, entity_type, entity_name)
parser.add_argument('-c', '--controller', help='controller ip', default='127.0.0.1') parser.add_argument('-u', '--username', help='user name', default='admin') parser.add_argument('-p', '--password', help='password', default='admin') parser.add_argument('--se_uuid', help='SE UUID', required=True) args = parser.parse_args() #print('parsed args', args) api_ssn = ApiSession(args.controller, args.username, args.password, args.tenant) api_utils = ApiUtils(api_ssn) entity_uuid = '*' mq = [ { 'metric_id': "se_stats.avg_cpu_usage", 'tenant': (args.tenant if args.tenant else 'admin'), 'step': args.step, 'limit': args.limit, 'serviceengine_uuid': args.se_uuid, 'pad_missing_data': False, }, { 'metric_id': "l7_client.sum_get_reqs, l7_client.sum_post_reqs,l4_client.avg_bandwidth," "l4_client.avg_complete_conns,l7_client.avg_complete_responses", 'tenant': (args.tenant if args.tenant else 'admin'),
class VirtualServiceExample(object): ''' Provides example of following operations 1. Create basic vs 2. Create vs with SSL objects 3. Create vs with custom parameters like application profile 4. Inventory API calls for virtualservice 5. Metrics API calls for virtualservice metrics ''' def __init__(self, api): self.api = api self.api_utils = ApiUtils(api) def create_basic_vs(self, vs_name, vip, servers=None): # first create pool for virtual service servers_obj = self.get_server_obj(servers) pool_name = vs_name + '-pool' pool_obj = self.create_pool(pool_name, servers_obj) pool_ref = self.api.get_obj_ref(pool_obj) # create virtual service dict services_obj = [{'port': 80, 'enable_ssl': False}] vs_obj = { 'name': vs_name, 'type': 'VS_TYPE_NORMAL', 'ip_address': { 'addr': vip, 'type': 'V4' }, 'enabled': True, 'services': services_obj, 'application_profile_name': 'System-HTTP', 'pool_ref': pool_ref } # post VS data in json format to avi api resp = self.api.post('virtualservice', data=json.dumps(vs_obj)) if resp.status_code in xrange(200, 299): logger.debug('Virtual service created successfully %s' % vs_name) else: logger.debug('Error creating virtual service : %s' % resp.text) def create_ssl_vs(self, vs_name, vip, servers=None): # import certs. ssl_kc_name = vs_name + '-' + 'ssl-kc' ssl_key_and_cert_ref = [self.upload_ssl_certs(ssl_kc_name)] # turning on SSL profile services_obj = [{'port': 443, 'enable_ssl': True}] servers_obj = self.get_server_obj(servers) # create pool for virtual service pool_name = vs_name + '-pool' pool_obj = self.create_pool(pool_name, servers_obj) pool_ref = self.api.get_obj_ref(pool_obj) # create virtual service dict for ssl VS vs_obj = { 'name': vs_name, 'type': 'VS_TYPE_NORMAL', 'ip_address': { 'addr': vip, 'type': 'V4' }, 'enabled': True, 'services': services_obj, 'ssl_key_and_certificate_refs': ssl_key_and_cert_ref, 'ssl_profile_name': 'System-Standard', 'application_profile_name': 'System-Secure-HTTP', 'pool_ref': pool_ref } resp = self.api.post('virtualservice', data=json.dumps(vs_obj)) if resp.status_code >= 200 and resp.status_code < 300: logger.debug('Virtual service created successfully %s' % vs_name) else: raise Exception('error %s' % str(resp)) def create_custom_vs(self, vs_name, vip, servers=None): # import certs. ssl_kc_name = vs_name + '-' + 'ssl-kc' ssl_key_and_cert_ref = [self.upload_ssl_certs(ssl_kc_name)] # turning on SSL profile services_obj = [{'port': 443, 'enable_ssl': True}] # create custom pool with health monitors servers_obj = self.get_server_obj(servers) pool_name = vs_name + '-pool' pool_obj = self.create_pool( pool_name, servers_obj, ['System-TCP', 'System-HTTP', 'System-Ping']) pool_ref = self.api.get_obj_ref(pool_obj) # create virtual service dict for ssl VS vs_obj = { 'name': vs_name, 'type': 'VS_TYPE_NORMAL', 'ip_address': { 'addr': vip, 'type': 'V4' }, 'enabled': True, 'services': services_obj, 'ssl_key_and_certificate_refs': ssl_key_and_cert_ref, 'ssl_profile_name': 'System-Standard', 'application_profile_name': 'System-Secure-HTTP', 'pool_ref': pool_ref } resp = self.api.post('virtualservice', data=json.dumps(vs_obj)) if resp.status_code >= 200 and resp.status_code < 300: logger.debug('Virtual service created successfully %s' % vs_name) else: logger.debug('Error creating virtual service : %s' % resp.text) def create_policy_vs(self, vs_name, vip, servers=None): ''' This is example to create a custom vs with HTTP policies 1. creates a rewrite policy ''' # import certs. ssl_kc_name = vs_name + '-' + 'ssl-kc' ssl_key_and_cert_ref = [self.upload_ssl_certs(ssl_kc_name)] # turning on SSL profile services_obj = [{'port': 443, 'enable_ssl': True}] # create custom pool with health monitors servers_obj = self.get_server_obj(servers) pool_name = vs_name + '-pool' pool_obj = self.create_pool( pool_name, servers_obj, ['System-TCP', 'System-HTTP', 'System-Ping']) pool_ref = self.api.get_obj_ref(pool_obj) # create virtual service dict for ssl VS vs_obj = { 'name': vs_name, 'type': 'VS_TYPE_NORMAL', 'ip_address': { 'addr': vip, 'type': 'V4' }, 'enabled': True, 'services': services_obj, 'ssl_key_and_certificate_refs': ssl_key_and_cert_ref, 'ssl_profile_name': 'System-Standard', 'application_profile_name': 'System-Secure-HTTP', 'pool_ref': pool_ref } resp = self.api.post('virtualservice', data=json.dumps(vs_obj)) if resp.status_code >= 200 and resp.status_code < 300: logger.debug('Virtual service created successfully %s' % vs_name) else: logger.debug('Error creating virtual service : %s' % resp.text) def get_inventory(self, inventory_type='virtualservice-inventory', obj_uuid='', params=None): params = {} if not params else params if 'page' not in params: params['page'] = 1 if 'page_size' not in params: params['page_size'] = 10 inventory_path = inventory_type if obj_uuid: # this is case of inventory for a specific object inventory_path = inventory_path + '/' + obj_uuid resp = self.api.get(inventory_path, params=params) if resp.status_code in xrange(200, 299): return json.loads(resp.text) else: return 'Error in getting inventory for %s, Error :%s' % ( inventory_type, resp.text) def delete(self, name, entity_type): resp = self.api.delete_by_name(entity_type, name) if resp.status_code in xrange(200, 299): print '%s name: %s deleted successfully' % (entity_type, name) else: print 'Error in deleting virtual service :%s' % resp.text def get_metrics(self, name, metric_id, entity_type='virtualservice'): resp = self.api.get_object_by_name(entity_type, name) uuid = self.api.get_obj_uuid(resp) path = 'analytics/metrics/%s/%s/?metric_id=%s&step=300&limit=12' % ( entity_type, uuid, metric_id) resp = self.api.get(path) if resp.status_code in xrange(200, 299): metrics_dict = json.loads(resp.text) logger.debug('%s', metrics_dict) return metrics_dict else: logger.debug('Error in getting %s metric for name : %s' % (entity_type, name)) def upload_ssl_certs(self, ssl_cert_name, ssl_cert_file_path=''): ''' ''' cert, key, _, _ = get_sample_ssl_params() # upload the key and cert to the controller with name ssl_cert_name resp = self.api_utils.import_ssl_certificate(ssl_cert_name, key, cert) if resp.status_code not in xrange(200, 299): print 'Error in uploading certs : %s' % resp.text exit(0) ssl_kc_ref = self.api.get_obj_ref(resp) return ssl_kc_ref def get_server_obj(self, servers): ''' ''' servers_obj = [] for server in servers: parts = server.split(':') ip_addr = parts[0] port = parts[1] if len(parts) == 2 else 80 servers_obj.append({ 'ip': { 'addr': ip_addr, 'type': 'V4' }, 'port': port }) return servers_obj def create_pool(self, name, servers_obj, monitor_names=None, lb_algorithm='LB_ALGORITHM_LEAST_CONNECTIONS'): health_monitors = None if monitor_names: health_monitors = [] for monitor_name in monitor_names: health_monitor_tcp = self.api.get_object_by_name( 'healthmonitor', monitor_name) health_monitors.append( self.api.get_obj_ref(health_monitor_tcp)) print health_monitors pool_name = name pool_obj = { "lb_algorithm": lb_algorithm, "default_server_port": 80, "name": pool_name, "servers": servers_obj, 'health_monitor_refs': health_monitors } resp = self.api.post('pool', data=json.dumps(pool_obj)) if resp.status_code in xrange(200, 299): return resp else: print 'Error in creating pool :%s' % resp.text exit(0) def update_password(self, resource_name, new_val): obj = self.api.get_object_by_name('user', resource_name) if not obj: resp = self.api.get('user?username=%s' % resource_name) if resp.status_code < 300: resp_json = json.loads(resp.text) if resp_json['count'] > 0: obj = json.loads(resp.text)['results'][0] if not obj: logger.error('User not found with user name : %s' % resource_name) exit(0) obj['password'] = new_val resp = self.api.put('user/%s' % obj['uuid'], data=obj) if resp.status_code in xrange(200, 299): logger.debug('User %s updated successfully' % resource_name) else: logger.error('Error updating user : %s' % resp.text) def add_security_policy(self, vs_name, ips): """ Example to add network security rule to existing VS """ ip_list = ips.split(',') addrs = [] for ip in ip_list: addrs.append({"type": "V4", "addr": ip}) rand_int = random.randint(0, 100) ipaddrgroup = { "name": '%s-Rule-%s-grp' % (vs_name, rand_int), "addrs": addrs } resp = self.api.post('ipaddrgroup', data=ipaddrgroup) if resp.status_code > 300: logger.error('Error creating ipaddrgroup : %s' % resp.text) exit(0) ip_grp_ref = self.api.get_obj_ref(resp) policy_name = '%s-policy-%s' % (vs_name, rand_int) policy = { "name": policy_name, "rules": [{ "name": '%s-Rule-%s' % (vs_name, rand_int), "index": rand_int, "enable": True, "action": "NETWORK_SECURITY_POLICY_ACTION_TYPE_DENY", "match": { "client_ip": { "group_refs": [ip_grp_ref], "match_criteria": "IS_IN" } }, }] } resp = self.api.post('networksecuritypolicy', data=policy) if resp.status_code > 300: logger.error('Error creating networksecuritypolicy: %s' % resp.text) exit(0) policy_ref = self.api.get_obj_ref(resp) obj = self.api.get_object_by_name('virtualservice', vs_name) if not obj: logger.error('VS not found with name : %s' % vs_name) exit(0) obj['network_security_policy_ref'] = policy_ref resp = self.api.put('virtualservice/%s' % obj['uuid'], data=obj) if resp.status_code > 300: logger.error('Error updating vs for networksecuritypolicy: %s' % resp.text) exit(0) logger.debug("Network security policy %s added to VS %s" % (policy_name, vs_name)) def edit_ip_group(self, ip_grp_name, ips): """ Example to edit ip-group with new set of ips """ obj = self.api.get_object_by_name('ipaddrgroup', ip_grp_name) if not obj: logger.error('ip-group not found with name : %s' % vs_name) exit(0) ip_list = ips.split(',') addrs = [] for ip in ip_list: addrs.append({"type": "V4", "addr": ip}) obj['addrs'] = addrs resp = self.api.put('ipaddrgroup/%s' % obj['uuid'], data=obj) if resp.status_code > 300: logger.error('Error in updating ip-group : %s' % resp.text) else: logger.error('ip-group %s updated successfully' % ip_grp_name) def clone_vs(self, vs_name, new_vip): """ Clones the VS and pool and assigns it a new VIP. It only changes the default pool and does not clone the pools referred in the rules. :param vs_name: name of the vs :param new_vip: new vip to be given to the vs """ # get the VS object v_obj = self.api.get_object_by_name('virtualservice', vs_name) if not v_obj: raise Exception('vs %s not found' % (vs_name)) # get the pool for this vs p_path = v_obj['pool_ref'].split('/api/')[1] # get the pool object p_obj = self.api.get(p_path).json() #create new pool del p_obj['uuid'] del p_obj['url'] del p_obj['tenant_ref'] del p_obj['cloud_ref'] p_obj.pop('vrf_ref', None) # change name p_obj['name'] = p_obj['name'] + '-clone' r = self.api.post('pool', p_obj) if r.status_code < 300: new_pool = r.json() print 'new pool ', new_pool else: raise Exception('pool %s not created %d' % (p_obj['name'], r.status_code)) # create VS with this new pool del v_obj['uuid'] del v_obj['url'] del v_obj['tenant_ref'] del v_obj['cloud_ref'] v_obj.pop('fqdn', None) v_obj.pop('vrf_context_ref', None) v_obj['name'] = v_obj['name'] + '-clone' v_obj['pool_ref'] = new_pool['url'] v_obj['ip_address']['addr'] = new_vip r = self.api.post('virtualservice', v_obj) if r.status_code < 299: print 'new_vs created ', r.json()
def __init__(self, api_session): self.api_session = api_session self.api_util = ApiUtils(api_session)
def __init__(self, api): self.api = api self.api_utils = ApiUtils(api)
class VirtualServiceExample(object): ''' Provides example of following operations 1. Create basic vs 2. Create vs with SSL objects 3. Create vs with custom parameters like application profile 4. Inventory API calls for virtualservice 5. Metrics API calls for virtualservice metrics ''' def __init__(self, api): self.api = api self.api_utils = ApiUtils(api) def create_basic_vs(self, vs_name, vip, servers=None): # first create pool for virtual service servers_obj = self.get_server_obj(servers) pool_name = vs_name + '-pool' pool_obj = self.create_pool(pool_name, servers_obj) pool_ref = self.api.get_obj_ref(pool_obj) # create virtual service dict services_obj = [{'port': 80, 'enable_ssl': False}] vs_obj = { 'name': vs_name, 'type': 'VS_TYPE_NORMAL', 'ip_address': { 'addr': vip, 'type': 'V4' }, 'enabled': True, 'services': services_obj, 'application_profile_name': 'System-HTTP', 'pool_ref': pool_ref } # post VS data in json format to avi api resp = self.api.post('virtualservice', data=json.dumps(vs_obj)) if resp.status_code in range(200, 299): logger.debug('Virtual service created successfully %s' % vs_name) else: logger.debug('Error creating virtual service : %s' % resp.text) def create_ssl_vs(self, vs_name, vip, servers=None): # import certs. ssl_kc_name = vs_name + '-' + 'ssl-kc' ssl_key_and_cert_ref = [self.upload_ssl_certs(ssl_kc_name)] # turning on SSL profile services_obj = [{'port': 443, 'enable_ssl': True}] servers_obj = self.get_server_obj(servers) # create pool for virtual service pool_name = vs_name + '-pool' pool_obj = self.create_pool(pool_name, servers_obj) pool_ref = self.api.get_obj_ref(pool_obj) # create virtual service dict for ssl VS vs_obj = { 'name': vs_name, 'type': 'VS_TYPE_NORMAL', 'ip_address': { 'addr': vip, 'type': 'V4' }, 'enabled': True, 'services': services_obj, 'ssl_key_and_certificate_refs': ssl_key_and_cert_ref, 'ssl_profile_name': 'System-Standard', 'application_profile_name': 'System-Secure-HTTP', 'pool_ref': pool_ref } resp = self.api.post('virtualservice', data=json.dumps(vs_obj)) if resp.status_code >= 200 and resp.status_code < 300: logger.debug('Virtual service created successfully %s' % vs_name) else: raise Exception('error %s' % str(resp)) def create_custom_vs(self, vs_name, vip, servers=None): # import certs. ssl_kc_name = vs_name + '-' + 'ssl-kc' ssl_key_and_cert_ref = [self.upload_ssl_certs(ssl_kc_name)] # turning on SSL profile services_obj = [{'port': 443, 'enable_ssl': True}] # create custom pool with health monitors servers_obj = self.get_server_obj(servers) pool_name = vs_name + '-pool' pool_obj = self.create_pool( pool_name, servers_obj, ['System-TCP', 'System-HTTP', 'System-Ping']) pool_ref = self.api.get_obj_ref(pool_obj) # create virtual service dict for ssl VS vs_obj = { 'name': vs_name, 'type': 'VS_TYPE_NORMAL', 'ip_address': { 'addr': vip, 'type': 'V4' }, 'enabled': True, 'services': services_obj, 'ssl_key_and_certificate_refs': ssl_key_and_cert_ref, 'ssl_profile_name': 'System-Standard', 'application_profile_name': 'System-Secure-HTTP', 'pool_ref': pool_ref } resp = self.api.post('virtualservice', data=json.dumps(vs_obj)) if resp.status_code >= 200 and resp.status_code < 300: logger.debug('Virtual service created successfully %s' % vs_name) else: logger.debug('Error creating virtual service : %s' % resp.text) def create_policy_vs(self, vs_name, vip, servers=None): ''' This is example to create a custom vs with HTTP policies 1. creates a rewrite policy ''' # import certs. ssl_kc_name = vs_name + '-' + 'ssl-kc' ssl_key_and_cert_ref = [self.upload_ssl_certs(ssl_kc_name)] # turning on SSL profile services_obj = [{'port': 443, 'enable_ssl': True}] # create custom pool with health monitors servers_obj = self.get_server_obj(servers) pool_name = vs_name + '-pool' pool_obj = self.create_pool( pool_name, servers_obj, ['System-TCP', 'System-HTTP', 'System-Ping']) pool_ref = self.api.get_obj_ref(pool_obj) # create virtual service dict for ssl VS vs_obj = { 'name': vs_name, 'type': 'VS_TYPE_NORMAL', 'ip_address': { 'addr': vip, 'type': 'V4' }, 'enabled': True, 'services': services_obj, 'ssl_key_and_certificate_refs': ssl_key_and_cert_ref, 'ssl_profile_name': 'System-Standard', 'application_profile_name': 'System-Secure-HTTP', 'pool_ref': pool_ref } resp = self.api.post('virtualservice', data=json.dumps(vs_obj)) if resp.status_code >= 200 and resp.status_code < 300: logger.debug('Virtual service created successfully %s' % vs_name) else: logger.debug('Error creating virtual service : %s' % resp.text) def get_inventory(self, inventory_type='virtualservice-inventory', obj_uuid='', params=None): params = {} if not params else params if 'page' not in params: params['page'] = 1 if 'page_size' not in params: params['page_size'] = 10 inventory_path = inventory_type if obj_uuid: # this is case of inventory for a specific object inventory_path = inventory_path + '/' + obj_uuid resp = self.api.get(inventory_path, params=params) if resp.status_code in range(200, 299): return json.loads(resp.text) else: return 'Error in getting inventory for %s, Error :%s' % ( inventory_type, resp.text) def delete(self, name, entity_type): resp = self.api.delete_by_name(entity_type, name) if resp.status_code in range(200, 299): print('%s name: %s deleted successfully' % (entity_type, name)) else: print('Error in deleting virtual service :%s' % resp.text) def get_metrics(self, name, metric_id, entity_type='virtualservice'): resp = self.api.get_object_by_name(entity_type, name) uuid = self.api.get_obj_uuid(resp) path = 'analytics/metrics/%s/%s/?metric_id=%s&step=300&limit=12' % ( entity_type, uuid, metric_id) resp = self.api.get(path) if resp.status_code in range(200, 299): metrics_dict = json.loads(resp.text) logger.debug('%s', metrics_dict) return metrics_dict else: logger.debug('Error in getting %s metric for name : %s' % ( entity_type, name)) def upload_ssl_certs(self, ssl_cert_name, ssl_cert_file_path=''): ''' ''' cert, key, _, _ = get_sample_ssl_params() # upload the key and cert to the controller with name ssl_cert_name resp = self.api_utils.import_ssl_certificate(ssl_cert_name, key, cert) if resp.status_code not in range(200, 299): print('Error in uploading certs : %s' % resp.text) exit(0) ssl_kc_ref = self.api.get_obj_ref(resp) return ssl_kc_ref def get_server_obj(self, servers): ''' ''' servers_obj = [] for server in servers: parts = server.split(':') ip_addr = parts[0] port = parts[1] if len(parts) == 2 else 80 servers_obj.append({ 'ip': { 'addr': ip_addr, 'type': 'V4' }, 'port': port }) return servers_obj def create_pool(self, name, servers_obj, monitor_names=None, lb_algorithm='LB_ALGORITHM_LEAST_CONNECTIONS'): health_monitors = None if monitor_names: health_monitors = [] for monitor_name in monitor_names: health_monitor_tcp = self.api.get_object_by_name('healthmonitor', monitor_name) health_monitors.append(self.api.get_obj_ref(health_monitor_tcp)) print(health_monitors) pool_name = name pool_obj = { "lb_algorithm": lb_algorithm, "default_server_port": 80, "name": pool_name, "servers": servers_obj, 'health_monitor_refs': health_monitors } resp = self.api.post('pool', data=json.dumps(pool_obj)) if resp.status_code in range(200, 299): return resp else: print('Error in creating pool :%s' % resp.text) exit(0) def update_password(self, resource_name, new_val): obj = self.api.get_object_by_name('user', resource_name) if not obj: resp = self.api.get('user?username=%s' % resource_name) if resp.status_code < 300: resp_json = json.loads(resp.text) if resp_json['count'] > 0: obj = json.loads(resp.text)['results'][0] if not obj: logger.error('User not found with user name : %s' % resource_name) exit(0) obj['password'] = new_val resp = self.api.put('user/%s' % obj['uuid'], data=obj) if resp.status_code in range(200, 299): logger.debug('User %s updated successfully' % resource_name) else: logger.error('Error updating user : %s' % resp.text) def add_security_policy(self, vs_name, ips): """ Example to add network security rule to existing VS """ ip_list = ips.split(',') addrs = [] for ip in ip_list: addrs.append({ "type": "V4", "addr": ip }) rand_int = random.randint(0, 100) ipaddrgroup = { "name": '%s-Rule-%s-grp' % (vs_name, rand_int), "addrs":addrs } resp = self.api.post('ipaddrgroup', data=ipaddrgroup) if resp.status_code > 300: logger.error('Error creating ipaddrgroup : %s' % resp.text) exit(0) ip_grp_ref = self.api.get_obj_ref(resp) policy_name = '%s-policy-%s' % (vs_name, rand_int) policy = { "name": policy_name, "rules": [ { "name": '%s-Rule-%s' % (vs_name, rand_int), "index": rand_int, "enable": True, "action": "NETWORK_SECURITY_POLICY_ACTION_TYPE_DENY", "match": { "client_ip": { "group_refs": [ip_grp_ref], "match_criteria": "IS_IN" } }, } ] } resp = self.api.post('networksecuritypolicy', data=policy) if resp.status_code > 300: logger.error('Error creating networksecuritypolicy: %s' % resp.text) exit(0) policy_ref = self.api.get_obj_ref(resp) obj = self.api.get_object_by_name('virtualservice', vs_name) if not obj: logger.error('VS not found with name : %s' % vs_name) exit(0) obj['network_security_policy_ref'] = policy_ref resp = self.api.put('virtualservice/%s' % obj['uuid'], data=obj) if resp.status_code > 300: logger.error('Error updating vs for networksecuritypolicy: %s' % resp.text) exit(0) logger.debug("Network security policy %s added to VS %s" % (policy_name, vs_name)) def edit_ip_group(self, ip_grp_name, ips): """ Example to edit ip-group with new set of ips """ obj = self.api.get_object_by_name('ipaddrgroup', ip_grp_name) if not obj: logger.error('ip-group not found with name : %s' % vs_name) exit(0) ip_list = ips.split(',') addrs = [] for ip in ip_list: addrs.append({ "type": "V4", "addr": ip }) obj['addrs'] = addrs resp = self.api.put('ipaddrgroup/%s' % obj['uuid'], data=obj) if resp.status_code > 300: logger.error('Error in updating ip-group : %s' % resp.text) else: logger.error('ip-group %s updated successfully' % ip_grp_name) def clone_vs(self, vs_name, new_vip): """ Clones the VS and pool and assigns it a new VIP. It only changes the default pool and does not clone the pools referred in the rules. :param vs_name: name of the vs :param new_vip: new vip to be given to the vs """ # get the VS object v_obj = self.api.get_object_by_name('virtualservice', vs_name) if not v_obj: raise Exception('vs %s not found' % (vs_name)) # get the pool for this vs p_path = v_obj['pool_ref'].split('/api/')[1] # get the pool object p_obj = self.api.get(p_path).json() #create new pool del p_obj['uuid'] del p_obj['url'] del p_obj['tenant_ref'] del p_obj['cloud_ref'] p_obj.pop('vrf_ref', None) # change name p_obj['name'] = p_obj['name'] + '-clone' r = self.api.post('pool', p_obj) if r.status_code < 300: new_pool = r.json() print('new pool ', new_pool) else: raise Exception('pool %s not created %d' % (p_obj['name'], r.status_code)) # create VS with this new pool del v_obj['uuid'] del v_obj['url'] del v_obj['tenant_ref'] del v_obj['cloud_ref'] v_obj.pop('fqdn', None) v_obj.pop('vrf_context_ref', None) v_obj['name'] = v_obj['name'] + '-clone' v_obj['pool_ref'] = new_pool['url'] v_obj['ip_address']['addr'] = new_vip r = self.api.post('virtualservice', v_obj) if r.status_code < 299: print('new_vs created ', r.json())
ca_key = f.read() with open('../certs/cacert.pem') as f: ca_cert = f.read() # Read the tenant config from apic/apic_tenant_config.json load_tenant_config() # Establish session with the Avi Controller in 'admin' tenant for # configuration try: admin_session = create_avi_endpoint(tenant='admin') except Exception: print('login failed to Avi Controller!') sys.exit(0) ApiUtils(admin_session).import_ssl_certificate('MyCert', server_key, server_crt) create_pki_profile(admin_session, 'MyPKIProfile', certs=[ca_cert]) create_application_profile(admin_session, 'MyAppProfile', 'MyPKIProfile') # Establish session with the APIC apic_config = get_avi_apic_config() apic_session = APICClient(apic_config['ip'], apic_config['username'], apic_config['password']) create_apic_topology() print('------------------------------------------------------') print('Creating objects in Avi for Tenant %s' % (tenant_config['Tenant'])) print('------------------------------------------------------') avi_tenant_session = create_avi_endpoint(tenant=tenant_config['Tenant']) # Create Ip Address Group if present create_avi_ipaddrgroup(avi_tenant_session)
help='number of values', type=int, default=2) parser.add_argument('-c', '--controller', help='controller ip', default='127.0.0.1') parser.add_argument('-u', '--username', help='user name', default='admin') parser.add_argument('-p', '--password', help='password', default='abc') args = parser.parse_args() print('parsed args', args) mq = { 'metric_id': args.vs_metrics, 'serviceengine_uuid': args.se_uuid, 'tenant': (args.tenant if args.tenant else 'admin'), 'step': args.step, 'limit': args.limit, 'aggregate_entity': not args.per_vs_metrics, 'entity_uuid': '*', 'pad_missing_data': False } api_ssn = ApiSession(args.controller, args.username, args.password, args.tenant) api_utils = ApiUtils(api_ssn) rsp = api_utils.get_metrics_collection(tenant=args.tenant, metric_requests=[mq]) print ('metrics query', mq) print (json.dumps(rsp, indent=2))
class VirtualServiceExample(object): ''' Provides example of following operations 1. Create basic vs 2. Create vs with SSL objects 3. Create vs with custom parameters like application profile 4. Inventory API calls for virtualservice 5. Metrics API calls for virtualservice metrics ''' def __init__(self, api): self.api = api self.api_utils = ApiUtils(api) def create_basic_vs(self, vs_name, vip, servers=None): # first create pool for virtual service servers_obj = self.get_server_obj(servers) pool_name = vs_name + '-pool' pool_obj = self.create_pool(pool_name, servers_obj) pool_ref = self.api.get_obj_ref(pool_obj) # create virtual service dict services_obj = [{'port': 80, 'enable_ssl': False}] vs_obj = { 'name': vs_name, 'type': 'VS_TYPE_NORMAL', 'ip_address': { 'addr': vip, 'type': 'V4' }, 'enabled': True, 'services': services_obj, 'application_profile_name': 'System-HTTP', 'pool_ref': pool_ref } # post VS data in json format to avi api resp = self.api.post('virtualservice', data=json.dumps(vs_obj)) if resp.status_code in xrange(200, 299): logger.debug('Virtual service created successfully %s' % vs_name) else: logger.debug('Error creating virtual service : %s' % resp.text) def create_ssl_vs(self, vs_name, vip, servers=None): # import certs. ssl_kc_name = vs_name + '-' + 'ssl-kc' ssl_key_and_cert_ref = [self.upload_ssl_certs(ssl_kc_name)] # turning on SSL profile services_obj = [{'port': 443, 'enable_ssl': True}] servers_obj = self.get_server_obj(servers) # create pool for virtual service pool_name = vs_name + '-pool' pool_obj = self.create_pool(pool_name, servers_obj) pool_ref = self.api.get_obj_ref(pool_obj) # create virtual service dict for ssl VS vs_obj = { 'name': vs_name, 'type': 'VS_TYPE_NORMAL', 'ip_address': { 'addr': vip, 'type': 'V4' }, 'enabled': True, 'services': services_obj, 'ssl_key_and_certificate_refs': ssl_key_and_cert_ref, 'ssl_profile_name': 'System-Standard', 'application_profile_name': 'System-Secure-HTTP', 'pool_ref': pool_ref } resp = self.api.post('virtualservice', data=json.dumps(vs_obj)) if resp.status_code >= 200 and resp.status_code < 300: logger.debug('Virtual service created successfully %s' % vs_name) else: raise Exception('error %s' % str(resp)) def create_custom_vs(self, vs_name, vip, servers=None): # import certs. ssl_kc_name = vs_name + '-' + 'ssl-kc' ssl_key_and_cert_ref = [self.upload_ssl_certs(ssl_kc_name)] # turning on SSL profile services_obj = [{'port': 443, 'enable_ssl': True}] # create custom pool with health monitors servers_obj = self.get_server_obj(servers) pool_name = vs_name + '-pool' pool_obj = self.create_pool( pool_name, servers_obj, ['System-TCP', 'System-HTTP', 'System-Ping']) pool_ref = self.api.get_obj_ref(pool_obj) # create virtual service dict for ssl VS vs_obj = { 'name': vs_name, 'type': 'VS_TYPE_NORMAL', 'ip_address': { 'addr': vip, 'type': 'V4' }, 'enabled': True, 'services': services_obj, 'ssl_key_and_certificate_refs': ssl_key_and_cert_ref, 'ssl_profile_name': 'System-Standard', 'application_profile_name': 'System-Secure-HTTP', 'pool_ref': pool_ref } resp = self.api.post('virtualservice', data=json.dumps(vs_obj)) if resp.status_code >= 200 and resp.status_code < 300: logger.debug('Virtual service created successfully %s' % vs_name) else: logger.debug('Error creating virtual service : %s' % resp.text) def create_policy_vs(self, vs_name, vip, servers=None): ''' This is example to create a custom vs with HTTP policies 1. creates a rewrite policy ''' # import certs. ssl_kc_name = vs_name + '-' + 'ssl-kc' ssl_key_and_cert_ref = [self.upload_ssl_certs(ssl_kc_name)] # turning on SSL profile services_obj = [{'port': 443, 'enable_ssl': True}] # create custom pool with health monitors servers_obj = self.get_server_obj(servers) pool_name = vs_name + '-pool' pool_obj = self.create_pool( pool_name, servers_obj, ['System-TCP', 'System-HTTP', 'System-Ping']) pool_ref = self.api.get_obj_ref(pool_obj) # create virtual service dict for ssl VS vs_obj = { 'name': vs_name, 'type': 'VS_TYPE_NORMAL', 'ip_address': { 'addr': vip, 'type': 'V4' }, 'enabled': True, 'services': services_obj, 'ssl_key_and_certificate_refs': ssl_key_and_cert_ref, 'ssl_profile_name': 'System-Standard', 'application_profile_name': 'System-Secure-HTTP', 'pool_ref': pool_ref } resp = self.api.post('virtualservice', data=json.dumps(vs_obj)) if resp.status_code >= 200 and resp.status_code < 300: logger.debug('Virtual service created successfully %s' % vs_name) else: logger.debug('Error creating virtual service : %s' % resp.text) def get_inventory(self, inventory_type='virtualservice-inventory', obj_uuid='', params=None): params = {} if not params else params if 'page' not in params: params['page'] = 1 if 'page_size' not in params: params['page_size'] = 10 inventory_path = inventory_type if obj_uuid: # this is case of inventory for a specific object inventory_path = inventory_path + '/' + obj_uuid resp = self.api.get(inventory_path, params=params) if resp.status_code in xrange(200, 299): return json.loads(resp.text) else: return 'Error in getting inventory for %s, Error :%s' % ( inventory_type, resp.text) def delete(self, name, entity_type): resp = self.api.delete_by_name(entity_type, name) if resp.status_code in xrange(200, 299): print '%s name: %s deleted successfully' % (entity_type, name) else: print 'Error in deleting virtual service :%s' % resp.text def get_metrics(self, name, metric_id, entity_type='virtualservice'): resp = self.api.get_object_by_name(entity_type, name) uuid = self.api.get_obj_uuid(resp) path = 'analytics/metrics/%s/%s/?metric_id=%s&step=300&limit=12' % ( entity_type, uuid, metric_id) resp = self.api.get(path) if resp.status_code in xrange(200, 299): metrics_dict = json.loads(resp.text) logger.debug('%s', metrics_dict) return metrics_dict else: logger.debug('Error in getting %s metric for name : %s' % (entity_type, name)) def upload_ssl_certs(self, ssl_cert_name, ssl_cert_file_path=''): ''' ''' cert, key, _, _ = get_sample_ssl_params() # upload the key and cert to the controller with name ssl_cert_name resp = self.api_utils.import_ssl_certificate(ssl_cert_name, key, cert) if resp.status_code not in xrange(200, 299): print 'Error in uploading certs : %s' % resp.text exit(0) ssl_kc_ref = self.api.get_obj_ref(resp) return ssl_kc_ref def get_server_obj(self, servers): ''' ''' servers_obj = [] for server in servers: parts = server.split(':') ip_addr = parts[0] port = parts[1] if len(parts) == 2 else 80 servers_obj.append({ 'ip': { 'addr': ip_addr, 'type': 'V4' }, 'port': port }) return servers_obj def create_pool(self, name, servers_obj, monitor_names=None, lb_algorithm='LB_ALGORITHM_LEAST_CONNECTIONS'): health_monitors = None if monitor_names: health_monitors = [] for monitor_name in monitor_names: health_monitor_tcp = self.api.get_object_by_name( 'healthmonitor', monitor_name) health_monitors.append( self.api.get_obj_ref(health_monitor_tcp)) print health_monitors pool_name = name pool_obj = { "lb_algorithm": lb_algorithm, "default_server_port": 80, "name": pool_name, "servers": servers_obj, 'health_monitor_refs': health_monitors } resp = self.api.post('pool', data=json.dumps(pool_obj)) if resp.status_code in xrange(200, 299): return resp else: print 'Error in creating pool :%s' % resp.text exit(0)