def turtles_down(session, referer): dnQuery = DnQuery(referer.dn) dnQuery.queryTarget = 'children' childMo = session.query(dnQuery) for newMo in childMo: print str(newMo.dn) turtles_down(session, newMo)
def lookupByClass(self, classNames, parentDn=None, **kwargs): """Lookup MO's by class. A short-form managed object (MO) query by class. Args: classNames (str or list): The class name list of class names. If parentDn is set, the classNames are used as a filter in a subtree query for the parentDn parentDn (cobra.mit.naming.Dn or str, optional): The distinguished name of the parent object as a :class:`cobra.mit.naming.Dn` or string. **kwargs: Arbitrary parameters to be passed to the query generated internally, to further filter the result Returns: list: A list of the managed objects found in the query. """ if parentDn: dnQuery = DnQuery(parentDn) dnQuery.classFilter = classNames dnQuery.queryTarget = 'subtree' self.__setQueryParams(dnQuery, kwargs) mos = self.query(dnQuery) else: classQuery = ClassQuery(classNames) self.__setQueryParams(classQuery, kwargs) mos = self.query(classQuery) return mos
def get_faults(self, epg_dn): class_query = DnQuery(epg_dn) class_query.subtree = 'full' class_query.subtreeInclude = 'faults' epg_list = self.moDir.query(class_query) fault_list = self.get_faults_from_tree(epg_list[0], []) return fault_list
def test_DnQuery_options(self): did = '1234567890' expectedOptions = '' dq = DnQuery('uni') dq.id = did expectedOptions += '_dc=' + did assert dq.options == expectedOptions
def lookupByClass(self, classNames, parentDn=None, propFilter=None): """Lookup MO's by class A short-form managed object (MO) query by class. Args: classNames (str or list): The class name list of class names. If parentDn is set, the classNames are used as a filter in a subtree query for the parentDn parentDn (cobra.mit.naming.Dn or str): The distinguished name of the parent object as a :class:`cobra.mit.naming.Dn` or string. propFilter (str): A property filter expression Returns: list: A list of the managed objects found in the query. """ if parentDn: dnQuery = DnQuery(parentDn) dnQuery.classFilter = classNames dnQuery.queryTarget = 'subtree' if propFilter: dnQuery.propFilter = propFilter mos = self.query(dnQuery) else: classQuery = ClassQuery(classNames) if propFilter: classQuery.propFilter = propFilter mos = self.query(classQuery) return mos
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_DnQuery_getUrl(self, sessionUrl, dc, requestType): session = LoginSession(sessionUrl, 'admin', 'password', requestFormat=requestType) dn = 'uni' dq = DnQuery('uni') expected = sessionUrl + '/api/mo/' + dn + '.' + requestType dq.id = dc expected += '?_dc=' + dc assert dq.getUrl(session) == expected
def get_full_tenant(self,tenant_name): dnQ = DnQuery('uni/tn-{}'.format(tenant_name)) dnQ.subtree = 'full' tenant = self.mo_dir.query(dnQ) if tenant: return tenant[0] return None
def query_child_objects(self, dn_query_name): """ Retrieve the object using the dn and return all the children under it :param dn_query_name: dn of the management object :return: """ dn_query = DnQuery(dn_query_name) dn_query.queryTarget = QUERY_TARGET_CHILDREN child_mos = self.moDir.query(dn_query) return child_mos
def check_backup_status(md, name): sleep(1) dq = DnQuery('uni/backupst/jobs-[uni/fabric/configimp-{}]'.format(name)) backup_job = md.query(dq) last_runtime = backup_job[0].lastJobName run_dn = 'uni/backupst/jobs-[uni/fabric/configimp-{}]/run-{}'.format( name, last_runtime) dq = DnQuery(run_dn) last_run = md.query(dq) print 'Backup status: {}'.format(last_run[0].details)
def findTenantVrfContexts(tenant, apicMoDir): logging.debug('Inside findTenantVrfContexts function') tenantDn = formTenantDn(tenant) dnQuery = DnQuery(tenantDn) dnQuery.subtree = 'children' tenantMo = apicMoDir.query(dnQuery) if len(tenantMo) > 0: # We expect only 1 tenant with that name return tenantMo[0].ctx else: return []
def get_ports_in_group(moDir, uri): ''' :param moDir: login session :param uri: dn of the policy group :return: list of ports configured for a policy group ''' ports = [] dnq = DnQuery(uri) dnq.queryTarget = 'children' dnq.classFilter = 'infraRtAccBaseGrp' ports = moDir.query(dnq) return ports
def main(host, username, password, tenant): apic = "https://%s" % host print("Connecting to APIC : %s" % apic) moDir = MoDirectory(LoginSession(apic, username, password)) moDir.login() dn_name = "uni/tn-" + tenant print(dn_name) dnq = DnQuery(dn_name) dnq.subtree = 'children' tenantMO = moDir.query(dnq) for bdMO in tenantMO.BD: print("BD NAME => {", bdMO.name, "}")
def get_domain_aep(moDir, Aep): ''' :param moDir: login session :param Aep: attachable entity profile name :return: list of domains in the AEP ''' uri = 'uni/infra/attentp-{0}/dompcont' dnq = DnQuery(uri.format(Aep)) dnq.queryTarget = 'children' dnq.classFilter = 'infraAssocDomP' assocDomP = moDir.query(dnq) dompDns = [each.dompDn for each in assocDomP if each] return dompDns
def get_vlan_pool(moDir, domain_dn): ''' :param moDir: login session :param domain_dn: dn of the domain :return: dn of a vlan pool ''' dnq = DnQuery(domain_dn) dnq.queryTarget = 'children' dnq.classFilter = 'infraRsVlanNs' vlanNs = moDir.query(dnq) #there will only be one pool in the domain pool = vlanNs[0].tDn return pool
def get_nodeid(moDir, leafProfile): """ :param moDir: login session :param leafProfile: leaf Profile name :return node ids a switch. assumes one LeafS in leaf Profile, maximum of 2 nodes in a block. '0' if not configured """ uri = 'uni/infra/nprof-{0}' dnq = DnQuery(uri.format(leafProfile)) dnq.queryTarget = 'children' dnq.classFilter = 'infraLeafS' leafs = moDir.query(dnq) dnq2 = DnQuery(leafs[0].dn) dnq2.queryTarget = 'children' nodeBlk = moDir.query(dnq2) dnq2.classFilter = 'infraNodeBlk' nodeBlk = moDir.query(dnq2) if len(nodeBlk) == 2: if int(nodeBlk[0].from_) < int(nodeBlk[1].from_): return nodeBlk[0].from_ + '-' + nodeBlk[1].from_ else: return nodeBlk[1].from_ + '-' + nodeBlk[0].from_ elif len(nodeBlk) == 1: return nodeBlk[0].from_ else: return "0"
def get_fexports(moDir, fexProfile): ''' :param moDir: login session :param fexProfile: FEX Profile name :return: list of all configured ports ''' configured = [] uri = 'uni/infra/fexprof-{0}' dnq = DnQuery(uri.format(fexProfile)) dnq.queryTarget = 'children' dnq.classFilter = 'infraHPortS' ports = moDir.query(dnq) names = [each.name for each in ports if each] for name in names: uri2 = 'uni/infra/fexprof-{0}/hports-{1}-typ-range' dnq2 = DnQuery(uri2.format(fexProfile, name)) dnq2.queryTarget = 'children' dnq2.classFilter = 'infraPortBlk' blocks = moDir.query(dnq2) for block in blocks: ints = [] startingPort = block.fromPort card = block.fromCard ints.append(card + '/' + startingPort) s = int(startingPort) while s != int(block.toPort): s += 1 ints.append(card + '/' + str(s)) configured.append({'name': name, 'ports': ints}) return configured
def get_epg_dom(moDir, uri, Aepg): """ :param moDir: login session :param uri: dn of EPG :param Aepg: name of EPG :return list of domains for an EPG """ domains = [] dnq = DnQuery(uri + Aepg) dnq.queryTarget = 'children' dnq.classFilter = 'fvRsDomAtt' rsDomAtt = moDir.query(dnq) # "uni/phys-LEGACY", "uni/vmmp-VMware/dom-AVS-01" domains = [each.tDn for each in rsDomAtt if each] return domains
def get_policy_group_aep(moDir, policyGroup, type): """ :param moDir: login session :param policyGroup: name of policy group :param type: type of policy. accbundle or accportgrp :return AEP for a policy group """ uri = 'uni/infra/funcprof/{0}{1}' dnq = DnQuery(uri.format(type, policyGroup)) dnq.queryTarget = 'children' dnq.classFilter = 'infraRsAttEntP' rsAttEntP = moDir.query(dnq) try: aep = str(rsAttEntP[0].tDn).split('attentp-')[1] except IndexError: aep = '0' return aep
def get_vlans(moDir, pool_dn): ''' :param moDir: login session :param pool_dn: dn of a vlan pool :return: list of vlans ''' vlans = [] dnq = DnQuery(pool_dn) dnq.queryTarget = 'children' dnq.classFilter = 'fvnsEncapBlk' encapBlk = moDir.query(dnq) for ranges in encapBlk: # cannot access from keyword, so access as dictionary startingVlan = ranges.__dict__['from'].split('-')[1] vlans.append('vlan-' + startingVlan) s = int(startingVlan) while s != int(ranges.to.split('-')[1]): s += 1 vlans.append('vlan-' + str(s)) return vlans
def get_fexport_policy_group(moDir, fexProfile, port_name): ''' :param moDir: login session :param fexProfile: profile name of the FEX :param port_name: name of the port :return: policy group for the configured port. '0' if not configured ''' uri = 'uni/infra/fexprof-{0}/hports-{1}-typ-range' dnq = DnQuery(uri.format(fexProfile, port_name)) dnq.queryTarget = 'children' dnq.classFilter = 'infraRsAccBaseGrp' rsAccBaseGrp = moDir.query(dnq) try: if rsAccBaseGrp[0].tCl == 'infraAccBndlGrp': policy_group = str(rsAccBaseGrp[0].tDn).split('accbundle-')[1] elif rsAccBaseGrp[0].tCl == 'infraAccPortGrp': policy_group = str(rsAccBaseGrp[0].tDn).split('accportgrp-')[1] except IndexError: policy_group = '0' return policy_group
def lookupByClass(self, classNames, parentDn=None, **queryParams): """ A short-form managed object (MO) query by class. Args: classNames: Name of the class to lookup parentDn: dn of the root object were to start search from (optional) queryParams: a dictionary including the properties to the added to the query. """ if parentDn: dnQuery = DnQuery(parentDn) dnQuery.classFilter = classNames dnQuery.queryTarget = 'subtree' self.__setQueryParams(dnQuery, queryParams) mos = self.query(dnQuery) else: classQuery = ClassQuery(classNames) self.__setQueryParams(classQuery, queryParams) mos = self.query(classQuery) return mos
def lookupByDn(self, dnStrOrDn, **queryParams): """ A short-form managed object (MO) query using the distinguished name(Dn) of the MO. Args: dnStrOrDn: dn of the object to lookup queryParams: a dictionary including the properties to the added to the query. """ dnQuery = DnQuery(dnStrOrDn) self.__setQueryParams(dnQuery, queryParams) mos = self.query(dnQuery) return mos[0] if mos else None
def test_get_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) dnQuery = DnQuery('uni/tn-common') #dnQuery.subtree = "full" tq = moDir.query(dnQuery) assert len(tq) == 1 tq = tq[0] assert str(tq.parentDn) == 'uni' assert str(tq.dn) == 'uni/tn-common'
def lookupByDn(self, dnStrOrDn): """Query the APIC or fabric node by distinguished name (Dn) A short-form managed object (MO) query using the Dn of the MO of the MO. Args: dnStrOrDn (str or cobra.mit.naming.Dn): A distinguished name as a :class:`cobra.mit.naming.Dn` or string Returns: None or cobra.mit.mo.Mo: None if no MO was returned otherwise :class:`cobra.mit.mo.Mo` """ dnQuery = DnQuery(dnStrOrDn) mos = self.query(dnQuery) return mos[0] if mos else None
def check_if_switchport_configured(moDir, switchProfile, range): ''' :param moDir: login session :param switchProfile: switch Profile name :param range: switch port range to check :return: True if configured ''' configured = [] proposed = [] card, fromPort, toPort = input_ports(range) proposed.append(card + '/' + fromPort) fromP = int(fromPort) toP = int(toPort) while (fromP != toP): fromP += 1 proposed.append(card + '/' + str(fromP)) uri = 'uni/infra/accportprof-{0}_ifselector' dnq = DnQuery(uri.format(switchProfile)) dnq.queryTarget = 'children' dnq.classFilter = 'infraHPortS' ports = moDir.query(dnq) names = [each.name for each in ports if each] for name in names: uri2 = 'uni/infra/accportprof-{0}_ifselector/hports-{1}-typ-range' dnq2 = DnQuery(uri2.format(switchProfile, name)) dnq2.queryTarget = 'children' dnq2.classFilter = 'infraPortBlk' blocks = moDir.query(dnq2) for block in blocks: startingPort = block.fromPort card = block.fromCard configured.append(card + '/' + startingPort) s = int(startingPort) while s != int(block.toPort): s += 1 configured.append(card + '/' + str(s)) for p in proposed: if p in configured: return True return False
def lookupByDn(self, dnStrOrDn, **kwargs): """Query the APIC or fabric node by distinguished name (Dn). A short-form managed object (MO) query using the Dn of the MO of the MO. Args: dnStrOrDn (str or cobra.mit.naming.Dn): A distinguished name as a :class:`cobra.mit.naming.Dn` or string **kwargs: Arbitrary parameters to be passed to the query generated internally, to further filter the result Returns: None or cobra.mit.mo.Mo: None if no MO was returned otherwise :class:`cobra.mit.mo.Mo` """ dnQuery = DnQuery(dnStrOrDn) self.__setQueryParams(dnQuery, kwargs) mos = self.query(dnQuery) return mos[0] if mos else None
def get_full_aci_config(apic, user, password, outfile): try: url = "https://" + apic ls = cobra.mit.session.LoginSession(url, "apic:ACS\\" + user, password, secure=False, timeout=30) md = cobra.mit.access.MoDirectory(ls) md.login() #Get tenant config cq = ClassQuery('fvTenant') cq.subtree = 'full' cq.propInclude= 'config-only' tenant_config = md.query(cq) #Infra config dq = DnQuery('uni/infra') dq.subtree = 'full' dq.propInclude = 'config-only' infra_config = md.query(dq) #Fabric config dq = DnQuery('uni/fabric') dq.subtree = 'full' dq.propInclude = 'config-only' fabric_config = md.query(dq) file = open(outfile, 'w+') file.write("# " + apic + " #") file.write("\n###########" + '\n') file.write("# TENANTS ") file.write("\n###########" + '\n') for tenant in tenant_config: file.write(toJSONStr(tenant, prettyPrint=True)) file.write("\n###########" + '\n') file.write("# Infra ") file.write("\n###########" + '\n') for infra in infra_config: file.write(toJSONStr(infra, prettyPrint=True)) file.write("\n###########" + '\n') file.write("# Fabric ") file.write("\n###########" + '\n') for fabric in fabric_config: file.write(toJSONStr(fabric, prettyPrint=True)) file.close() except: print "Error in get_full_aci_config() for %s: %s" % (apic, sys.exc_info()[0])
# Making a new epg and calling it "vmepg" application_profile = moDir.lookupByDn("uni/tn-{0}/ap-{1}".format(tenant, ap)) new_epg = AEPg(application_profile, "vmepg") # Committing the changes config_request = ConfigRequest() config_request.addMo(new_epg) moDir.commit(config_request) # Enter epg to use as template for vmepg epg_template= "default" dnQuery = DnQuery('uni/tn-{0}/ap-{1}/epg-{2}'.format(tenant, ap, epg_template)) dnQuery.subtree = 'children' epgMO = moDir.query(dnQuery) # Traversing every property within epg_template and copying it to vmepg for epg in epgMO: for epgChild in epg.children: for name, obj in inspect.getmembers(sys.modules[__name__]): if inspect.isclass(obj): copy_of_property = str(epgChild.rn) if (copy_of_property.lower().startswith(obj.__name__.lower())): exec("object_made = " + obj.__name__ + "(epg, \"" + copy_of_property + "\")") config_request.addMo(object_made) moDir.commit(config_request)
from cobra.mit.session import LoginSession from cobra.mit.access import MoDirectory from cobra.mit.request import DnQuery urllib3.disable_warnings() #Disable HTTPS warnings apic_url = '' apic_user = '' apic_password = '' loginSession = LoginSession(apic_url, apic_user, apic_password) #Setup Login credentials md = MoDirectory(loginSession) md.login() dq1 = DnQuery('uni/<INSERT TENANT NAME>/<<INSERT AP PROFILE NAME>') #Query the Tenant dq1.queryTarget='children' #request all children from Tenant Bridge_Domains = md.query(dq1) #Get list of Bridge Domains (VLANs) IFPG_List=[] temp='temp' ifpg_check = re.compile("") #create regex for your own naming convention of IFPGs to filter children of AP profile for bd in Bridge_Domains: dq2 = DnQuery('uni/<INSERT TENANT NAME>/<<INSERT AP PROFILE NAME>/epg-'+bd.name) #create query for each BD found with previous query dq2.queryTarget='children' #target children (static ports) dq2.subtreeClassFilter='fvRsPathAtt' StaticPorts = md.query(dq2) #Get Result for epg in StaticPorts: if re.findall(ifpg_check, str(epg.dn)): #Check if entry if InterFace Policy Group temp = re.findall(ifpg_check, str(epg.dn)) #Save IFPG if entry checks out if len(IFPG_List)==0:
def get_children(session, referer): dnQuery = DnQuery(referer.dn) dnQuery.queryTarget = 'children' childMo = session.query(dnQuery) return childMo
def test_DnQuery_init(self): assert isinstance(DnQuery('uni/tn-common'), DnQuery)
def test_DnQuery_dnStr(self): dn = 'uni' dq = DnQuery(dn) assert dq.dnStr == dn