コード例 #1
0
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()
コード例 #2
0
 def main_function(self):
     # Query a tenant
     self.check_if_tenant_exist()
     fv_bd = self.check_if_mo_exist('uni/tn-'+self.tenant+'/BD-', self.bridge_domain, BD, description='Bridge Domain', return_false=True, set_mo=False)
     if not fv_bd:
         fv_bd = BD(self.mo, self.bridge_domain)
     create_subnet(fv_bd, self.subnet)
コード例 #3
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
コード例 #4
0
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)
コード例 #5
0
def createBridgeDomain(fv_tenant, bridge_domain, subnet_ip, private_network):
    """Create a Bridge Domain. A private layer 2 bridge domain (BD) consists of a set of physical or virtual ports. Each bridge domain must be linked to a context and have at least one subnet. """
    # Create a bridge domain
    fv_bd = BD(fv_tenant, bridge_domain)

    # Create a subnet
    fv_subnet = Subnet(fv_bd, subnet_ip)

    # Connect the bridge domain to a network
    fv_rsctx = RsCtx(fv_bd, tnFvCtxName=private_network)
コード例 #6
0
ファイル: apic_epg_v6.py プロジェクト: cda75/aci
def create_BD(tenant, bdName, vNum, vrf, subnet):
    try:
        fvBD = BD(tenant, name=bdName, arpFlood=u'true')
        Subnet(fvBD, ctrl=u'unspecified', ip=subnet, virtual=u'true')
        RsCtx(fvBD, tnFvCtxName=vrf)
        CONFIG.addMo(fvBD)
        print '[+] Bridge Domain %s created successfully' % bdName
    except:
        print '[-] Error creating Bridge Domain'
        exit(1)
コード例 #7
0
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
コード例 #8
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
コード例 #9
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 == []
コード例 #10
0
ファイル: apicagent.py プロジェクト: rchirakk/aci-gw
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']
コード例 #11
0
ファイル: cobra_apic_base.py プロジェクト: castropr/NCAplus
 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
コード例 #12
0
def create_3tier_application(modir, tenant_name):
    policy_universe = modir.lookupByDn('uni')
    fv_tenant = Tenant(policy_universe, tenant_name)

    # create context
    fv_ctx = Ctx(fv_tenant, CTX_NAME)

    #
    fv_bd = BD(fv_tenant, 'BD1')

    #
    fv_rs_ctx = RsCtx(fv_bd)
    fv_rs_ctx.__setattr__('tnFvCtxName', 'Apple-Router')
    fv_subnet_10 = Subnet(fv_bd,'10.0.0.1/24', scope='public')
    fv_subnet_20 = Subnet(fv_bd, '20.0.0.1/24', scope='public')
    fv_subnet_30 = Subnet(fv_bd, '30.0.0.1/24', scope='public')
    fv_subnet_40 = Subnet(fv_bd, '40.0.0.1/24', scope='public')

    #
    fv_ap = Ap(fv_tenant, '3-TierApp')

    fv_aepg_client = AEPg(fv_ap, 'Client')
    fv_rs_bd_client = RsBd(fv_aepg_client, tnFvBDName='BD1')
#    fv_rs_bd_client.__setattr__('tnFvBDName', 'BD1')
    fv_rs_cons_webct_client = RsCons(fv_aepg_client, 'WebCt')

    fv_aepg_web = AEPg(fv_ap, 'Web')
    fv_rs_bd_web = RsBd(fv_aepg_web, tnFvBDName='BD1')
    fv_rs_cons_webct_web = RsProv(fv_aepg_web, 'WebCt')
    fv_rs_cons_appct_web = RsCons(fv_aepg_web, 'AppCt')

    fv_aepg_app = AEPg(fv_ap, 'App')
    fv_rs_bd_app = RsBd(fv_aepg_app, tnFvBDName='DB1')
    fv_rs_cons_webct_app = RsProv(fv_aepg_app, 'WebCt')
    fv_rs_cons_appct_app = RsCons(fv_aepg_app, 'AppCt')

    fv_aepg_db = AEPg(fv_ap, 'DB')
    fv_rs_bd_db = RsBd(fv_aepg_db, tnFvBDName='BD1')
    fv_rs_prov_db = RsProv(fv_aepg_db, 'DbCt')

    print toXMLStr(policy_universe, prettyPrint=True)
    # Commit the change using a ConfigRequest object
    configReq = ConfigRequest()
    configReq.addMo(policy_universe)
    modir.commit(configReq)
コード例 #13
0
def add_bridge_domain_subnet(modir, tenant_name, bridge_domain, subnet_ip, network_name):
    """Build a bridge domain and its associated subnet"""

    # Query to a tenant
    fv_tenant = modir.lookupByDn('uni/tn-' + tenant_name)

    # Create a bridge domain
    fv_bd = BD(fv_tenant, bridge_domain)

    # Create a subnet
    fv_subnet = Subnet(fv_bd, subnet_ip)

    # Connect the bridge domain to a network
    if isinstance(modir.lookupByDn('uni/tn-' + tenant_name + '/ctx-' + network_name), Ctx):
        fv_rsctx = RsCtx(fv_bd, tnFvCtxName=network_name)
    else:
        print 'Network', network_name, 'does not existe.'

    print_query_xml(fv_tenant)
    commit_change(modir, fv_tenant)
コード例 #14
0
class Test_mit_request_ConfigRequest(object):

    def test_ConfigRequest_init(self):
        assert isinstance(ConfigRequest(), ConfigRequest)

    def test_ConfigRequest_options(self):
        cid = '1234567890'
        expectedOptions = ''
        cr =  ConfigRequest()
        cr.id = cid
        expectedOptions += '_dc=' + cid
        assert cr.options == expectedOptions

    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 test_ConfigRequest_data_raises(self):
        cr = ConfigRequest()
        with pytest.raises(CommitError):
            abc = cr.data

    def test_ConfigRequest_xmldata(self):
        expected1 = ('<?xml version="1.0" encoding="UTF-8"?>\n' +
                    '<fvTenant name=\'test\' status=\'created,modified\'>' +
                    '</fvTenant>')
        expected2 = ('<?xml version="1.0" encoding="UTF-8"?>\n' +
                    '<fvTenant status=\'created,modified\' name=\'test\'>' +
                    '</fvTenant>')
        polUni = Uni('')
        fvTenant = Tenant(polUni, 'test')
        cr = ConfigRequest()
        cr.addMo(fvTenant)
        assert (cr.xmldata == expected1 or cr.xmldata == expected2)

    def test_ConfigRequest_xmldata_raises(self):
        cr = ConfigRequest()
        with pytest.raises(CommitError):
            abc = cr.xmldata

   # expected is None means you expect the same value returned that was set
    @pytest.mark.parametrize("value", [
        ('full'),
        ('modified'),
        ('no'),
    ])
    def test_ConfigRequest_subtree(self, value):
        cr = ConfigRequest()
        cr.subtree = value
        assert cr.subtree == value

    def test_ConfigRequest_subtree_raises(self):
        cr = ConfigRequest()
        with pytest.raises(ValueError):
            cr.subtree = 'children'

    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)

    # addMo is tested in test_ConfigRequest_requestargs but we still need
    # branch testing.  See test_ConfigRequest_addMo_raises_* methods
    #def test_ConfigRequest_addMo(self):

    def test_ConfigRequest_addMo_raises_no_context(self):
        polUni = Uni('')
        cr = ConfigRequest()
        with pytest.raises(ValueError):
            cr.addMo(polUni)

    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_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_removeMo_and_hasMo_negative(self):
        fvTenant = Tenant('uni', 'testing')
        fvnsVlanInstP = VlanInstP('uni/infra', 'namespace1', 'dynamic')
        cr = ConfigRequest()
        cr.addMo(fvTenant)
        cr.removeMo(fvTenant)
        cr.addMo(fvnsVlanInstP)
        assert not cr.hasMo(fvTenant.dn)

    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_removeMo_raises(self):
        fvTenant = Tenant('uni', 'testing')
        cr = ConfigRequest()
        with pytest.raises(KeyError):
            cr.removeMo(fvTenant)

    @pytest.mark.parametrize("mos, expected", [
        ([None], None),
        ([], LooseNode(u'topology', u"101")),
        ([BD(u'uni/tn-testing', u'test')], Tenant(u'uni', u'testing')),
    ])
    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

    @pytest.mark.parametrize("sessionUrl,mo,dc,requestType", [
        ('http://1.1.1.1', Tenant('uni', 'testing'), None, 'xml'),
        ('http://1.1.1.1', Tenant('uni', 'testing'), None, 'json'),
        ('http://1.1.1.1', Tenant('uni', 'testing'), '1', 'xml'),
        ('http://1.1.1.1', Tenant('uni', 'testing'), '1', 'json'),
    ])
    def test_ConfigRequest_getUriPathAndOptions(self, sessionUrl, mo, dc,
                                                requestType):
        session = LoginSession(sessionUrl, 'admin', 'password',
                               requestFormat=requestType)

        cr = ConfigRequest()
        cr.addMo(mo)
        expected = '/api/mo/' + str(mo.dn) + '.' + requestType
        if dc is not None:
            cr.id =  dc
            expected += '?_dc=' + dc
        assert cr.getUriPathAndOptions(session) == expected


    @pytest.mark.parametrize("sessionUrl,mo,requestType", [
        ("http://1.1.1.1", Tenant('uni', 'testing'), 'xml'),
        ("http://1.1.1.1", Tenant('uni', 'testing'), 'json'),
        ("http://2.2.2.2", VlanInstP('uni/infra', 'namespace1', 'dynamic'),
            'xml'),
        ("http://2.2.2.2", VlanInstP('uni/infra', 'namespace1', 'dynamic'),
            'json'),
    ])
    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
コード例 #15
0
moDir = MoDirectory(LoginSession('https://apic', 'admin', 'cisco123'))
moDir.login()

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

print("Starting Tenant Creation.\n**")
for tenant in TENANT_INFO:
    print("Creating tenant %s.." % (tenant['name']))
    fvTenantMo = Tenant(uniMo, tenant['name'])

    # Create Private Network
    Ctx(fvTenantMo, tenant['ctx'])

    # Create Bridge Domain
    fvBDMo = BD(fvTenantMo, name=tenant['bd'])

    # Create association to private network
    RsCtx(fvBDMo, tnFvCtxName=tenant['ctx'])

    # 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'])
コード例 #16
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!')
コード例 #17
0
    md.login()
    print "Trying to log in ... successful"
    # Get the top level Policy Universe Directory
    uniMo = md.lookupByDn('uni')

    for tenant in tenants:
        print "Creating Tenant [{}]".format(tenant.getName())
        fvTenantMo = Tenant(uniMo, tenant.getName(), descr=tenant.getDesc())

        for vrf in tenant.getVrfs():
            print "Creating VRF [{}]".format(vrf.getName())
            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)
コード例 #18
0
def tenant_policy(host, user, password):
    print('[BEG] Tenant Configuration')
    moDir = apic_login(host, user, password)

    uniMo = moDir.lookupByDn('uni')

    fvTenantMo = Tenant(uniMo, 'Cobra-Demo')

    print('--- Building VRF(s)')
    # Create Private Network
    vrf1 = Ctx(fvTenantMo, "DC_INSIDE")
    vrf2 = Ctx(fvTenantMo, "DC_OUTISDE")

    print('--- Building Bridge Domain(s)')
    # Create Bridge Domain & Subnets
    fvBDMo1 = BD(fvTenantMo, "SERVER_BD1")
    fvSubnet = Subnet(fvBDMo1,
                      name=u'Sub1',
                      ip=u'106.0.1.1/24',
                      preferred=u'no',
                      virtual=u'no')
    fvSubnet = Subnet(fvBDMo1,
                      name=u'Sub2',
                      ip=u'106.0.2.1/24',
                      preferred=u'no',
                      virtual=u'no')

    print('--- Adding Subnets to Bridge Domain(s)')
    # Create Bridge Domain & Subnets
    fvBDMo2 = BD(fvTenantMo, "SERVER_BD2")
    fvSubnet = Subnet(fvBDMo2,
                      name=u'Sub3',
                      ip=u'106.0.3.1/24',
                      preferred=u'no',
                      virtual=u'no',
                      scope=u'public')
    fvSubnet = Subnet(fvBDMo2,
                      name=u'Sub4',
                      ip=u'106.0.4.1/24',
                      preferred=u'no',
                      virtual=u'yes')
    fvSubnet = Subnet(fvBDMo2,
                      name=u'Sub5',
                      ip=u'106.0.5.1/24',
                      preferred=u'no',
                      virtual=u'no',
                      scope=u'public')

    print('--- Adding Bridge Domain(s) to VRF(s)')
    # Create association to private network
    fv1RsCtx = RsCtx(fvBDMo1, tnFvCtxName=vrf1.name)
    fv2RsCtx = RsCtx(fvBDMo2, tnFvCtxName=vrf1.name)

    print('--- Building Web Filter')
    # Build Web Filters
    vzFilter1 = Filter(fvTenantMo, name=u'Web-Filters')
    vzEntry = Entry(vzFilter1,
                    applyToFrag=u'no',
                    dToPort=u'https',
                    prot=u'tcp',
                    stateful=u'no',
                    etherT=u'ip',
                    dFromPort=u'https',
                    name=u'https')
    vzEntry2 = Entry(vzFilter1,
                     applyToFrag=u'no',
                     dToPort=u'https',
                     prot=u'tcp',
                     stateful=u'no',
                     etherT=u'ip',
                     dFromPort=u'https',
                     name=u'https')

    print('--- Building App Filter')
    # Build App Filters
    vzFilter2 = Filter(fvTenantMo, name=u'App-Filters')
    vzEntry = Entry(vzFilter2,
                    applyToFrag=u'no',
                    dToPort=u'8080',
                    prot=u'tcp',
                    stateful=u'no',
                    etherT=u'ip',
                    dFromPort=u'8080',
                    name=u'tcp8080')
    vzEntry2 = Entry(vzFilter2,
                     dToPort=u'8443',
                     prot=u'tcp',
                     stateful=u'no',
                     etherT=u'ip',
                     dFromPort=u'8443',
                     name=u'tcp8443')

    print('--- Creating Contract(s)')
    #Create Contracts
    httpContract = BrCP(fvTenantMo, 'WEB')
    vzSubjMo = Subj(httpContract, 'Web-Ports')
    RsSubjFiltAtt(vzSubjMo, tnVzFilterName=vzFilter1.name)
    RsSubjFiltAtt(vzSubjMo, tnVzFilterName='icmp')

    appContract = BrCP(fvTenantMo, 'APP')
    vzSubjMo = Subj(appContract, 'App-Ports')
    RsSubjFiltAtt(vzSubjMo, tnVzFilterName=vzFilter2.name)
    RsSubjFiltAtt(vzSubjMo, tnVzFilterName='icmp')

    dbContract = BrCP(fvTenantMo, 'DB')
    vzSubjMo = Subj(dbContract, 'DB-Ports')
    RsSubjFiltAtt(vzSubjMo, tnVzFilterName='icmp')

    print('--- Creating Application Profile')
    #Create Application Profile
    fvApMo = Ap(fvTenantMo, 'DemoAppProfile')

    print('--- Building EPG: App')
    #Build AEPg APP
    fvAEPg1 = AEPg(fvApMo, 'APP')
    fvAEPgBD1 = RsBd(fvAEPg1, tnFvBDName=fvBDMo1.name)
    #Attach Static AEPg to Interface
    fvRsPathAtt1 = RsPathAtt(fvAEPg1,
                             tDn=u'topology/pod-1/paths-101/pathep-[eth1/15]',
                             primaryEncap=u'unknown',
                             instrImedcy=u'lazy',
                             mode=u'regular',
                             encap=u'vlan-2005')

    AppProv1 = RsProv(fvAEPg1, tnVzBrCPName=appContract.name)
    AppCons1 = RsCons(fvAEPg1, tnVzBrCPName=dbContract.name)

    print('--- Building EPG: Web')
    #Build AEPg WEB
    fvAEPg2 = AEPg(fvApMo, 'WEB')
    fvAEPgBD1 = RsBd(fvAEPg2, tnFvBDName=fvBDMo2.name)
    #Attach Static AEPg to Interface
    fvRsPathAtt2 = RsPathAtt(fvAEPg2,
                             tDn=u'topology/pod-1/paths-101/pathep-[eth1/16]',
                             primaryEncap=u'unknown',
                             instrImedcy=u'lazy',
                             mode=u'regular',
                             encap=u'vlan-2006')

    WebProv1 = RsProv(fvAEPg2, tnVzBrCPName=httpContract.name)
    WebCons1 = RsCons(fvAEPg2, tnVzBrCPName=appContract.name)

    print('--- Building EPG: DB')
    #Build AEPg DB
    fvAEPg3 = AEPg(fvApMo, 'DB')
    print('	--- Attaching DB to Bridge Domain: ' + fvBDMo2.name)
    fvAEPgBD1 = RsBd(fvAEPg3, tnFvBDName=fvBDMo2.name)
    #Attach Static AEPg to Interface
    fvRsPathAtt3 = RsPathAtt(fvAEPg3,
                             tDn=u'topology/pod-1/paths-101/pathep-[eth1/17]',
                             primaryEncap=u'unknown',
                             instrImedcy=u'lazy',
                             mode=u'regular',
                             encap=u'vlan-2007')

    DbProv1 = RsProv(fvAEPg3, tnVzBrCPName=dbContract.name)

    print('--- Building L3 Out')
    # Configure L3 Out
    l3extOut = Out(fvTenantMo, name=u'L3Ext-Cobra', enforceRtctrl=u'export')
    l3extRsEctx = RsEctx(l3extOut, tnFvCtxName=vrf1.name)
    l3extLNodeP = LNodeP(l3extOut, name=u'Leaf102')
    l3extRsNodeL3OutAtt = RsNodeL3OutAtt(l3extLNodeP,
                                         rtrIdLoopBack=u'no',
                                         rtrId=u'10.10.15.250',
                                         tDn=u'topology/pod-1/node-102')
    l3extLIfP = LIfP(l3extLNodeP, name=u'port1-Cobra')
    ospfIfP = IfP(l3extLIfP, authKeyId=u'1')
    ospfRsIfPol = RsIfPol(ospfIfP, tnOspfIfPolName=u'OSPF-P2P')
    l3extRsPathL3OutAtt = RsPathL3OutAtt(
        l3extLIfP,
        addr=u'10.10.100.9/30',
        encapScope=u'local',
        mode=u'regular',
        ifInstT=u'l3-port',
        mtu=u'1500',
        tDn=u'topology/pod-1/paths-102/pathep-[eth1/1]')

    l3extInstP = l3ext.InstP(l3extOut, name=u'L3-OUT-EPG')
    fvRsCons = RsCons(l3extInstP, tnVzBrCPName=httpContract.name)
    l3extSubnet = L3Sub(l3extInstP, ip=u'0.0.0.0/0')
    ospfExtP = ExtP(l3extOut,
                    areaCtrl=u'redistribute,summary',
                    areaId=u'0.0.0.1',
                    areaType=u'regular',
                    areaCost=u'1')
    BDAttL3Out1 = RsBDToOut(fvBDMo2, tnL3extOutName=l3extOut.name)

    cfg_commit(moDir, fvTenantMo)
    print('[END] Tenant Configuration')