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')) or
                 (excinfo.value.reason == ('user rouser does not have ' +
                                           'domain access to config Mo, ' +
                                           'class fvBD')))
     elif userobject.user == 'rwuser':
         r = moDir.commit(cr)
     else:
         raise NotImplementedError
Esempio n. 2
0
 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
Esempio n. 3
0
class APICHandler():
    def __init__(self):
        self.host = 'https://192.168.1.100'
        self.user = '******'
        self.pwd = 'GDTlabs123'
        self.session = None

    def do_login(self):
        loginSession = LoginSession(self.host, self.user, self.pwd)
        self.session = MoDirectory(loginSession)
        self.session.login()
        # print loginSession.cookie
        return self.session

    def target_location_lookup(self, active_session, location):
        change_location = self.session.lookupByDn(location)
        return change_location

    def update_config(self, active_session, change_location):
        configReq = ConfigRequest()
        configReq.addMo(change_location)
        self.session.commit(configReq)

    def logout(self, active_session):
        self.session.logout()
Esempio n. 4
0
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)
Esempio n. 5
0
def main(host, username, password, pool_name, from_vlan, to_vlan):
    apic = "https://%s" % host
    print("Connecting to APIC : %s" % apic)
    moDir = MoDirectory(LoginSession(apic, username, password))
    moDir.login()
    topMO = moDir.lookupByDn('uni')
    moDir.lookupByDn
    infraInfra = cobra.model.infra.Infra(topMO)
    fvnsVlanInstP = VlanInstP(infraInfra,name=pool_name, allocMode="static")
    temp_from_vlan = "vlan-" + from_vlan
    temp_to_vlan = "vlan-" + to_vlan
    fvnsEncapBlk = EncapBlk(fvnsVlanInstP, temp_from_vlan, temp_to_vlan)

    print(toXMLStr(topMO))
    c = ConfigRequest()
    c.addMo(infraInfra)
    moDir.commit(c)
Esempio n. 6
0
def main(host, username, password, pool_name, from_vlan, to_vlan):
    apic = "https://%s" % host
    print("Connecting to APIC : %s" % apic)
    moDir = MoDirectory(LoginSession(apic, username, password))
    moDir.login()
    topMO = moDir.lookupByDn('uni')
    moDir.lookupByDn
    infraInfra = cobra.model.infra.Infra(topMO)
    fvnsVlanInstP = VlanInstP(infraInfra, name=pool_name, allocMode="static")
    temp_from_vlan = "vlan-" + from_vlan
    temp_to_vlan = "vlan-" + to_vlan
    fvnsEncapBlk = EncapBlk(fvnsVlanInstP, temp_from_vlan, temp_to_vlan)

    print(toXMLStr(topMO))
    c = ConfigRequest()
    c.addMo(infraInfra)
    moDir.commit(c)
 def test_cleanup_user(self, apics, certobject, userobject):
     apic = apics[0]
     user = apics[2]
     password = apics[3]
     secure = False if apics[1] == 'False' else True
     userobject.aaaUser.delete()
     session = LoginSession(apic, user, password, secure=secure)
     moDir = MoDirectory(session)
     moDir.login()
     cr = ConfigRequest()
     cr.addMo(userobject.aaaUser)
     r = moDir.commit(cr)
     assert r == []
Esempio n. 8
0
def main():
    oType, oName = arg_parse()
    session = LoginSession(apicUrl, userName, userPass)
    mo = MoDirectory(session)
    try:
        mo.login()
        print '[+] Login successfull'
    except:
        print '[-] Login Error'
        exit(1)

    if ',' in oName:
        oName = oName.split(',')

    tenantDN = 'uni/tn-' + TENANT
    fvTenant = mo.lookupByDn(tenantDN)
    for name in oName:
        if oType.lower() == 'bd':
            dn = tenantDN + '/BD-' + name
        if oType.lower() == 'epg':
            dn = tenantDN + '/ap-' + APP + '/epg-' + name
        if oType == 'ap':
            dn = tenantDN + '/ap-' + name
        obj = mo.lookupByDn(dn)
        if obj:
            try:
                obj.delete()
                print '[+] Object %s "%s" successfully deleted' % (str(
                    oType.upper()), str(name))
                c = ConfigRequest()
                c.addMo(obj)
                mo.commit(c)
            except:
                print '[-] Error deleting object %s "%s"' % (str(
                    oType.upper()), str(name))
                exit(1)
        else:
            print '[-] %s "%s". Error! No such Object! ' % (str(
                oType.upper()), str(name))
Esempio n. 9
0
 def test_cleanup_user(self, apics, certobject, userobject):
     apic = apics[0]
     user = apics[2]
     password = apics[3]
     secure = False if apics[1] == 'False' else True
     userobject.aaaUser.delete()
     session = LoginSession(apic, user, password, secure=secure)
     moDir = MoDirectory(session)
     moDir.login()
     cr = ConfigRequest()
     cr.addMo(userobject.aaaUser)
     r = moDir.commit(cr)
     assert r.status_code == 200
Esempio n. 10
0
 def test_tn_cleanup(self, apics, certobject, userobject):
     if userobject.user == 'rouser':
         return
     apic = apics[0]
     user = apics[2]
     password = apics[3]
     secure = False if apics[1] == 'False' else True
     uni = Uni('')
     fvTenant = Tenant(uni, name='t')
     fvTenant.delete()
     fvBD = BD(fvTenant, 't-bd')
     fvBD.delete()
     fvAp = Ap(fvTenant, 't-app')
     fvAp.delete()
     session = LoginSession(apic, user, password, secure=secure)
     moDir = MoDirectory(session)
     moDir.login()
     cr = ConfigRequest()
     cr.addMo(fvTenant)
     r = moDir.commit(cr)
     assert r.status_code == 200
Esempio n. 11
0
 def test_tn_cleanup(self, apics, certobject, userobject):
     if userobject.user == 'rouser':
         return
     apic = apics[0]
     user = apics[2]
     password = apics[3]
     secure = False if apics[1] == 'False' else True
     uni = Uni('')
     fvTenant = Tenant(uni, name='t')
     fvTenant.delete()
     fvBD = BD(fvTenant, 't-bd')
     fvBD.delete()
     fvAp = Ap(fvTenant, 't-app')
     fvAp.delete()
     session = LoginSession(apic, user, password, secure=secure)
     moDir = MoDirectory(session)
     moDir.login()
     cr = ConfigRequest()
     cr.addMo(fvTenant)
     r = moDir.commit(cr)
     assert r == []
Esempio n. 12
0
def main(host, port, user, password):

    # CONNECT TO APIC
    print('Initializing connection to APIC...')
    apicUrl = 'http://%s:%d' % (host, port)
    moDir = MoDirectory(LoginSession(apicUrl, user, password))
    moDir.login()

    # Get the top level Policy Universe Directory
    uniMo = moDir.lookupByDn('uni')
    uniInfraMo = moDir.lookupByDn('uni/infra')

    # Create Vlan Namespace
    nsInfo = VMM_DOMAIN_INFO['namespace']
    print("Creating namespace %s.." % (nsInfo['name']))
    fvnsVlanInstPMo = VlanInstP(uniInfraMo, nsInfo['name'], 'dynamic')
    #fvnsArgs = {'from': nsInfo['from'], 'to': nsInfo['to']}
    EncapBlk(fvnsVlanInstPMo, nsInfo['from'], nsInfo['to'], name=nsInfo['name'])
    
    nsCfg = ConfigRequest()
    nsCfg.addMo(fvnsVlanInstPMo)
    moDir.commit(nsCfg)

    # Create VMM Domain
    print('Creating VMM domain...')

    vmmpVMwareProvPMo = moDir.lookupByDn('uni/vmmp-VMware')
    vmmDomPMo = DomP(vmmpVMwareProvPMo, VMM_DOMAIN_INFO['name'])
    
    vmmUsrMo = []
    for usrp in VMM_DOMAIN_INFO['usrs']:
        usrMo = UsrAccP(vmmDomPMo, usrp['name'], usr=usrp['usr'],
                        pwd=usrp['pwd'])
        vmmUsrMo.append(usrMo)

    # Create Controllers under domain
    for ctrlr in VMM_DOMAIN_INFO['ctrlrs']:
        vmmCtrlrMo = CtrlrP(vmmDomPMo, ctrlr['name'], scope=ctrlr['scope'],
                            hostOrIp=ctrlr['ip'])
        # Associate Ctrlr to UserP
        RsAcc(vmmCtrlrMo, tDn=vmmUsrMo[0].dn)
    
    # Associate Domain to Namespace
    RsVlanNs(vmmDomPMo, tDn=fvnsVlanInstPMo.dn)
   
    vmmCfg = ConfigRequest()
    vmmCfg.addMo(vmmDomPMo)
    moDir.commit(vmmCfg)
    print("VMM Domain Creation Completed.")

    print("Starting Tenant Creation..")
    for tenant in TENANT_INFO:
        print("Creating tenant %s.." % (tenant['name']))
        fvTenantMo = Tenant(uniMo, tenant['name'])
        
        # Create Private Network
        Ctx(fvTenantMo, tenant['pvn'])
        
        # Create Bridge Domain
        fvBDMo = BD(fvTenantMo, name=tenant['bd'])
        
        # Create association to private network
        RsCtx(fvBDMo, tnFvCtxName=tenant['pvn'])
        
        # Create Application Profile
        for app in tenant['ap']:
            print('Creating Application Profile: %s' % app['name'])
            fvApMo = Ap(fvTenantMo, app['name'])
            
            # Create EPGs 
            for epg in app['epgs']:
                
                print("Creating EPG: %s..." % (epg['name'])) 
                fvAEPgMo = AEPg(fvApMo, epg['name'])
                
                # Associate EPG to Bridge Domain 
                RsBd(fvAEPgMo, tnFvBDName=tenant['bd'])
                # Associate EPG to VMM Domain
                RsDomAtt(fvAEPgMo, vmmDomPMo.dn)

        # Commit each tenant seperately
        tenantCfg = ConfigRequest()
        tenantCfg.addMo(fvTenantMo)
        moDir.commit(tenantCfg)
    print('All done!')
Esempio n. 13
0
# Obtain the list of tenants and print their names
cq = ClassQuery('fvTenant')
tenants = md.query(cq)

for tenant in tenants:
    print tenant.name

raw_input('Press Enter to continue...')

# Define a new tenant
polUni = md.lookupByDn('uni')
tenant = Tenant(polUni, 'Some-New-Tenant')
tenant.descr = 'This tenant was created by cobra'

# Push the new tenant configuration to the APIC
cr = ConfigRequest()
cr.addMo(polUni)
md.commit(cr)

raw_input('Press Enter to continue...')

# Delete the newly created tenant
tenant.delete()

cr = ConfigRequest()
cr.addMo(polUni)
md.commit(cr)

# Log out of the APIC
md.logout()
Esempio n. 14
0
                                           annotation='',
                                           allocMode='static')
#EncapBlock
fvnsVlanInstPRed = cobra.model.fvns.VlanInstP(infraInfra, 'Group10-VLAN710',
                                              'static')
fvnsEncapBlkRed = cobra.model.fvns.EncapBlk(fvnsVlanInstPRed,
                                            from_=u'vlan-710',
                                            to=u'vlan-710',
                                            allocMode=u'static')

# commit the generated code to APIC
modification = cobra.mit.request.ConfigRequest()
modification.addMo(infraInfra)
modification.addMo(fvnsVlanInstPGreen)
modification.addMo(fvnsVlanInstPRed)
moDir.commit(modification)

#2 Create physical Domains per server

#2.1 Server Green
physDomPGreen = cobra.model.phys.DomP(polUni, name=u'Group10-DOMAIN-GREEN')
aaaDomainRefGreen = cobra.model.aaa.DomainRef(physDomPGreen, name=u'group10')
infraRsVlanNsGreen = cobra.model.infra.RsVlanNs(
    physDomPGreen, tDn=u'uni/infra/vlanns-[Group10-VLAN510]-static')

#2.2 Server Red
physDomPRed = cobra.model.phys.DomP(polUni, name=u'Group10-DOMAIN-RED')
aaaDomainRefRed = cobra.model.aaa.DomainRef(physDomPRed, name=u'group10')
infraRsVlanNsRed = cobra.model.infra.RsVlanNs(
    physDomPRed, tDn=u'uni/infra/vlanns-[Group10-VLAN710]-static')
Esempio n. 15
0
if __name__ == "__main__":

    # Enter tenant, application profile where VMM exists
    tenant = "infra"
    ap = "access"

    # 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())):
Esempio n. 16
0
    #infra.RsHIfPol(portgroupMo,tnFabricHIfPolName='10G')
    #infra.RsLacpPol(portgroupMo,tnLacpLagPolName='LACP-active')
    #infra.RsCdpIfPol(portgroupMo,tnCdpIfPolName='default')
    #infra.RsLldpIfPol(portgroupMo,tnLldpIfPolName="LLDP_ENABLE")
    #infra.RsAttEntP(portgroupMo,tDn=rsaaepntdn)

    # Commit Portgroup
    #portgroupMoCfg=request.ConfigRequest()
    #    portgroupMo.delete()
    #portgroupMoCfg.addMo(portgroupMo)
    #moDir.commit(portgroupMoCfg)

    # Commit contract
    vzBrCP = request.ConfigRequest()
    vzBrCP.addMo(vzBrCP)
    moDir.commit(vzBrCP)

    #Commit L3Out
    l3moCfg = request.ConfigRequest()
    #   l3outMo.delete()
    l3moCfg.addMo(l3outMo)
    moDir.commit(l3moCfg)

    #Commit VRF
    vrfmoCfg = request.ConfigRequest()
    #   vrfMo.delete()
    vrfmoCfg.addMo(vrfMo)
    moDir.commit(vrfmoCfg)

    #Commit L3ExternalDomain
    # Commiting the entire l3outDomMo, but only deleting vlan ranges
Esempio n. 17
0
class apic_base:
    def __init__(self):
        self.session = None
        self.moDir = None
        self.configReq = None
        self.uniMo = None

    """ Authentication """
    def login(self, url, user, password):
        """
        Login to the APIC
        :param url:
        :param user:
        :param password:
        :return:
        """
        self.session = LoginSession(url, user, password)
        self.moDir = MoDirectory(self.session)
        self.moDir.login()
        self.configReq = ConfigRequest()
        self.uniMo = self.moDir.lookupByDn('uni')

    def logout(self):
        """
        Logout from the APIC
        :return:
        """
        self.moDir.logout()

    """ Commits """
    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)

    """ Queries """
    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

    """ Generic Deletes """
    def delete_dn_by_pattern(self, dn_object_list, dn_pattern, recursive):
        """
        Travers a dn list and compare each member with a pattern. If there is a match that object will be removed.
        If recursive is true, the algorithm will also do a recursive look for the children of each object looking
        for the pattern: will stop only when there is no more children to look for.
        :param dn_object_list:
        :param dn_pattern:
        :param recursive:
        :return:
        """
        for dn_object in dn_object_list:
            if dn_pattern in str(dn_object.dn):
                try:
                    self.delete_by_dn(str(dn_object.dn))
                except CommitError as e:
                    print 'Could not delete ' + str(dn_object.dn) + ' -> ' + str(e)
            elif recursive:
                children = self.query_child_objects(dn_object.dn)
                if children is not None:
                    self.delete_dn_by_pattern(children, dn_pattern, recursive)

    def delete_by_dn(self, dn_name):
        """
        Retrieve a mo and it removes it from the APIC
        :param dn_name:
        :return:
        """
        dn_object = self.moDir.lookupByDn(dn_name)
        if dn_object is not None:
            dn_object.delete()
            self.commit(dn_object)

    """ Tenants """
    def create_tenant(self, tenant_name):
        """
        Creates a tenant and commit changes to controller
        :param tenant_name:
        :return:
        """
        fv_tenant_mo = Tenant(self.uniMo, tenant_name)
        self.commit(fv_tenant_mo)
        return fv_tenant_mo

    def delete_tenant(self, tenant_dn):
        """
        Deletes a tenant and commit changes to controller
        :param tenant_dn:
        :return:
        """
        self.delete_by_dn(tenant_dn)

    def get_all_tenants(self):
        """
        Searches all tenants within apic
        :return:
        """
        class_query = ClassQuery('fvTenant')
        tn_list = self.moDir.query(class_query)
        return tn_list

    """ Switch Profiles """
    def delete_switch_profile(self, switch_profile_name):
        """
        Deletes an access policy switch profile
        :param switch_profile_name:
        :return:
        """
        self.delete_by_dn('uni/infra/nprof-' + switch_profile_name)

    """ Bridge domains """
    def create_bd(self, bd_name, tenant_dn, default_gw, **creation_props):
        """
        Creates a BD object. Creates a subnet for the default gateway if it is not None
        :param bd_name:
        :param tenant_dn:
        :param default_gw:
        :param creation_props:
        :return:
        """
        fv_bd_mo = BD(tenant_dn, bd_name, creation_props)
        self.commit(fv_bd_mo)
        if default_gw is not None and len(default_gw) > 0:
            fv_subnet_mo = Subnet(fv_bd_mo, default_gw)
            self.commit(fv_subnet_mo)
        return fv_bd_mo

    def delete_bd(self, bd_dn):
        """
        Removes a bridge domain
        :param bd_dn:
        :return:
        """
        self.delete_by_dn(bd_dn)

    def get_bds_by_tenant(self, tenant_dn):
        """
        Retrieve a list with all bridge domains under a tenant
        :param tenant_dn:
        :return:
        """
        # Queries all the children and then filter them in memory looking for the ones that belongs to the BD class
        tn_children = self.query_child_objects(tenant_dn)
        return filter(lambda x: type(x).__name__ == 'BD', tn_children)

    def get_all_bds(self):
        """
        Returns a list of all bridge domains in the fabric
        :return:
        """
        class_query = ClassQuery('fvBD')
        bd_list = self.moDir.query(class_query)
        return bd_list

    """ Filters """
    def create_filter(self, tenant_dn, filter_name):
        """
        Creates a filter under a tenant
        :param tenant_dn:
        :param filter_name:
        :return:
        """
        vz_filter_mo = Filter(tenant_dn, filter_name)
        self.commit(vz_filter_mo)

    def delete_filter(self, filter_dn):
        """
        Removes a filter from the APIC
        :param filter_dn:
        :return:
        """
        self.delete_by_dn(filter_dn)

    def get_filters_by_tenant(self, tenant_dn):
        """
        Query the filters that are children of a tenant
        :param tenant_dn:
        :return:
        """
        tn_children = self.query_child_objects(tenant_dn)
        # Queries all the children and then filter them in memory looking for the ones that belongs to the Filter class
        return filter(lambda x: type(x).__name__ == 'Filter', tn_children)

    """ Contracts """
    def create_contract(self, tenant_dn, contract_name):
        """
        Creates a contract under a tenant
        :param tenant_dn:
        :param contract_name:
        :return:
        """
        vz_contract = BrCP(tenant_dn, contract_name)
        self.commit(vz_contract)

    def delete_contract(self, contract_dn):
        """
        Removes a contract from the APIC
        :param contract_dn:
        :return:
        """
        self.delete_by_dn(contract_dn)

    def get_contracts_by_tenant(self, tenant_dn):
        """
        Return a list with all the contracts under a tenant
        :param tenant_dn:
        :return:
        """
        tn_children = self.query_child_objects(tenant_dn)
        # Queries all the children and then filter them in memory looking for the ones that belongs to the BrCP class
        return filter(lambda x: type(x).__name__ == 'BrCP', tn_children)

    def assign_contract(self, epg_dn, provider_dn, consumer_dn):
        """
        Assign contracts to an end point group
        :param epg_dn:
        :param provider_dn: Provider contract
        :param consumer_dn: Consumer contract
        :return:
        """
        epg_mo = self.moDir.lookupByDn(epg_dn)
        if len(provider_dn) > 0:
            # Retrieve the provider contract
            provider_mo = self.moDir.lookupByDn(provider_dn)
            # Create the provider relationship with EPG
            rsprov_mo = RsProv(epg_mo, provider_mo.name)
            self.commit(rsprov_mo)
        if len(consumer_dn) > 0:
            # Retrieve the consumer contract
            consumer_mo = self.moDir.lookupByDn(consumer_dn)
            # Creates the consumer relationship with EPG
            rscons_mo = RsCons(epg_mo, consumer_mo.name)
            self.commit(rscons_mo)

    def delete_assign_contract(self, epg_dn):
        """
        Removes the EPG's assigned contracts
        :param epg_dn:
        :return:
        """
        # Queries all the EPG children and then filter them in memory looking for the ones that belongs to the
        # RsProv class
        epg_providers = filter(lambda x: type(x).__name__ == 'RsProv', self.query_child_objects(epg_dn))
        # Queries all the EPG children and then filter them in memory looking for the ones that belongs to the
        # RsCons class
        epg_consumers = filter(lambda x: type(x).__name__ == 'RsCons', self.query_child_objects(epg_dn))
        # For each consumer and provider contract removes the relationship
        for provider in epg_providers:
            provider.delete()
            self.commit(provider)
        for consumer in epg_consumers:
            consumer.delete()
            self.commit(consumer)

    """ Subjects """
    def create_subject(self, filter_dn, contract_dn, subject_name):
        """
        Creates a subject between a contract and a filter
        :param filter_dn:
        :param contract_dn:
        :param subject_name:
        :return:
        """
        subject_dn = Subj(contract_dn, subject_name)
        self.commit(subject_dn)
        filter_mo = self.moDir.lookupByDn(filter_dn)
        rs_filter_subject = RsSubjFiltAtt(subject_dn, filter_mo.name)
        self.commit(rs_filter_subject)

    def get_subjects_by_contract(self, contract_dn):
        """
        Returns all subject under a given contract
        :param contract_dn:
        :return:
        """
        contract_children = self.query_child_objects(contract_dn)
        # Queries all the children and then filter them in memory looking for the ones that belongs to the Subj class
        return filter(lambda x: type(x).__name__ == 'Subj', contract_children)

    def delete_subject(self, subject_dn):
        """
        Removes a subject from the APIC
        :param subject_dn:
        :return:
        """
        self.delete_by_dn(subject_dn)

    """ End Point Groups """
    def create_epg(self, ap_dn, bd_dn, epg_name):
        """
        Creates a EPG and, if the bd_dn parameter is not None, will associate that bridge domain to the EPG
        :param ap_dn: application profile to be used as parent
        :param bd_dn: bridge domain to be associated with the EPG
        :param epg_name:
        :return:
        """
        epg_mo = AEPg(ap_dn, epg_name)
        self.commit(epg_mo)
        if bd_dn is not None and len(bd_dn) > 0:
            # Queries all the children and then filter them in memory looking for the ones that belongs to the RsBd
            #  class. Choose the first one and assign it to the rsbd_mo variable
            rsbd_mo = filter(lambda x: type(x).__name__ == 'RsBd', self.query_child_objects(str(epg_mo.dn)))[0]
            # The tnFvBDName is the attribute that sets the relationship between the bridge domain and the EPG.
            # Looks for the bd_dn object and then assign its name to the tnFvBDName attribute of the rsdb_mo object
            rsbd_mo.tnFvBDName = self.moDir.lookupByDn(bd_dn).name
            self.commit(rsbd_mo)
        return epg_mo

    def delete_epg(self, epg_dn):
        """
        Removes an EPG from the APIC
        :param epg_dn:
        :return:
        """
        self.delete_by_dn(epg_dn)

    def get_epg_by_ap(self, ap_dn):
        """
        Returns a list of end point groups under an application profile
        :param ap_dn:
        :return:
        """
        ap_children = self.query_child_objects(ap_dn)
        # Queries all the children and then filters them in memory looking for the ones that belongs to the AEPg class.
        return filter(lambda x: type(x).__name__ == 'AEPg', ap_children)

    """ Application Profiles """
    def create_ap(self, tenant_dn, ap_name):
        """
        Creates an application profile
        :param tenant_dn:
        :param ap_name:
        :return:
        """
        ap_mo = Ap(tenant_dn, ap_name)
        self.commit(ap_mo)
        return ap_mo

    def delete_ap(self, ap_dn):
        """
        Removes an application profile
        :param ap_dn:
        :return:
        """
        self.delete_by_dn(ap_dn)

    def get_ap_by_tenant(self, tenant_dn):
        """
        Returns a list of application profiles under a tenant
        :param tenant_dn:
        :return:
        """
        tn_children = self.query_child_objects(tenant_dn)
        # Queries all the children and then filters them in memory looking for the ones that belongs to the Ap class.
        return filter(lambda x: type(x).__name__ == 'Ap', tn_children)
    # and then use these variables in your script.
    #
    # Example:
    # import os
    # PASSWORD = os.getenv('MY_SECURE_PASSWORD')
    #
    # Here the environment variable is called 'MY_SECURE_PASSWORD' which
    # contains your secret password.
    USERNAME = "******"
    PASSWORD = "******"

    # Connecting and Authenticating - create a new session and login
    loginSession = LoginSession(APIC_URL, USERNAME, PASSWORD)
    mo_dir = MoDirectory(loginSession)
    mo_dir.login()

    # Build a new configuration object
    tenant_name = 'Tenant1'
    uni_mo = mo_dir.lookupByDn('uni')
    new_mo = Tenant(uni_mo, name=tenant_name)

    # Create a new config request
    tenant_cfg = ConfigRequest()
    tenant_cfg.addMo(new_mo)

    # Commit the config request
    mo_dir.commit(tenant_cfg)

    # Get the tenant by is's name
    tenant = mo_dir.lookupByDn(f'uni/{tenant_name}')
Esempio n. 19
0
class cobra_apic_base:
    def __init__(self):
        self.session = None
        self.moDir = None
        self.configReq = None
        self.uniMo = None

    """ Authentication """
    def login(self, url, user, password):
        """
        Login to the APIC
        :param url:
        :param user:
        :param password:
        :return:
        """
        self.apic_url = url
        self.apic_user = user
        self.session = LoginSession(url, user, password)
        self.moDir = MoDirectory(self.session)
        self.moDir.login()
        self.configReq = ConfigRequest()
        self.uniMo = self.moDir.lookupByDn('uni')

    def logout(self):
        """
        Logout from the APIC
        :return:
        """
        self.moDir.logout()

    """ Commits """
    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)

    """ Queries """
    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

    """ Generic Deletes """
    def delete_dn_by_pattern(self, dn_object_list, dn_pattern, recursive):
        """
        Travers a dn list and compare each member with a pattern. If there is a match that object will be removed.
        If recursive is true, the algorithm will also do a recursive look for the children of each object looking
        for the pattern: will stop only when there is no more children to look for.
        :param dn_object_list:
        :param dn_pattern:
        :param recursive:
        :return:
        """
        for dn_object in dn_object_list:
            if dn_pattern in str(dn_object.dn):
                try:
                    self.delete_by_dn(str(dn_object.dn))
                except CommitError as e:
                    print 'Could not delete ' + str(dn_object.dn) + ' -> ' + str(e)
            elif recursive:
                children = self.query_child_objects(dn_object.dn)
                if children is not None:
                    self.delete_dn_by_pattern(children, dn_pattern, recursive)

    def delete_by_dn(self, dn_name):
        """
        Retrieve a mo and it removes it from the APIC
        :param dn_name:
        :return:
        """
        dn_object = self.moDir.lookupByDn(dn_name)
        if dn_object is not None:
            dn_object.delete()
            self.commit(dn_object)

    """ Tenants """
    def create_tenant(self, tenant_name):
        """
        Creates a tenant and commit changes to controller
        :param tenant_name:
        :return:
        """
        fv_tenant_mo = Tenant(self.uniMo, tenant_name)
        self.commit(fv_tenant_mo)
        return fv_tenant_mo

    def delete_tenant(self, tenant_dn):
        """
        Deletes a tenant and commit changes to controller
        :param tenant_dn:
        :return:
        """
        self.delete_by_dn(tenant_dn)

    def get_all_tenants(self):
        """
        Searches all tenants within apic
        :return:
        """
        class_query = ClassQuery('fvTenant')
        tn_list = self.moDir.query(class_query)
        return tn_list

    """ Switch Profiles """
    def delete_switch_profile(self, switch_profile_name):
        """
        Deletes an access policy switch profile
        :param switch_profile_name:
        :return:
        """
        self.delete_by_dn('uni/infra/nprof-' + switch_profile_name)

    """ Bridge domains """
    def create_bd(self, bd_name, tenant_dn, default_gw, **creation_props):
        """
        Creates a BD object. Creates a subnet for the default gateway if it is not None
        :param bd_name:
        :param tenant_dn:
        :param default_gw:
        :param creation_props:
        :return:
        """
        fv_bd_mo = BD(tenant_dn, bd_name, creation_props)
        self.commit(fv_bd_mo)
        if default_gw is not None and len(default_gw) > 0:
            fv_subnet_mo = Subnet(fv_bd_mo, default_gw)
            self.commit(fv_subnet_mo)
        return fv_bd_mo

    def delete_bd(self, bd_dn):
        """
        Removes a bridge domain
        :param bd_dn:
        :return:
        """
        self.delete_by_dn(bd_dn)

    def get_bds_by_tenant(self, tenant_dn):
        """
        Retrieve a list with all bridge domains under a tenant
        :param tenant_dn:
        :return:
        """
        # Queries all the children and then filter them in memory looking for the ones that belongs to the BD class
        tn_children = self.query_child_objects(tenant_dn)
        return filter(lambda x: type(x).__name__ == 'BD', tn_children)

    def get_all_bds(self):
        """
        Returns a list of all bridge domains in the fabric
        :return:
        """
        class_query = ClassQuery('fvBD')
        bd_list = self.moDir.query(class_query)
        return bd_list

    """ Filters """
    def create_filter(self, tenant_dn, filter_name):
        """
        Creates a filter under a tenant
        :param tenant_dn:
        :param filter_name:
        :return:
        """
        vz_filter_mo = Filter(tenant_dn, filter_name)
        self.commit(vz_filter_mo)

    def delete_filter(self, filter_dn):
        """
        Removes a filter from the APIC
        :param filter_dn:
        :return:
        """
        self.delete_by_dn(filter_dn)

    def get_filters_by_tenant(self, tenant_dn):
        """
        Query the filters that are children of a tenant
        :param tenant_dn:
        :return:
        """
        tn_children = self.query_child_objects(tenant_dn)
        # Queries all the children and then filter them in memory looking for the ones that belongs to the Filter class
        return filter(lambda x: type(x).__name__ == 'Filter', tn_children)

    """ Contracts """
    def create_contract(self, tenant_dn, contract_name):
        """
        Creates a contract under a tenant
        :param tenant_dn:
        :param contract_name:
        :return:
        """
        vz_contract = BrCP(tenant_dn, contract_name)
        self.commit(vz_contract)

    def delete_contract(self, contract_dn):
        """
        Removes a contract from the APIC
        :param contract_dn:
        :return:
        """
        self.delete_by_dn(contract_dn)

    def get_contracts_by_tenant(self, tenant_dn):
        """
        Return a list with all the contracts under a tenant
        :param tenant_dn:
        :return:
        """
        tn_children = self.query_child_objects(tenant_dn)
        # Queries all the children and then filter them in memory looking for the ones that belongs to the BrCP class
        return filter(lambda x: type(x).__name__ == 'BrCP', tn_children)

    def assign_contract(self, epg_dn, provider_dn, consumer_dn):
        """
        Assign contracts to an end point group
        :param epg_dn:
        :param provider_dn: Provider contract
        :param consumer_dn: Consumer contract
        :return:
        """
        epg_mo = self.moDir.lookupByDn(epg_dn)
        if len(provider_dn) > 0:
            # Retrieve the provider contract
            provider_mo = self.moDir.lookupByDn(provider_dn)
            # Create the provider relationship with EPG
            rsprov_mo = RsProv(epg_mo, provider_mo.name)
            self.commit(rsprov_mo)
        if len(consumer_dn) > 0:
            # Retrieve the consumer contract
            consumer_mo = self.moDir.lookupByDn(consumer_dn)
            # Creates the consumer relationship with EPG
            rscons_mo = RsCons(epg_mo, consumer_mo.name)
            self.commit(rscons_mo)

    def delete_assign_contract(self, epg_dn):
        """
        Removes the EPG's assigned contracts
        :param epg_dn:
        :return:
        """
        # Queries all the EPG children and then filter them in memory looking for the ones that belongs to the
        # RsProv class
        epg_providers = filter(lambda x: type(x).__name__ == 'RsProv', self.query_child_objects(epg_dn))
        # Queries all the EPG children and then filter them in memory looking for the ones that belongs to the
        # RsCons class
        epg_consumers = filter(lambda x: type(x).__name__ == 'RsCons', self.query_child_objects(epg_dn))
        # For each consumer and provider contract removes the relationship
        for provider in epg_providers:
            provider.delete()
            self.commit(provider)
        for consumer in epg_consumers:
            consumer.delete()
            self.commit(consumer)

    """ Subjects """
    def create_subject(self, filter_dn, contract_dn, subject_name):
        """
        Creates a subject between a contract and a filter
        :param filter_dn:
        :param contract_dn:
        :param subject_name:
        :return:
        """
        subject_dn = Subj(contract_dn, subject_name)
        self.commit(subject_dn)
        filter_mo = self.moDir.lookupByDn(filter_dn)
        rs_filter_subject = RsSubjFiltAtt(subject_dn, filter_mo.name)
        self.commit(rs_filter_subject)

    def get_subjects_by_contract(self, contract_dn):
        """
        Returns all subject under a given contract
        :param contract_dn:
        :return:
        """
        contract_children = self.query_child_objects(contract_dn)
        # Queries all the children and then filter them in memory looking for the ones that belongs to the Subj class
        return filter(lambda x: type(x).__name__ == 'Subj', contract_children)

    def delete_subject(self, subject_dn):
        """
        Removes a subject from the APIC
        :param subject_dn:
        :return:
        """
        self.delete_by_dn(subject_dn)

    """ End Point Groups """
    def create_epg(self, ap_dn, bd_dn, epg_name):
        """
        Creates a EPG and, if the bd_dn parameter is not None, will associate that bridge domain to the EPG
        :param ap_dn: application profile to be used as parent
        :param bd_dn: bridge domain to be associated with the EPG
        :param epg_name:
        :return:
        """
        epg_mo = AEPg(ap_dn, epg_name)
        self.commit(epg_mo)
        if bd_dn is not None and len(bd_dn) > 0:
            # Queries all the children and then filter them in memory looking for the ones that belongs to the RsBd
            #  class. Choose the first one and assign it to the rsbd_mo variable
            rsbd_mo = filter(lambda x: type(x).__name__ == 'RsBd', self.query_child_objects(str(epg_mo.dn)))[0]
            # The tnFvBDName is the attribute that sets the relationship between the bridge domain and the EPG.
            # Looks for the bd_dn object and then assign its name to the tnFvBDName attribute of the rsdb_mo object
            rsbd_mo.tnFvBDName = self.moDir.lookupByDn(bd_dn).name
            self.commit(rsbd_mo)
        return epg_mo

    def delete_epg(self, epg_dn):
        """
        Removes an EPG from the APIC
        :param epg_dn:
        :return:
        """
        self.delete_by_dn(epg_dn)

    def get_epg_by_ap(self, ap_dn):
        """
        Returns a list of end point groups under an application profile
        :param ap_dn:
        :return:
        """
        ap_children = self.query_child_objects(ap_dn)
        # Queries all the children and then filters them in memory looking for the ones that belongs to the AEPg class.
        return filter(lambda x: type(x).__name__ == 'AEPg', ap_children)

    """ Application Profiles """
    def create_ap(self, tenant_dn, ap_name):
        """
        Creates an application profile
        :param tenant_dn:
        :param ap_name:
        :return:
        """
        ap_mo = Ap(tenant_dn, ap_name)
        self.commit(ap_mo)
        return ap_mo

    def delete_ap(self, ap_dn):
        """
        Removes an application profile
        :param ap_dn:
        :return:
        """
        self.delete_by_dn(ap_dn)

    def get_ap_by_tenant(self, tenant_dn):
        """
        Returns a list of application profiles under a tenant
        :param tenant_dn:
        :return:
        """
        tn_children = self.query_child_objects(tenant_dn)
        # Queries all the children and then filters them in memory looking for the ones that belongs to the Ap class.
        return filter(lambda x: type(x).__name__ == 'Ap', tn_children)

    def __repr__(self):
        return 'Connected to %s with userid: %s' % (self.apic_url, self.apic_user)
        print('Creating Application Profile: %s' % app['name'])
        fvApMo = Ap(fvTenantMo, app['name'])

        # Create EPGs
        for epg in app['epgs']:

            print("Creating EPG: %s..." % (epg['name']))
            fvAEPgMo = AEPg(fvApMo, epg['name'])

            # Associate EPG to Bridge Domain
            RsBd(fvAEPgMo, tnFvBDName=tenant['bd'])

    # Commit each tenant separately
    tenantCfg = ConfigRequest()
    tenantCfg.addMo(fvTenantMo)
    moDir.commit(tenantCfg)
print('All tenants created.\n**')

print("Get the tenants by class.\n**")
tnQuery = ClassQuery('fvTenant')
tnMos = moDir.query(tnQuery)
for tnMo in tnMos:
    print(tnMo.dn)

print("Get the tenants by DN and delete them.\n**")
for tenant in TENANT_INFO:
    tnMo = moDir.lookupByDn('uni/tn-{0}'.format(tenant['name']))
    print(tnMo.name)
    print("Deleting tenant %s.." % (tenant['name']))
    tnMo.delete()
    tenantCfg = ConfigRequest()
Esempio n. 21
0
apicUsername = '******' + TacacsUser
apicPassword = TacacsPassword
loginSession = LoginSession(apicUrl, apicUsername, apicPassword)

# Create a session with the APIC and login
moDir = MoDirectory(loginSession)
moDir.login()

#Prompt User for Tenant to create BD in.
#UserTenant = raw_input('Create BD in which tenant? ')

# Start at the Tenant of MIT tree
TenantMo = moDir.lookupByDn((r'uni/tn-ExampleSdkTenant'))

# Create a new BD MO and connect it as a Child object to the Tenant MO
fvBDMo = fvModels.BD(TenantMo, name='myBD')

# Associate the VRF under the new BD
fvRsCtxMo = fvModels.RsCtx(fvBDMo, tnFvCtxName='myVRF')

# Add Subnet to BD
fvSubnetMo = fvModels.Subnet(fvBDMo, ip='10.20.30.1/24')

# Create a new configuration request to the APIC and pass in the new Tenant MO (including its children MOs)
# Commit the changes to the APIC
cfgRequest = ConfigRequest()
cfgRequest.addMo(fvBDMo)
moDir.commit(cfgRequest)

# Log Out once the request is complete
moDir.logout()
Esempio n. 22
0
if lldpAdjEps:
    print "Found adjacent hosts via LLDP:"
for adjEp in lldpAdjEps:
    print str(adjEp.dn) + " is connected to " + str(adjEp.sysName)

infraInfra = Infra(uniMo)

for adjEp in lldpAdjEps:
    if is_leaf(str(adjEp.dn)):
        infraHPathS = HPathS(infraInfra,
                             name="adjEp-{0}-{1}".format(
                                 str(adjEp.sysName),
                                 get_node_name(str(adjEp.dn))),
                             descr=str(adjEp.sysName))
        infraRsHPathAtt = RsHPathAtt(infraHPathS,
                                     tDn=concat_path_ep(str(adjEp.dn)))
    else:
        infraSHPathS = SHPathS(infraInfra,
                               name="adjEp-{0}-{1}".format(
                                   str(adjEp.sysName),
                                   get_node_name(str(adjEp.dn))),
                               descr=str(adjEp.sysName))
        infraRsSHPathAtt = RsSHPathAtt(infraSHPathS,
                                       tDn=concat_path_ep(str(adjEp.dn)))

configReq = ConfigRequest()
configReq.addMo(infraInfra)
moDir.commit(configReq)

moDir.logout()
Esempio n. 23
0
class CobraClient(object):
    def __init__(self, hosts, user, password, ssl, verify=False, request_timeout=90):
        protocol = 'https' if ssl else 'http'


        LOG.info(hosts)

        self.api_base = collections.deque(['%s://%s/api' % (protocol, host) for host in hosts])
        self.verify = verify
        self.timeout = 90
        self.user = user
        self.password = password
        self.login()

    def login(self):
        # TODO handle multiple hosts
        LOG.info("ACI Login")
        login_session = LoginSession(self.api_base[0], self.user, self.password)
        self.mo_dir = MoDirectory(login_session)
        self.mo_dir.login()

        LOG.info("Login session created, will expire at {} in {} seconds".format(login_session.refreshTime,login_session.refreshTimeoutSeconds))


    def logout(self):
        self.mo_dir.logout()

    def lookupByDn(self, dn):
        retries = 0
        while retries < RETRY_LIMIT:
            try:
                uni_mo = self.mo_dir.lookupByDn(dn)
                return uni_mo
            except SSLError as e:
                self._retry(retries, e)
            except QueryError  as e:
                LOG.info("Lookup to ACI failed due to {}:{} retrying {} of {}".format(e.error, e.reason,retries,RETRY_LIMIT))
                if e.error == 403:
                    self.mo_dir.login()
                    LOG.info("New login session created")
                    self._retry(retries, e)
                else:
                    raise e

    def commit(self, managed_objects):
        retries = 0
        while retries < RETRY_LIMIT:
            try:
                config_request = ConfigRequest()

                if isinstance(managed_objects, list):
                    for mos in managed_objects:
                        config_request.addMo(mos)
                else:
                    config_request.addMo(managed_objects)

                return self.mo_dir.commit(config_request)
            except SSLError as e:
                self._retry(retries, e)
            except CommitError  as e:
                LOG.info("Commit to ACI failed due to {}:{} retrying  {} of {}".format(e.error, e.reason, retries,RETRY_LIMIT))
                if e.error == 403:
                    self.mo_dir.login()
                    LOG.info("New login session created")
                    self._retry(retries, e)
                else:
                    raise e

    def _retry(self, retries, e):
        retries += 1
        if retries >= RETRY_LIMIT:
            raise e

    def mo_exists(self, dn):
        mo = self.lookupByDn(dn)
        return mo is not None

    def uni_mo(self):
        return self.lookupByDn('uni')

    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 get_tenant(self,tenant_name):
        tenant_mo = Tenant(self.uni_mo(), tenant_name)
        if self.mo_exists(tenant_mo.dn):
            return tenant_mo

        return None

    def get_or_create_tenant(self, tenant_name):
        tenant_mo = Tenant(self.uni_mo(), tenant_name)

        if not self.mo_exists(tenant_mo.dn):
            LOG.info("Configured tenant {} is missing, creating it now".format(tenant_mo.dn))
            self.commit(tenant_mo)
        else:
            LOG.info("Using existing ACI tenant {}".format(tenant_mo.dn))

        return tenant_mo
Esempio n. 24
0
            Ctx(fvTenantMo, vrf.getName(), descr=vrf.getDesc())

            for bd in vrf.getBds():
                print "Creating BD [{}]".format(bd.getName())
                fvBDMo = BD(fvTenantMo, bd.getName(), descr=bd.getDesc())
                # Create association to VRF
                RsCtx(fvBDMo, tnFvCtxName=vrf.getName())

            for ap in vrf.getAppProfiles():
                print "Creating App Profile [{}]".format(ap.getName())
                fvApMo = Ap(fvTenantMo, ap.getName(), descr=ap.getDesc())

                for epg in ap.getEpgs():
                    print "Creating EPG [{}]".format(epg.getName())
                    fvAEPgMo = AEPg(fvApMo, epg.getName(), descr=epg.getDesc())
                    # Associate EPG to Bridge Domain
                    RsBd(fvAEPgMo, tnFvBDName=epg.getBdName())
                    # Associate EPG to VMM Domain
                    #RsDomAtt(fvAEPgMo, vmmDomPMo.dn)

        tenantCfg = ConfigRequest()
        tenantCfg.addMo(fvTenantMo)
        print "tenantCfg data: " + tenantCfg.data
        md.commit(tenantCfg)

    md.logout()

else:
    print "User cancelled the script! Good bye ..."

# end of main program
from cobra.mit.access import MoDirectory
from cobra.mit.session import LoginSession
from cobra.model.fv import Ctx
from cobra.model.fv import *
from cobra.mit.request import *

# APIC Login Credentials
apicUrl = 'https://URL-of-APIC'
loginSession = LoginSession(apicUrl, 'username', 'password')

# APIC Managed Object Directory - starting at the top
moDir = MoDirectory(loginSession)

# Program asks for the name of the tenant to be created
TenantName = raw_input("Tenant Name: ")

moDir.login()

# Create new Tenant 
uniMo = moDir.lookupByDn('uni')
fvTenantMo = Tenant(uniMo, TenantName)

# Create new Private network/VRF under the new Tenant
fvContextMo = Ctx(fvTenantMo, 'myVRF')

# Add the new Tenant and its VRF Configuration to the APIC and commit these changes
cfgRequest = ConfigRequest()
cfgRequest.addMo(fvTenantMo)
moDir.commit(cfgRequest)

moDir.logout()
Esempio n. 26
0
    # Enter tenant, application profile where VMM exists
    tenant = "infra"
    ap = "access"

    # 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)