Пример #1
0
 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
Пример #2
0
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
Пример #3
0
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)
Пример #4
0
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
Пример #5
0
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)
Пример #6
0
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
Пример #7
0
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
Пример #8
0
 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
Пример #9
0
 def test_session_reset(self):
     papi = ApiSession(api.controller_ip, api.username, api.password,
                       verify=False, api_version=api.api_version)
     res = papi.get('pool', params={'fields': 'name'})
     assert res.status_code == 200
     papi.reset_session()
     res = papi.get('pool', params={'fields': 'name'})
     assert res.status_code == 200
     data = {'name': 'test-reset'}
     res = papi.post('pool', data=data)
     assert res.status_code == 201
     papi.reset_session()
     res = papi.delete_by_name('pool', 'test-reset')
     assert res.status_code == 204
Пример #10
0
 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)
Пример #11
0
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
Пример #12
0
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)
Пример #13
0
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
Пример #14
0
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)
Пример #15
0
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
Пример #16
0
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)
Пример #17
0
 def test_multiple_tenants(self):
     """
     Tests api with multiple tenants to make sure object is only returned
     for the right tenant.
     """
     tobj = {'name': 'test-tenant'}
     resp = api.post('tenant', data=tobj)
     assert resp.status_code in (200, 201)
     tapi = ApiSession(api.controller_ip, api.username, api.password,
                       tenant=tobj['name'], verify=False)
     t_obj = tapi.get_object_by_name('tenant', tobj['name'])
     # created pool.
     log.info('tenant %s', t_obj)
     basic_vs_cfg = gSAMPLE_CONFIG["BasicVS"]
     pool_cfg = copy.deepcopy(basic_vs_cfg["pool_obj"])
     pool_cfg['name'] = pool_cfg['name'] + '-test-tenant'
     resp = tapi.post('pool', data=pool_cfg)
     assert resp.status_code in (200, 201)
     # check pool was not created in tenant admin
     pname = pool_cfg['name']
     resp = api.get_object_by_name('pool', pname)
     assert resp is None
     resp = tapi.get_object_by_name('pool', pname)
     assert resp
     resp = api.get_object_by_name('pool', pname, tenant_uuid=t_obj['uuid'])
     assert resp
     resp = api.get_object_by_name('pool', pname, tenant='test-tenant')
     assert resp
     resp = tapi.delete_by_name("pool", pname)
     assert resp.status_code in (200, 204)
     resp = api.get_object_by_name('pool', pname, tenant='test-tenant')
     assert resp is None
     resp = tapi.delete_by_name('tenant', 'test-tenant', tenant='admin')
     assert resp.status_code in (200, 204)
Пример #18
0
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
Пример #19
0
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)
Пример #20
0
 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
Пример #21
0
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)
Пример #22
0
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)
Пример #23
0
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))
Пример #24
0
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)
Пример #25
0
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)
Пример #26
0
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)
Пример #27
0
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))
Пример #28
0
    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
Пример #29
0
    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
Пример #30
0
 def getObject(self, objectUrl, objectParams):
     api = ApiSession.get_session(self.fqdn, self.username, self.password,
                                  self.tenant)
     result = api.get(objectUrl, params=objectParams)
     return result.json()
Пример #31
0
    def create_cloud(self, ctrlr_inst_info, se_inst_info, ssh_user,
                     ssh_pub_key, ssh_priv_key):
        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)

        resp = avi_api.get('seproperties')
        if resp.status_code != 200:
            self.log.warn('Error getting seproperties %d' % resp.status_code)
            return
        se_prop_obj = json.loads(resp.text)
        se_prop_obj['se_runtime_properties'][
            'se_handle_interface_routes'] = True
        se_prop_obj['se_runtime_properties']['global_mtu'] = 1400
        put_rsp = avi_api.put('seproperties/%s' % se_prop_obj['uuid'],
                              data=se_prop_obj)
        self.log.info('Updated seproperties obj status %d %s' %
                      (put_rsp.status_code, put_rsp.text))

        net_obj_name = ctrlr_inst_info.get('network', 'perf-network')
        net_obj = avi_api.get_object_by_name('network', net_obj_name)
        if not net_obj:
            ipam_subnet = ctrlr_inst_info['ipam_subnet'].split('/')
            prefix = ipam_subnet[0]
            mask = ipam_subnet[1]
            net_obj = {
                'name':
                net_obj_name,
                'configured_subnets': [{
                    'prefix': {
                        'ip_addr': {
                            'addr': prefix,
                            'type': 'V4'
                        },
                        'mask': mask
                    },
                    'static_ranges': [{
                        'begin': {
                            'addr': ctrlr_inst_info['ipam_start'],
                            'type': 'V4'
                        },
                        'end': {
                            'addr': ctrlr_inst_info['ipam_start'],
                            'type': 'V4'
                        }
                    }]
                }]
            }
            resp = avi_api.post('network', data=net_obj)
            self.log.info('Created network %s rsp %s' % (net_obj, resp.text))
            if resp.status_code >= 300:
                self.log.warn('Error creating network obj %s' %
                              resp.status_code)
                return
            net_obj = avi_api.get_object_by_name('network', net_obj_name)

        ipam_obj_name = ctrlr_inst_info.get('ipamdnsproviderprofile',
                                            'perf-ipam')
        ipam_obj = avi_api.get_object_by_name('ipamdnsproviderprofile',
                                              ipam_obj_name)
        if not ipam_obj:
            ipam_obj = {
                'name': ipam_obj_name,
                'type': 'IPAMDNS_TYPE_GCP',
                'gcp_profile': {
                    'usable_network_refs': [net_obj['url']]
                }
            }
            resp = avi_api.post('ipamdnsproviderprofile', data=ipam_obj)
            self.log.info('Created GCP IPAM %s rsp %s' % (ipam_obj, resp.text))
            if resp.status_code >= 300:
                self.log.warn('Error creating ipam obj %s' % resp.status_code)
                return
            ipam_obj = avi_api.get_object_by_name('ipamdnsproviderprofile',
                                                  ipam_obj_name)

        cc_user = avi_api.get_object_by_name('cloudconnectoruser', ssh_user)
        if not cc_user:
            cc_user = self._create_cc_user(avi_api, ssh_user, ssh_pub_key,
                                           ssh_priv_key)
            if not cc_user:
                return

        cloud = ctrlr_inst_info.get('cloud', 'Default-Cloud')
        cloud_obj = avi_api.get_object_by_name('cloud', cloud)
        if not cloud_obj:
            cloud_obj = {
                'vtype': 'CLOUD_LINUXSERVER',
                'ipam_provider_ref': ipam_obj['url'],
                'linuxserver_configuration': {
                    'ssh_attr': {
                        'ssh_user': ssh_user
                    }
                }
            }
            resp = avi_api.post('cloud', data=cloud_obj)
            self.log.info('Created cloud %s rsp %s' % (cloud_obj, resp.text))
            if resp.status_code >= 300:
                self.log.warn('Error creating cloud obj %s' % resp.status_code)
                return
        else:
            cloud_obj['vtype'] = 'CLOUD_LINUXSERVER'
            cloud_obj['ipam_provider_ref'] = ipam_obj['url']
            if 'linuxserver_configuration' not in cloud_obj:
                cloud_obj['linuxserver_configuration'] = {}
            cloud_obj['linuxserver_configuration']['ssh_attr'] = \
                    {'ssh_user': ssh_user}
            put_rsp = avi_api.put('cloud/%s' % cloud_obj['uuid'],
                                  data=cloud_obj)
            self.log.info('Updated Cloud obj status %d %s' %
                          (put_rsp.status_code, put_rsp.text))

        seg_objs_rsp = avi_api.get('serviceenginegroup')
        seg_objs = json.loads(seg_objs_rsp.text)
        seg_obj = next((seg for seg in seg_objs['results']
                        if cloud_obj['uuid'] in seg['cloud_ref']), None)
        if not seg_obj:
            self.log.warn('Unable to find SEGroup obj for cloud %s',
                          cloud_obj['uuid'])
            return
        seg_obj['min_scaleout_per_vs'] = se_inst_info['instances']
        seg_obj['max_scaleout_per_vs'] = se_inst_info['instances']
        seg_obj['dedicated_dispatcher_core'] = True
        put_rsp = avi_api.put('serviceenginegroup/%s' % seg_obj['uuid'],
                              data=seg_obj)
        self.log.info('Updated SEGroup obj status %d %s' %
                      (put_rsp.status_code, put_rsp.text))
Пример #32
0
    def test_user_login(self):
        api1 = ApiSession(controller_ip=login_info.get('controller_ip'),
            username=login_info.get('username'),
            password=login_info.get('password'),
            lazy_authentication=False)
        user_info = gSAMPLE_CONFIG["Passwords"]
        original_password = login_info.get('password')
        new_password = "******"
        user_info['password'] = new_password
        user_info['old_password'] = original_password
        res = api1.put('useraccount', data=json.dumps(user_info))
        assert res.status_code == 200
        api1.clear_cached_sessions()

        api2 = ApiSession(controller_ip=login_info.get('controller_ip'),
                          username=login_info.get('username'),
                          password=new_password,
                          lazy_authentication=False)
        res = api2.get('pool')
        assert res.status_code in [200, 204]
        old_password = user_info['password']
        changed_password = original_password
        user_info['password'] = original_password
        user_info['old_password'] = old_password
        result = api2.put('useraccount', user_info)
        assert result.status_code == 200
        res = api2.get('pool')
        assert res.status_code in [200, 204]
        api2.clear_cached_sessions()

        api3 = ApiSession(controller_ip=login_info.get('controller_ip'),
                          username=login_info.get('username'),
                          password=changed_password,
                          lazy_authentication=False)
        res = api3.get('pool')
        assert res.status_code in [200, 204]
Пример #33
0
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)
Пример #34
0
def main():
    """Module instantiation"""
    module = AnsibleModule(argument_spec=dict(ip_address=dict(required=True),
                                              request_type=dict(required=True),
                                              port=dict(required=True),
                                              vs_name=dict(required=True),
                                              controller=dict(required=True),
                                              username=dict(required=True),
                                              password=dict(required=True),
                                              tenant=dict()))

    if not HAS_REQUEST:
        module.fail_json(msg='Library not imported properly')

    # Accessing arguments
    uri = module.params.get("ip_address", None)
    request_type = module.params.get('request_type', None)
    port = module.params.get('port', None)
    virtualservice_name = module.params.get('vs_name', None)
    controller = module.params.get('controller', None)
    password = module.params.get('password', None)
    username = module.params.get('username', None)
    tenant = module.params.get('tenant', None)
    OBJECT_TYPE = 'virtualservice'
    try:
        # Creating Api session
        session = ApiSession.get_session(controller,
                                         username,
                                         password=password,
                                         tenant=tenant)
    except:
        module.exit_json(stderr='Virtualservice Session is not created',
                         changed=False,
                         success=1)
    # Get the vs parameter for getting vs state
    response = session.get_object_by_name(OBJECT_TYPE, virtualservice_name)
    if response:
        uuid = response['uuid']
        vs_up = False
        # If uuid the check the state of virtualservice
        if uuid:
            status_path = 'virtualservice-inventory/%s' % uuid
            for i in range(0, 10):
                # Check if virtualservice is up
                response = session.get(status_path)
                response = response.json()
                if 'OPER_UP' == response['runtime']['oper_status']['state']:
                    vs_up = True
                    break
                else:
                    time.sleep(0.2)
        # If virtualservice is up then send traffic
        if vs_up:
            # Send http get requests to generate traffic
            if request_type == 'http' or request_type == 'https':
                for i in range(0, 10):
                    try:
                        response = requests.get(request_type + '://' + uri +
                                                ':' + port,
                                                verify=False)
                    except:
                        module.fail_json(msg='Virtualservice is down')
                    if response.status_code >= 200 \
                            and response.status_code <= 299:
                        continue
                    else:
                        module.fail_json(msg='Virtualservice is down')
                        break
                if response.status_code >= 200 and \
                                response.status_code <= 299:
                    module.exit_json(
                        stdout='Virtualservice Traffic sent successfully',
                        changed=False,
                        success=0)
                else:
                    module.exit_json(stderr='Virtualservice is not reachable',
                                     changed=False,
                                     success=1)
            # Send tcp requests traffic if 0 then Success else False
            elif request_type == 'tcp':
                command = 'nc -w 2 %s %s' % (uri, port)
                cmd = shlex.split(command)
                out = call(cmd)
                if not out:
                    module.exit_json(
                        stderr='Tcp Traffic sent successfully',
                        changed=False,
                        success=0,
                    )
                else:
                    module.exit_json(stderr='Tcp Traffic failed',
                                     changed=False,
                                     success=1)
            # type dns then do the dns lookup
            elif request_type == 'dns':
                try:
                    ip = socket.gethostbyname('google.com')
                except:
                    module.fail_json(msg='Not valid dns')
                if ip:
                    module.exit_json(stderr='Dns Lookup successful %s' % ip,
                                     changed=False,
                                     success=0)
                else:
                    module.exit_json(stderr='Dns Lookup unsuccessful',
                                     changed=False,
                                     success=1)
        else:
            module.exit_json(stderr='Virtualservice is not UP',
                             changed=False,
                             success=1)
    else:
        module.exit_json(stderr='Virtualservice is not configured',
                         changed=False,
                         success=1)
Пример #35
0
 def postObject(self, objectUrl, objectData):
     api = ApiSession.get_session(self.fqdn, self.username, self.password,
                                  self.tenant)
     result = api.post(objectUrl, data=objectData)
     return result.json()
Пример #36
0
                        help='number of values',
                        type=int, default=168)
    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",
Пример #37
0
def main():
    argument_specs = dict(force_mode=dict(type='bool', default=True),
                          upload=dict(required=True, type='bool'),
                          path=dict(type='str', required=True),
                          file_path=dict(type='str', required=True),
                          params=dict(type='dict'),
                          timeout=dict(type='int', default=60))
    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.'))

    if not HAS_LIB:
        return module.fail_json(
            msg=
            'avi_api_fileservice, requests_toolbelt is required for this module'
        )

    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)

    tenant_uuid = api_creds.tenant_uuid
    tenant = api_creds.tenant
    timeout = int(module.params.get('timeout'))
    # path is a required argument
    path = 'fileservice/%s' % module.params.get('path', '')
    params = module.params.get('params', None)
    data = module.params.get('data', None)
    # Get the api_version from module.
    api_version = api_creds.api_version
    if data is not None:
        data = json.loads(data)
    upload = module.params['upload']
    file_path = module.params['file_path']
    force_mode = module.params['force_mode']

    if upload:
        if not os.path.exists(file_path):
            return module.fail_json('File not found : %s' % file_path)
        file_name = os.path.basename(file_path)
        #Handle special case of upgrade controller using .pkg file which will be uploaded to upgrade_pkgs directory
        if file_name.lower().endswith('.pkg'):
            uri = 'controller://upgrade_pkgs'
            path = 'fileservice/uploads'
        else:
            uri = 'controller://%s' % module.params.get('path',
                                                        '').split('?')[0]
        changed = False
        file_uri = 'fileservice?uri=%s' % uri
        rsp = api.post(file_uri,
                       tenant=tenant,
                       tenant_uuid=tenant_uuid,
                       timeout=timeout)
        with open(file_path, "rb") as f:
            f_data = {
                "file": (file_name, f, "application/octet-stream"),
                "uri": uri
            }
            m = MultipartEncoder(fields=f_data)
            headers = {'Content-Type': m.content_type}
            rsp = api.post(path, data=m, headers=headers, verify=False)
            if rsp.status_code > 300:
                return module.fail_json(msg='Fail to upload file: %s' %
                                        rsp.text)
            else:
                return module.exit_json(changed=True,
                                        msg="File uploaded successfully")

    elif not upload:
        # Removing existing file.
        if force_mode and os.path.exists(file_path):
            os.remove(file_path)
        rsp = api.get(path, params=params, stream=True)
        if rsp.status_code > 300:
            return module.fail_json(msg='Fail to download file: %s' % rsp.text)
        with open(file_path, 'wb') as f:
            for chunk in rsp.iter_content(chunk_size=1024):
                if chunk:
                    f.write(chunk)
        return module.exit_json(msg='File downloaded successfully',
                                changed=True)
Пример #38
0
def testbed_setup(testbed):
    print(f"Data for Testbed {testbed['name'].capitalize()}")
    print(f"Controller IP: {testbed['controller_ip']}")
    print(f"DVWA VIP: {testbed['vses']['DVWA']['vip_ip']}")
    print(f"DVWA FQDN: {testbed['vses']['DVWA']['vs_fqdn']}")
    print(f"Hackazon VIP: {testbed['vses']['Hackazon']['vip_ip']}")
    print(f"Hackazon FQDN: {testbed['vses']['Hackazon']['vs_fqdn']}")
    api = ApiSession.get_session(controller_ip=testbed['controller_ip'],
                                 username=testbed['controller_username'],
                                 password=testbed['controller_password'],
                                 tenant=testbed['tenant'],
                                 api_version=testbed['api_version'])

    for name, vs in testbed['vses'].items():
        print("Setting up Demo VS:" + name)
        pool_obj = {
            "lb_algorithm":
            'LB_ALGORITHM_LEAST_CONNECTIONS',
            "default_server_port":
            80,
            "name":
            vs['pool_name'],
            "servers": [{
                'ip': {
                    'addr': vs['pool_server_ip'],
                    'type': 'V4',
                },
                'port': vs['pool_server_port'],
            }],
            "health_monitor_refs": [],
        }

        resp = api.post('pool', data=json.dumps(pool_obj))
        print('- Create Pool', resp)

        get_pool_obj = api.get_object_by_name('pool', vs['pool_name'])
        pool_ref = api.get_obj_ref(get_pool_obj)

        get_waf_profile = api.get_object_by_name('wafprofile',
                                                 'System-WAF-Profile')
        get_waf_profile['name'] = vs['waf_profile_name']
        resp = api.post('wafprofile', get_waf_profile)
        print("- Create new WAF profile", resp)
        get_profile_obj = api.get_object_by_name('wafprofile',
                                                 vs['waf_profile_name'])
        profile = api.get_obj_ref(get_profile_obj)

        get_waf_obj = api.get_object_by_name('wafpolicy', 'System-WAF-Policy')
        get_waf_obj['name'] = vs['waf_policy_name']
        get_waf_obj['waf_profile_ref'] = profile

        resp = api.post('wafpolicy', get_waf_obj)
        print("- Create new WAF Policy", resp)
        get_waf_obj = api.get_object_by_name('wafpolicy',
                                             vs['waf_policy_name'])
        waf_ref = api.get_obj_ref(get_waf_obj)
        # print "WAF", waf_ref

        backupconf = api.get_object_by_name('backupconfiguration',
                                            'Backup-Configuration')
        backupconf['backup_passphrase'] = 'notpresenttoavoiderror'
        resp = api.put('backupconfiguration/%s' % backupconf['uuid'],
                       backupconf)
        # print("Change Backup Configuration defaults", resp.text)

        error_page_body = api.get_object_by_name('errorpagebody',
                                                 'Custom-Error-Page')
        error_page_body_ref = api.get_obj_ref(error_page_body)

        error_page_profile = {
            'error_pages': [{
                'enable': True,
                'error_page_body_ref': error_page_body_ref,
                'index': 0,
                'match': {
                    'match_criteria': 'IS_IN',
                    'status_codes': [403]
                }
            }],
            'name':
            vs['error_page_profile_name'],
        }

        resp = api.post('errorpageprofile', error_page_profile)
        print("- Create new Error Page Profile", resp)

        error_page_profile = api.get_object_by_name(
            'errorpageprofile', vs['error_page_profile_name'])
        error_page_profile_ref = api.get_obj_ref(error_page_profile)

        # Add Datascript for Request-ID response Header
        dsname = "Request-ID-Header-%s" % vs['waf_policy_name']
        dsobject = {
            "evt": "VS_DATASCRIPT_EVT_HTTP_RESP",
            "script": """r = avi.http.get_request_id()
                         if r == nil then
                           r = "none"
                         end
                         avi.http.add_header( "X-Request-Id", r )""",
            "name": dsname,
        }
        dssetname = "DS-SET-Request-ID-Header-%s" % vs['waf_policy_name']
        dssetobject = {
            'datascript': [
                dsobject,
            ],
            'name': dssetname
        }
        resp = api.post('vsdatascriptset', data=json.dumps(dssetobject))
        print("- Create new Response Data Script", resp)

        ds = api.get_object_by_name('vsdatascriptset', dssetname)
        ds_ref = api.get_obj_ref(ds)

        # Creating VS
        services_obj = [{
            'port': 80,
            'enable_ssl': False
        }, {
            'port': 443,
            'enable_ssl': True
        }]
        vs_obj = {
            'name': vs['vs_name'],
            'type': 'VS_TYPE_NORMAL',
            'vip': [{
                'ip_address': {
                    'addr': vs['vip_ip'],
                    'type': 'V4'
                },
            }],
            'dns_info': [{
                'fqdn': vs['vs_fqdn']
            }],
            'enabled': True,
            'services': services_obj,
            'application_profile_name': 'System-HTTP',
            'error_page_profile_ref': error_page_profile_ref,
            'pool_ref': pool_ref,
            'waf_policy_ref': waf_ref,
            'vs_datascripts': [{
                'index': 1,
                'vs_datascript_set_ref': ds_ref
            }],
            'analytics_policy': {
                'udf_log_throttle': 10,
                'full_client_logs': {
                    'duration': 0,
                    'throttle': 10,
                    'enabled': True
                },
                'metrics_realtime_update': {
                    'duration': 0,
                    'enabled': True
                },
                'significant_log_throttle': 10,
                'client_insights': 'NO_INSIGHTS',
                'all_headers': True
            }
        }

        resp = api.post('virtualservice', data=json.dumps(vs_obj))
        print("- Create VS with new WAF Policy", resp)  #, resp.text

    print('Setup done.')
Пример #39
0
                        type=int, default=3600)
    parser.add_argument('-l', '--limit',
                        help='number of values',
                        type=int, default=168)
    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')


    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 = '*'
    if args.vs_name != '*':
        vs_obj = api_ssn.get_object_by_name('virtualservice', args.vs_name)
        entity_uuid = vs_obj['uuid']

    mq = {
        'metric_id': (args.metrics if args.metrics else 'l4_client.avg_bandwidth,l4_client.avg_complete_conns,l7_client.avg_complete_responses,l7_client.sum_get_reqs, l7_client.sum_post_reqs'),
        'tenant': (args.tenant if args.tenant else 'admin'),
        'step': args.step,
        'limit': args.limit,
        'entity_uuid': entity_uuid,
        'pad_missing_data': False
    }
Пример #40
0
    def create_vs(self, ctrlr_inst_info, pool_inst_info, pool_prefix,
                  num_pool_instances):
        instances = self.list_instances(pool_inst_info)
        pool_instances = [
            i for i in instances if i['name'].startswith(pool_prefix)
        ]

        if len(pool_instances) < num_pool_instances:
            self.log.warn('Just %d instances running %d requested' %
                          (len(pool_instances), num_pool_instances))
            return
        pool_ips = {
            i['info']['networkInterfaces'][0]['networkIP']
            for i in pool_instances
        }

        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)

        ds_name = ctrlr_inst_info.get('datascript', 'perf-vs-datascript')
        ds_obj = avi_api.get_object_by_name('vsdatascriptset', ds_name)
        if not ds_obj:
            ds_obj = {
                'name':
                ds_name,
                'datascript': [{
                    'evt': 'VS_DATASCRIPT_EVT_HTTP_REQ',
                    'script': 'avi.http.response(200)'
                }]
            }
            resp = avi_api.post('vsdatascriptset', data=ds_obj)
            self.log.info('Created DataScript %s rsp %s' % (ds_obj, resp.text))
            if resp.status_code >= 300:
                self.log.warn('Error creating DataScript obj %s' %
                              resp.status_code)
                return
        else:
            ds_obj['name'] = ds_name
            ds_obj['datascript'] = [{'evt': 'VS_DATASCRIPT_EVT_HTTP_REQ', \
                'script': 'avi.http.response(200)'}]
            put_rsp = avi_api.put('vsdatascriptset/%s' % ds_obj['uuid'],
                                  data=ds_obj)
            self.log.info('Updated DataScript obj status %d %s' %
                          (put_rsp.status_code, put_rsp.text))
        ds_obj = avi_api.get_object_by_name('vsdatascriptset', ds_name)

        sslcert_name = ctrlr_inst_info.get('ssl_cert', None)
        if sslcert_name:
            sslcert = avi_api.get_object_by_name('sslkeyandcertificate',
                                                 sslcert_name)
            if not sslcert:
                self.log.warn('SSL cert %s not found', sslcert_name)
                return

        pool_name = pool_inst_info.get('name', 'perf-pool')
        pool_obj = avi_api.get_object_by_name('pool', pool_name)
        servers = [{'ip': {'type': 'V4', 'addr': i}, 'port': 80} \
                  for i in pool_ips]
        if not pool_obj:
            pool_obj = {'name': pool_name, 'servers': servers}
            resp = avi_api.post('pool', data=pool_obj)
            self.log.info('Created Pool %s rsp %s' % (pool_obj, resp.text))
            if resp.status_code >= 300:
                self.log.warn('Error creating Pool obj %s' % resp.status_code)
                return
        else:
            pool_obj['servers'] = servers
            put_rsp = avi_api.put('pool/%s' % pool_obj['uuid'], data=pool_obj)
            self.log.info('Updated pool obj status %d %s' %
                          (put_rsp.status_code, put_rsp.text))
        pool_obj = avi_api.get_object_by_name('pool', pool_name)

        vs_name = ctrlr_inst_info.get('virtualservice', 'perf-vs')
        vs_obj = avi_api.get_object_by_name('virtualservice', vs_name)
        if sslcert_name:
            service = {'port': ctrlr_inst_info['port'], 'enable_ssl': True}
        else:
            service = {'port': ctrlr_inst_info['port'], 'enable_ssl': False}
        analytics_policy = {
            'client_insights': 'NO_INSIGHTS',
            'metrics_realtime_update': {
                'duration': 0,
                'enabled': True
            },
            'full_client_logs': {
                'duration': 0,
                'enabled': False
            }
        }
        placement_subnet_l = ctrlr_inst_info['placement_subnet'].split('/')
        placement_subnet = {
            'ip_addr': {
                'addr': placement_subnet_l[0],
                'type': 'V4'
            },
            'mask': placement_subnet_l[1]
        }
        if not vs_obj:
            vs_obj = {
                'name':
                vs_name,
                'ip_address': {
                    'addr': ctrlr_inst_info['vip'],
                    'type': 'V4'
                },
                'services': [service],
                'analytics_policy':
                analytics_policy,
                'scaleout_ecmp':
                True,
                'vs_datascripts': [{
                    'index': 1,
                    'vs_datascript_set_ref': ds_obj['url']
                }],
                'pool_ref':
                pool_obj['url'],
                'subnet':
                placement_subnet,
                'ign_pool_net_reach':
                True
            }
            if sslcert_name:
                vs_obj['ssl_key_and_certificate_refs'] = [sslcert['url']]
            resp = avi_api.post('virtualservice', data=vs_obj)
            self.log.info('Created VirtualService %s rsp %s' %
                          (vs_obj, resp.text))
            if resp.status_code >= 300:
                self.log.warn('Error creating VirtualService obj %s' %
                              resp.status_code)
                return
        else:
            vs_obj['ip_address'] = {
                'addr': ctrlr_inst_info['vip'],
                'type': 'V4'
            }
            vs_obj['services'] = [service]
            vs_obj['analytics_policy'] = analytics_policy
            vs_obj['scaleout_ecmp'] = True
            vs_obj['vs_datascripts'] = [{
                'index': 1,
                'vs_datascript_set_ref': ds_obj['url']
            }]
            if sslcert_name:
                vs_obj['ssl_key_and_certificate_refs'] = [sslcert['url']]
            vs_obj['pool_ref'] = pool_obj['url']
            vs_obj['subnet'] = placement_subnet
            vs_obj['ign_pool_net_reach'] = True
            put_rsp = avi_api.put('virtualservice/%s' % vs_obj['uuid'],
                                  data=vs_obj)
            self.log.info('Updated VirtualService obj status %d %s' %
                          (put_rsp.status_code, put_rsp.text))
Пример #41
0
 def __init__(self, avi_ip, avi_user, avi_pswd, avi_version):
     self.avi_api = ApiSession(avi_ip,
                               avi_user,
                               avi_pswd,
                               api_version=avi_version)
Пример #42
0
def main():
    argument_specs = dict(
        state=dict(default='present',
                   choices=['absent', 'present']),
        avi_api_update_method=dict(default='put',
                                   choices=['put', 'patch']),
        avi_api_patch_op=dict(choices=['add', 'replace', 'delete']),
        patch_level=dict(type='str', default='/site/dns_vses',
                         choices=['/site/dns_vses', '/site']),
        async_interval=dict(type='int',),
        clear_on_max_retries=dict(type='int',),
        client_ip_addr_group=dict(type='dict',),
        description=dict(type='str',),
        dns_configs=dict(type='list',),
        error_resync_interval=dict(type='int',),
        is_federated=dict(type='bool',),
        leader_cluster_uuid=dict(type='str', required=True),
        maintenance_mode=dict(type='bool',),
        name=dict(type='str', required=True),
        send_interval=dict(type='int',),
        send_interval_prior_to_maintenance_mode=dict(type='int',),
        sites=dict(type='list',),
        tenant_ref=dict(type='str',),
        third_party_sites=dict(type='list',),
        url=dict(type='str',),
        uuid=dict(type='str',),
        view_id=dict(type='int',),
    )
    argument_specs.update(avi_common_argument_spec())
    module = AnsibleModule(
        argument_spec=argument_specs, supports_check_mode=True)
    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_method = module.params['avi_api_update_method']
    if str(api_method).lower() == 'patch':
        patch_op = module.params['avi_api_patch_op']
        # Create controller session
        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)
        # Get existing gslb objects
        rsp = api.get('gslb', api_version=api_creds.api_version)
        existing_gslb = rsp.json()
        gslb = existing_gslb['results']
        for gslb_obj in gslb:
            if (gslb_obj['leader_cluster_uuid'] ==
                    module.params['leader_cluster_uuid']):
                if str(patch_op).lower() == 'add':
                    patch_add_gslb(module, gslb_obj)
                elif str(patch_op).lower() == 'replace':
                    patch_replace_gslb(module, gslb_obj)
                elif str(patch_op).lower() == 'delete':
                    patch_delete_gslb(module, gslb_obj)
            module.params.update(gslb_obj)
            module.params.pop("patch_level")
            module.params.update(
                {
                    'avi_api_update_method': 'put',
                    'state': 'present'
                }
            )

    return avi_ansible_api(module, 'gslb',
                           set([]))
Пример #43
0
                    required=True,
                    help='IP Address of the controller')
parser.add_argument('-u',
                    '--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:
Пример #44
0
def main():

    parser = argparse.ArgumentParser(
        description="AVISDK based Script to export list of virtual services ")
    parser.add_argument("-u",
                        "--username",
                        required=True,
                        help="Login username")
    parser.add_argument("-p",
                        "--password",
                        required=True,
                        help="Login password")
    parser.add_argument("-c",
                        "--controller",
                        required=True,
                        help="Controller IP address")
    parser.add_argument("-a",
                        "--api_version",
                        required=True,
                        help="Api Version Name")
    parser.add_argument("-t",
                        "--tenant",
                        required=False,
                        help="The tenant which get list from.")
    parser.add_argument(
        "-e",
        "--enable",
        action='store_true',
        required=False,
        help="Flag if you want to enable virtual services instead.")
    args = parser.parse_args()

    user = str([args.username if args.username else "admin"][0])
    password = args.password
    controller = args.controller
    api_version = str(args.api_version)
    tenant = str([args.tenant if args.tenant else "admin"][0])
    enableonly = args.enable

    print "CHECKING API VERSION SELECTED!!"
    print "API Version Selected: %s" % api_version

    try:
        version = api_version.split(".")
        if int(version[0]) >= 17:
            if int(version[0]) == 17 and int(version[1]) < 2:
                print "The selected API version is not compatible with this script."
                exit(1)
            else:
                if int(version[0]) == 17 and int(
                        version[1]) == 2 and int(version[2]) < 4:
                    print "The selected API version is not compatible with this script."
                    exit(1)
        else:
            print "The selected API version is not compatible with this script."
            exit(1)

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        print "Unexpected Error: %s, %s" % (exc_type, exc_tb.tb_lineno)
        exit(1)

    print "Starting Virtual Service Check"

    # Get API Session Details
    urllib3.disable_warnings()
    api = ApiSession.get_session(controller,
                                 user,
                                 password,
                                 tenant=tenant,
                                 api_version=api_version)

    print "Avi Networks Authentication Successful"

    print "Gathering Virtual Service Information"
    page = 1
    vs_list = list()
    while True:

        resp = api.get("virtualservice",
                       params={
                           'page_size': 100,
                           'page': str(page)
                       })

        if resp.status_code in range(200, 299):

            print "Downloading Records (Page:" + str(page) + ")"
            json_data = json.loads(resp.text)

            for row in json_data['results']:
                vs_list.append(row["uuid"])

            if 'next' in json_data:
                page = page + 1
            else:
                print "Total VS Found: " + str(json_data['count'])
                break
        else:
            print('Error Occurred /w GET:%s' % resp.text)
            exit(0)

    if len(vs_list) < 1:
        print 'No Virtual Services Found!'
        exit(0)

    output = raw_input(
        "Type 'y' to continue and disable/enable listed virtual services or any other key to cancel.: "
    )
    if output != 'y':
        print 'Request Cancelled!'
        exit(0)
    else:

        syslog.syslog(syslog.LOG_WARNING,
                      ("Avi Script Executed (PARAMS: %s,%s,%s,%s)" %
                       (user, api_version, controller, tenant)))

        q = Queue(maxsize=0)
        num_theads = min(100, len(vs_list))
        results = [{} for x in vs_list]
        for i in range(len(vs_list)):
            q.put((i, vs_list[i]))

        for i in range(num_theads):

            # print 'Starting Thread: %s' % i
            worker = threading.Thread(target=crawl_update,
                                      args=(q, results, api, tenant,
                                            enableonly))
            worker.setDaemon(True)
            worker.start()

        q.join()
        print 'All Tasks Done!'

        syslog.syslog(syslog.LOG_WARNING,
                      ("Avi Script Completed (PARAMS: %s,%s,%s,%s)" %
                       (user, api_version, controller, tenant)))
Пример #45
0
 def test_reuse_api_session(self):
     api1 = ApiSession(avi_credentials=api.avi_credentials,
                       verify=False)
     api2 = ApiSession.get_session(avi_credentials=api.avi_credentials,
                                   verify=False)
     assert api1 == api2
Пример #46
0
vm_mgmt_maskbits="24"
vm_mgmt_begin_addr="10.91.55.100"
vm_mgmt_end_addr="10.91.55.200"
vm_mgmt_dg="10.91.55.1"
vrf_gw_mon_ip="10.91.29.1"
vrf_name="VRF-GSLB"
prefix_name="luiz"
vcenter_folder="luiz"
network_name="PG-1029"
net_address="10.91.29.0"
net_maskbits="24"
beg_addr="10.91.55.101"
end_addr="10.91.55.250"
service_engine_group_name="SEGGSLB"

api = ApiSession.get_session(controller_ip=ip, username=username, password=password, tenant=tenant, api_version='17.2.10')

jsondata = {"vtype":"CLOUD_VCENTER",
            "prefer_static_routes":False,
            "enable_vip_static_routes":False,
            "state_based_dns_registration":True,
            "mtu":1500,
            "dhcp_enabled":False,
            "license_type":"LIC_CORES",
            "license_tier":"ENTERPRISE_18",
            "name":vmware_cloud_name,
            "vcenter_configuration": {
                "privilege":"WRITE_ACCESS",
                "username":vcenter_user,
                "vcenter_url":vcenter_url,
                "password":vcenter_pwd,
                        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)
Пример #48
0
 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"]
     vsvip_name = gSAMPLE_CONFIG["SSL-VS"]["vsvip_obj"]["name"]
     resp = papi.post('pool', data=gSAMPLE_CONFIG["SSL-VS"]["pool_obj"])
     assert resp.status_code == 201
     vip_resp = papi.post('vsvip',
                          data=gSAMPLE_CONFIG["SSL-VS"]["vsvip_obj"])
     assert resp.status_code == 201
     pool_ref = papi.get_obj_ref(resp.json())
     vsvip_ref = papi.get_obj_ref(vip_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["vsvip_ref"] = vsvip_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)
     resp = papi.delete_by_name('vsvip', vsvip_name)
     assert resp.status_code in (200, 204)
Пример #49
0
                     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)
Пример #50
0
    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
Пример #51
0
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)
Пример #52
0
def main():

    #Getting Required Args
    parser = argparse.ArgumentParser(
        description="AVISDK based Script to get the status and configuration" +
        " information of the Virtual Services")
    parser.add_argument("-u",
                        "--username",
                        required=True,
                        help="Login username")
    parser.add_argument("-p",
                        "--password",
                        required=True,
                        help="Login password")
    parser.add_argument("-c",
                        "--controller",
                        required=True,
                        help="Controller IP address")
    parser.add_argument("-t", "--tenant", required=False, help="Tenant Name")
    parser.add_argument("-a",
                        "--api_version",
                        required=False,
                        help="Tenant Name")
    args = parser.parse_args()

    user = args.username
    host = args.controller
    password = args.password
    if args.tenant:
        tenant = args.tenant
    else:
        tenant = "*"

    if args.api_version:
        api_version = args.api_version
    else:
        api_version = "17.1.1"

    #Getting API session for the intended Controller.
    api = ApiSession.get_session(host,
                                 user,
                                 password,
                                 tenant=tenant,
                                 api_version=api_version)

    #Getting the list of VirtualService(s).
    vs_list = get_vs_list(api, api_version)

    #Getting VS information
    oper_dict = get_vs_oper_info(api, api_version, vs_list)

    #print "Final Oper Dict:" + str(oper_dict)

    for state, vs in oper_dict.iteritems():
        print("VS in State:%s [%s]" % (state, len(vs)))
        table = PrettyTable(hrules=ALL)
        table.field_names = ["VS Name", "VIP_ID", "VIP_Address", "DNS_INFO"]
        for vss in vs:
            vips = list()
            dns_info = list()
            vip_count = 0
            dns_count = 0
            if 'vip_1' in vss.keys():
                vips = [
                    value for key, value in vss.iteritems()
                    if 'vip' in key.lower()
                ]
                vip_count = len(vips)
            if 'dns_1' in vss.keys():
                dns_info = [
                    value for key, value in vss.iteritems()
                    if 'dns' in key.lower()
                ]
                dns_count = len(dns_info)
            vs_name = vss['name']
            vip_ids = ''
            vips_list = ''
            dns_list = ''
            for vip in vips:
                vip_ids += vip['vip_id'] + "\n"
                vips_list += vip['ip_address']['addr']
                if vip.get('floating_ip', None):
                    vips_list += '- ' + vip['floating_ip']['addr']
                vips_list += '\n'
            for dns in dns_info:
                dns_list += dns['fqdn'] + "\n"
            table.add_row(
                [vs_name, vip_ids[:-1], vips_list[:-1], dns_list[:-1]])

        print table
        print "\n"