def createBridgeDomain(tenant, epgSpec, apicMoDir): logging.debug('Inside createBridgeDomain function') gw = epgSpec['gw-cidr'] netmask = gw.split('/') if len(netmask) != 2: return ['failed', 'invalid subnet'] # Check if gw ip is correct bdIsL3 = True if netmask[0] == '': logging.info('Missing gateway in contiv network. Creating BD without Subnet (L2 only).') bdIsL3 = False bdName = epgSpec['nw-name'] bdDn = formBDDn(tenant, bdName) logging.info('Creating BD %s under tenant %s' % (bdName, tenant)) # Check if there is a VRF to tie the BD. If not, create one. tenMo = tenantDict[tenant] ctxMos = findTenantVrfContexts(tenant, apicMoDir) logging.debug('Fetched context mos:') logging.debug(ctxMos) if len(ctxMos) == 0: # No VRFs found. Need to create one. tenVrfName = formTenantVRFName(tenant) ctxMo = Ctx(tenMo, tenVrfName) cR = ConfigRequest() cR.addMo(ctxMo) apicMoDir.commit(cR) elif len(ctxMos) > 1: logging.error('Multi VRF scenario requires pre-created BDs') return ['failed', 'Multiple VRFs under tenant not supported yet'] else: for ctxMo in ctxMos: tenVrfName = ctxMo.name fvBDMo = BD(tenMo, name=bdName) RsCtx(fvBDMo, tnFvCtxName=tenVrfName) if bdIsL3: # create subnet Subnet(fvBDMo, gw) cR = ConfigRequest() cR.addMo(fvBDMo) apicMoDir.commit(cR) if bdIsL3: subnetDict[gw] = fvBDMo logging.info('Created BD {}'.format(bdName)) return ['success', 'ok']
def create_contracts(modir, tenant_name): policy_universe = modir.lookupByDn('uni') fv_tenant = Tenant(policy_universe, tenant_name) # create Contract for web vz_ct_web = BrCP(fv_tenant, CONTRACT_WEB_CT) vz_subj_web = Subj(vz_ct_web, 'Web') vz_rs_subj_filt_att_web = RsSubjFiltAtt(vz_subj_web, 'http') #create contract for App vz_ct_app = BrCP(fv_tenant, CONTRACT_APP_CT) vz_subj_rmi = Subj(vz_ct_app, 'RMI') vz_rs_subj_filt_att_rmi = RsSubjFiltAtt(vz_subj_rmi, 'rmi') # create filter for sql vz_ct_db = BrCP(fv_tenant, CONTRACT_DB_CT) vz_subj_db = Subj(vz_ct_db, 'DbCt') vz_rs_subj_filt_att_db = RsSubjFiltAtt(vz_subj_db, 'sql') # print the query in XML format print toXMLStr(policy_universe, prettyPrint=True) # Commit the change using a ConfigRequest object configReq = ConfigRequest() configReq.addMo(policy_universe) modir.commit(configReq)
def create_bridge_domains(delete=''): bd_df = pd.read_excel("input-data/ACI_DD_Workbook.xlsx", sheet_name='Bridge_Domains') file = open("BD_Configuration.log", "w") logon = apic_logon() uniMo = logon.lookupByDn('uni') for index, row in bd_df.iterrows(): fvTenant = Tenant(uniMo, row['Tenant']) if delete == 'yes': fvBD = BD(fvTenant, name=row['Name'], status='deleted') else: fvBD = BD(fvTenant, name=row['Name'], arpFlood=row['ARP Flood'], ipLearning=row['EP_learn'], description=row['Description'], multiDstPktAct=row['MultiDest_Flood'], mcastAllow=row['mcastAllow'], unkMcastAct=row['L3Unk_Mcast'], limitIpLearnToSubnets=row['Limit_IP_Learn']) fvRsCtx = RsCtx(fvBD, tnFvCtxName=row['VRF']) if pd.isnull(row['L3O']) == False: fvRsBDToOut = RsBDToOut(fvBD, tnL3extOutName=row['L3O']) cfgRequest = ConfigRequest() cfgRequest.addMo(fvBD) logon.commit(cfgRequest) json_data = toJSONStr(fvBD, prettyPrint=True) file.write( '\n-------------------------------------------------------------------\n' ) file.write(json_data) file.close()
def create_vrfs(delete=''): vrf_df = pd.read_excel("input-data/ACI_DD_Workbook.xlsx", sheet_name='VRFs') file = open("VRF_Configuration.log", "w") logon = apic_logon() uniMo = logon.lookupByDn('uni') for index, row in vrf_df.iterrows(): fvTenant = Tenant(uniMo, row['Tenant']) if delete == 'yes': fvCtx = Ctx(fvTenant, name=row['Name'], status='deleted') else: fvCtx = Ctx(fvTenant, name=row['Name'], pcEnfDir=row['Enforcement Direction'], pcEndPref=row['Enforcement'], description=row['Description']) cfgRequest = ConfigRequest() cfgRequest.addMo(fvCtx) logon.commit(cfgRequest) json_data = toJSONStr(fvCtx, prettyPrint=True) file.write( '\n-------------------------------------------------------------------\n' ) file.write(json_data) file.close()
def test_post_tn(self, apics, certobject, userobject): apic = apics[0] secure = False if apics[1] == 'False' else True userobject.pkey = certobject.readFile( fileName=certobject.pkeyfile) session = CertSession(apic, userobject.certDn, userobject.pkey, secure=secure, requestFormat='xml') moDir = MoDirectory(session) uni = Uni('') fvTenant = Tenant(uni, name='t') fvBD = BD(fvTenant, 't-bd') fvAp = Ap(fvTenant, 't-app') cr = ConfigRequest() #cr.subtree = 'full' cr.addMo(fvTenant) if userobject.user == 'rouser': with pytest.raises(RestError) as excinfo: r = moDir.commit(cr) assert excinfo.value.reason == ('user rouser does not have ' + 'domain access to config Mo, ' + 'class fvTenant') elif userobject.user == 'rwuser': r = moDir.commit(cr) else: raise NotImplementedError
def createTenant(md, tn, desc): uniMo = md.lookupByDn('uni') fvTenantMo = Tenant(uniMo, name=tn, descr=desc) cfgRequest = ConfigRequest() cfgRequest.addMo(fvTenantMo) md.commit(cfgRequest)
def create_tenant(logon_session, tenant_name="Example_TN", description="Description"): from cobra.internal.codec.jsoncodec import toJSONStr from cobra.model.fv import Tenant, RsTenantMonPol from cobra.mit.request import ConfigRequest import cobra.model.pol import cobra.model.vns c = ConfigRequest() #apic_logon(apic_url, user, password) polUni = cobra.model.pol.Uni('') fvTenant = Tenant(polUni, ownerKey=u'', name=tenant_name, descr=description, nameAlias=tenant_name, ownerTag=u'', annotation=u'') vnsSvcCont = cobra.model.vns.SvcCont(fvTenant, annotation=u'') fvRsTenantMonPol = RsTenantMonPol(fvTenant, annotation=u'', tnMonEPGPolName=u'') tenant_data = toJSONStr(polUni) c.addMo(polUni) logon_session.commit(c) return tenant_data
def test_ConfigRequest_options(self): cid = '1234567890' expectedOptions = '' cr = ConfigRequest() cr.id = cid expectedOptions += '_dc=' + cid assert cr.options == expectedOptions
def vpc_policy(host, user, password): print('[BEG] VPC Configuration') moDir = apic_login(host, user, password) polUni = Uni('') fabricInst = Inst(polUni) print('--- Creating VPC Domain') VPCdID = '20' SW1 = '103' SW2 = '104' fabricProtPol = ProtPol(fabricInst, pairT=u'explicit', name=u'default') fabricExplicitGEp = ExplicitGEp(fabricProtPol, id=VPCdID, name=u'VPC-Cobra-Policy') fabricRsVpcInstPol = RsVpcInstPol(fabricExplicitGEp, tnVpcInstPolName=u'default') print('--- Assigning LEAF Switches - Node' + SW1 + ' Node' + SW2 + ' to Domain ID:' + VPCdID) fabricNodePEp = NodePEp(fabricExplicitGEp, id=SW1) fabricNodePEp2 = NodePEp(fabricExplicitGEp, id=SW2) tenantCfg = ConfigRequest() tenantCfg.addMo(fabricInst) moDir.commit(tenantCfg) print('[END] VPC Configuration \n')
def test_ConfigRequest_getUrl(self, sessionUrl, mo, requestType): session = LoginSession(sessionUrl, 'admin', 'password', requestFormat=requestType) expected = sessionUrl + '/api/mo/' + str(mo.dn) + '.' + requestType cr = ConfigRequest() cr.addMo(mo) assert cr.getUrl(session) == expected
def create_apn(logon_session, tenant_name="Example_TN", description="Description", ap_name=''): from cobra.internal.codec.jsoncodec import toJSONStr from cobra.model.fv import Tenant, RsTenantMonPol, Ap from cobra.mit.request import ConfigRequest import cobra.model.pol import cobra.model.vns c = ConfigRequest() #apic_logon(apic_url, user, password) polUni = cobra.model.pol.Uni('') fvTenant = Tenant(polUni, tenant_name) # build the request using cobra syntax fvAp = Ap(fvTenant, ownerKey=u'', name=ap_name, descr=description, nameAlias=u'', ownerTag=u'', prio=u'unspecified', annotation=u'') apn_data = toJSONStr(polUni) c.addMo(polUni) logon_session.commit(c) return apn_data
def test_ConfigRequest_removeMo_no_configMos_left(self): fvTenant = Tenant('uni', 'testing') fvnsVlanInstP = VlanInstP('uni/infra', 'namespace1', 'dynamic') cr = ConfigRequest() cr.addMo(fvTenant) cr.removeMo(fvTenant) assert not cr.hasMo(fvTenant.dn)
def test_ConfigRequest_addMo_raises_not_allowed_context(self): fvTenant = Tenant('uni', 'testing') fvnsVlanInstP = VlanInstP('uni/infra', 'namespace1', 'dynamic') cr = ConfigRequest() cr.addMo(fvTenant) with pytest.raises(ValueError): cr.addMo(fvnsVlanInstP)
def test_ConfigRequest_requestargs(self): expected1 = { 'data': '<?xml version="1.0" encoding="UTF-8"?>\n' + '<fvTenant name=\'testing\' ' + 'status=\'created,modified\'></fvTenant>', 'headers': { 'Cookie': 'APIC-cookie=None' }, 'timeout': 90, 'verify': False } expected2 = { 'data': '<?xml version="1.0" encoding="UTF-8"?>\n' + '<fvTenant status=\'created,modified\' ' + 'name=\'testing\'></fvTenant>', 'headers': { 'Cookie': 'APIC-cookie=None' }, 'timeout': 90, 'verify': False } polUni = Uni('') fvTenant = Tenant(polUni, 'testing') session = LoginSession('http://1.1.1.1', 'admin', 'password') cr = ConfigRequest() cr.addMo(fvTenant) assert (cr.requestargs(session) == expected1 or cr.requestargs(session) == expected2)
def config_obj(moDir, mo): # Create Config Request CfgRqst = ConfigRequest() CfgRqst.addMo(mo) # Commit Config Request moDir.commit(CfgRqst)
def test_ConfigRequest_removeMo_and_hasMo_positive(self): fvTenant = Tenant('uni', 'testing') fvnsVlanInstP = VlanInstP('uni/infra', 'namespace1', 'dynamic') cr = ConfigRequest() cr.addMo(fvTenant) cr.removeMo(fvTenant) cr.addMo(fvnsVlanInstP) assert cr.hasMo(fvnsVlanInstP.dn)
def test_ConfigRequest_data(self): expected = ('{"fvTenant": {"attributes": {"name": "test", "status": ' + '"created,modified"}}}') polUni = Uni('') fvTenant = Tenant(polUni, 'test') cr = ConfigRequest() cr.addMo(fvTenant) assert cr.data == expected
def createLogicalNodeProfile(md, tn, l3out, profile, desc): parentdn = 'uni/tn-' + tn + '/out-' + l3out uniMo = md.lookupByDn(parentdn) lnp = LNodeP(uniMo, name=profile, descr=desc) cfgRequest = ConfigRequest() cfgRequest.addMo(lnp) md.commit(cfgRequest)
def createBD(md, tn, bdname, desc): tenant = 'uni/tn-' + tn uniMo = md.lookupByDn(tenant) fvBDMo = BD(uniMo, name=bdname, descr=desc, ipLearning='no') cfgRequest = ConfigRequest() cfgRequest.addMo(fvBDMo) md.commit(cfgRequest)
def createL2OUT(md, tn, l2out, desc): tenant = 'uni/tn-' + tn uniMo = md.lookupByDn(tenant) L2OUTMo = Out(uniMo, name=l2out, descr=desc) cfgRequest = ConfigRequest() cfgRequest.addMo(L2OUTMo) md.commit(cfgRequest)
def commit_change(self, changed_object=None, print_xml=True, pretty_print=True): """Commit the changes to APIC""" changed_object = self.mo if changed_object is None else changed_object if print_xml: print_query_xml(changed_object, pretty_print=pretty_print) config_req = ConfigRequest() config_req.addMo(changed_object) self.modir.commit(config_req)
def createVRF(md, tn, vrfname, desc): tenant = 'uni/tn-' + tn uniMo = md.lookupByDn(tenant) fvCtxMo = Ctx(uniMo, name=vrfname, descr=desc) cfgRequest = ConfigRequest() cfgRequest.addMo(fvCtxMo) md.commit(cfgRequest)
def createBGPPeer(md, tn, l3out, profile, address, desc): parentdn = 'uni/tn-' + tn + '/out-' + l3out + '/lnodep-' + profile uniMo = md.lookupByDn(parentdn) bgpp = PeerP(uniMo, name=profile, addr=address, descr=desc) cfgRequest = ConfigRequest() cfgRequest.addMo(bgpp) md.commit(cfgRequest)
def add_servicegraph(): apicURL = os.getenv("CliqrCloud_AciApicEndpoint") apicUser = os.getenv("CliqrCloud_AciUsername") apicPwd = os.getenv("CliqrCloud_AciPassword") apicTenant = os.getenv("CliqrCloud_AciTenantName") apicServiceGraphTemplate = os.getenv("Cloud_Setting_serviceGraphTemplate") # Handle cases where APIC URL is configured without ssl (typically, in a lab). if apicURL.startswith("https"): loginSession = LoginSession(apicURL, apicUser, apicPwd) else: loginSession = LoginSession(apicURL, apicUser, apicPwd,secure=False) # CliqrTier_CentOS_1_Cloud_Setting_AciPortGroup_2 tmpString = "CliqrTier_" + os.getenv("CliqrDependencies") + "_Cloud_Setting_AciPortGroup_2" appProfileName = os.getenv(tmpString).split("|")[1] qTenant = "tn-" + apicTenant qString = "uni/" + qTenant + "/ap-" + appProfileName dnQuery = DnQuery(qString) dnQuery.queryTarget = 'subtree' dnQuery.classFilter = 'fvRsProv' dnQuery.subtree = 'children' #dnQuery.subtreePropFilter='eq(fvRsCons.tCl,"vzBrCP")' # Obtain Session from APIC. moDir = MoDirectory(loginSession) moDir.login() # Query to obtain data from Managed Object Directory. dmo = moDir.query(dnQuery) print str(dmo[0].tDn) # Debug String. Remove from running env. logging.debug(" Contract String Obtained :" + dmo[0].tDn) # Service Graph - Query String qStringAbsG = "uni/" + qTenant + "/AbsGraph-" + apicServiceGraphTemplate graphMO = moDir.lookupByDn(qStringAbsG) # Subject Query String qStringSubj = dmo[0].tDn + "/subj-cliqr-subject" subjMO = moDir.lookupByDn(qStringSubj) # Attach Graph to Contract. RsSubjGraphAtt(subjMO, tnVnsAbsGraphName=graphMO.name) # Create Commit Object. nsCfg = ConfigRequest() nsCfg.addMo(subjMO) moDir.commit(nsCfg) contractString = dmo[0].tDn tmpArr = contractString.split("/") apicContractName = tmpArr[len(tmpArr)-1].replace("brc-","") aviApicContractArg = apicContractName + ":" + apicServiceGraphTemplate aviApicEpgName = appProfileName + ":" + os.getenv(tmpString).split("|")[2] params = {} with open('params.json', 'r') as p: params = json.loads(p.read()) params['apic_contract_graph'] = aviApicContractArg params['apic_epg_name'] = aviApicEpgName logging.debug(" Dump Params :: " + json.dumps(params)) with open('params.json', 'w') as f: json.dump(params, f)
def test_post_cert_to_local_user(self, moDir, certobject, userobject): # Update the user object with the cert data userobject.aaaUserCert.data = certobject.readFile( fileName=certobject.certfile) # Commit the user to the APIC with the cert cr = ConfigRequest() cr.addMo(userobject.aaaUser) r = moDir.commit(cr) assert r.status_code == 200
def create_tenant(modir, tenant_name): policy_universe = modir.lookupByDn('uni') fvTenant = Tenant(policy_universe, tenant_name) print toXMLStr(policy_universe, prettyPrint=True) configReq = ConfigRequest() configReq.addMo(policy_universe) modir.commit(configReq)
def commit(self, commit_object): """ Commits object changes to controller :param commit_object: :return: """ self.configReq = ConfigRequest() self.configReq.addMo(commit_object) self.moDir.commit(self.configReq)
def test_ConfigRequest_getRootMo(self, mos, expected): cr = ConfigRequest() mos.append(expected) for mo in mos: if mo is not None: try: cr.addMo(mo) except ValueError: pass assert cr.getRootMo() == expected
def create_bd(logon_session, tenant_name="Example_TN", description="Description", bd_name='', vrf_name=''): from cobra.internal.codec.jsoncodec import toJSONStr from cobra.model.fv import Tenant, RsTenantMonPol, BD, RsIgmpsn, RsCtx from cobra.model.fv import RsBdToEpRet, RsBDToNdP from cobra.mit.request import ConfigRequest import cobra.model.pol import cobra.model.vns c = ConfigRequest() #apic_logon(apic_url, user, password) polUni = cobra.model.pol.Uni('') fvTenant = Tenant(polUni, tenant_name) fvBD = BD(fvTenant, multiDstPktAct=u'bd-flood', mcastAllow=u'no', limitIpLearnToSubnets=u'yes', unicastRoute=u'no', unkMcastAct=u'flood', descr=u'', llAddr=u'::', nameAlias=u'', type=u'regular', ipLearning=u'no', vmac=u'not-applicable', mac=u'00:22:BD:F8:19:FF', epMoveDetectMode=u'', ownerTag=u'', intersiteBumTrafficAllow=u'no', annotation=u'', ownerKey=u'', name=bd_name, epClear=u'no', unkMacUcastAct=u'flood', arpFlood=u'yes', intersiteL2Stretch=u'no', OptimizeWanBandwidth=u'no') fvRsIgmpsn = RsIgmpsn(fvBD, tnIgmpSnoopPolName=u'', annotation=u'') fvRsCtx = RsCtx(fvBD, annotation=u'', tnFvCtxName=vrf_name) fvRsBdToEpRet = RsBdToEpRet(fvBD, resolveAct=u'resolve', annotation=u'', tnFvEpRetPolName=u'') fvRsBDToNdP = RsBDToNdP(fvBD, annotation=u'', tnNdIfPolName=u'') bd_data = toJSONStr(polUni) c.addMo(polUni) logon_session.commit(c) return bd_data
def commit_change(self, changed_object=None, print_xml=True): """Commit the changes to APIC""" # config_req = ConfigRequest() # config_req.addMo(self.mo) # self.modir.commit(config_req) # modir.logout() configReq = ConfigRequest() configReq.addMo(self.mo) self.modir.commit(configReq) self.modir.logout()