Exemplo n.º 1
0
def add_vmm_domain_association(fv_epg, vmm_domain, **args):
    """Add Vmm Domain Association"""
    args = args['optional_args'] if 'optional_args' in args.keys() else args
    fv_rsdomatt = RsDomAtt(fv_epg,
                           'uni/vmmp-VMware/dom-' + vmm_domain,
                           instrImedcy=get_value(args, 'deployment_immediacy',
                                                 DEFAULT_IMMEDIACY),
                           resImedcy=get_value(args, 'resolution_immediacy',
                                               DEFAULT_IMMEDIACY))
Exemplo n.º 2
0
def add_domain_to_epg(mo, dName=DOMAIN, dType='phys'):
    dName = 'uni/' + dType + '-' + dName
    try:
        RsDomAtt(mo, tDn=dName, resImedcy='immediate')
        print '[+] EPG successfully attached to Domain %s' % DOMAIN
        CONFIG.addMo(mo)
    except:
        print '[-] Error attaching EPG to Domain %s' % DOMAIN
        exit(1)
Exemplo n.º 3
0
def create_application_epg(fv_ap, epg, **args):
    """Create a Application. A set of requirements for the application-level EPG instance. The policy regulates connectivity and visibility among the end points within the scope of the policy. """
    args = args['optional_args'] if 'optional_args' in args.keys() else args
    fv_aepg = AEPg(fv_ap,
                   epg,
                   prio=get_value(args, 'prio', 'unspecified').lower())

    # Provide bridge_domain to the EPG.
    if is_valid_key(args, 'bridge_domain'):
        fv_rsbd = RsBd(fv_aepg, tnFvBDName=args['bridge_domain'])

    if is_valid_key(args, 'custom_qos'):
        fv_rscustqospol = RsCustQosPol(fv_aepg,
                                       tnQosCustomPolName=args['custom_qos'])

    if is_valid_key(args, 'monitoring'):
        fv_rsaepgmonpol = RsAEPgMonPol(fv_aepg,
                                       tnMonEPGPolName=args['monitoring'])

    if is_valid_key(args, 'associated_domain_profile'):
        for profile in args['associated_domain_profile']:
            fv_rsdomatt = RsDomAtt(
                fv_aepg,
                'uni/phys-' + profile['domain_profile'],
                instrImedcy=get_value(profile, 'deployment_immediacy',
                                      DEFAULT_IMMEDIACY),
                resImedcy=get_value(profile, 'resolution_immediacy',
                                    DEFAULT_IMMEDIACY))

    if is_valid_key(args, 'statically_link') and args['statically_link']:
        if is_valid_key(args, 'leaf') and is_valid_key(
                args['leaf'], 'node_id', ban=['None']):
            fv_rsnodeatt = RsNodeAtt(
                fv_aepg,
                'topology/pod-1/node-' + str(args['leaf']['node_id']),
                encap=args['leaf']['encap'],
                mode=get_value(args['leaf'], 'mode', DEFAULT_MODE),
                instrImedcy=get_value(args['leaf'], 'deployment_immediacy',
                                      DEFAULT_IMMEDIACY))

        if is_valid_key(args, 'path') and is_valid_key(
                args['path'], 'node_id', ban=['None']):
            fv_rsnodeatt = RsPathAtt(
                fv_aepg,
                'topology/pod-1/paths-' + str(args['path']['node_id']) +
                '/pathep-[eth' + args['path']['eth'] + ']',
                encap=args['path']['encap'],
                mode=get_value(args['path'], 'mode', DEFAULT_MODE),
                instrImedcy=get_value(args['path'], 'deployment_immediacy',
                                      DEFAULT_IMMEDIACY))

    return fv_aepg
Exemplo n.º 4
0
def add_vmm_domain_association(modir, tenant_name, application, epg,
                               vmm_domain, **args):
    fv_epg = modir.lookupByDn('uni/tn-' + tenant_name + '/ap-' + application +
                              '/epg-' + epg)
    args = args['args_from_CLI'] if 'args_from_CLI' in args.keys() else args
    if isinstance(fv_epg, AEPg):
        fv_rsdomatt = RsDomAtt(fv_epg,
                               'uni/vmmp-VMware/dom-' + vmm_domain,
                               instrImedcy=get_value(args,
                                                     'deployment_immediacy',
                                                     'lazy'),
                               resImedcy=get_value(args,
                                                   'resolution_immediacy',
                                                   'lazy'))
    else:
        print 'Fail to find EPG', epg, 'Please make sure you have the EPG in application', application
        return

    print_query_xml(fv_epg)
    commit_change(modir, fv_epg)
Exemplo n.º 5
0
 def associate_epg_physical_domain(self, epg_dn, physical_domain_name):
     """
     Associate a physical domain to an end point group
     :param epg_dn:
     :param physical_domain_name:
     :return:
     """
     # Query the physical domain according to an specific name
     class_query = ClassQuery('physDomP')
     class_query.propFilter = 'eq(physDomP.name, "' + PD_PREFIX + physical_domain_name + '")'
     pd_list = self.moDir.query(class_query)
     # If the physical domain does not exists, create it with the vlan pool and the attachable entity profile
     if len(pd_list) == 0:
         vlan_pool_mo = self.create_vlan_pool(VLAN_POOL_PREFIX + physical_domain_name, 'static')
         DomP_mo = self.create_physical_domain(PD_PREFIX + physical_domain_name, str(vlan_pool_mo.dn))
         self.create_attachable_entity_profile(AEP_PREFIX + physical_domain_name, str(DomP_mo.dn))
     else:
         DomP_mo = pd_list[0]
     # Creates and commits the association
     rsdom = RsDomAtt(epg_dn, str(DomP_mo.dn))
     self.commit(rsdom)
Exemplo n.º 6
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!')
Exemplo n.º 7
0
def create_endpoint_groups(delete=''):
    epg_df = pd.read_excel("input-data/ACI_DD_Workbook.xlsx",
                           sheet_name='End_Point_Groups')
    file = open("EPG_Configuration.log", "w")
    logon = apic_logon()
    uniMo = logon.lookupByDn('uni')
    for index, row in epg_df.iterrows():
        fvTenant = Tenant(uniMo, row['Tenant'])
        fvAp = Ap(fvTenant, row['Application Profile'])
        if delete == 'yes':
            fvAEPg = AEPg(fvAp, name=row['Name'], status='deleted')
        else:
            fvAEPg = AEPg(fvAp,
                          name=row['EPG Name'],
                          description=row['EPG Description'],
                          prefGrMemb=row['prefGrMemb'])
            if pd.isnull(row['Associated Bridge Domain']) == False:
                fvRsBD = RsBd(fvAEPg,
                              tnFvBDName=row['Associated Bridge Domain'])
            if pd.isnull(row['Physical Domain']) == False:
                fvRsDomAtt = RsDomAtt(fvAEPg,
                                      tDn='uni/phys-%s' %
                                      row['Physical Domain'])
            if pd.isnull(row['Static Path']) == False:
                fvRsPathAtt = RsPathAtt(fvAEPg,
                                        tDn=row['Static Path'],
                                        encap='vlan-%s' % row['VLAN Encap'])
            if pd.isnull(row['Associated VMM1']) == False:
                fvRsDomAtt1 = RsDomAtt(fvAEPg,
                                       tDn='uni/vmmp-VMware/dom-' +
                                       row['Associated VMM1'],
                                       primaryEncap=u'unknown',
                                       classPref=u'encap',
                                       delimiter=u'',
                                       instrImedcy=u'lazy',
                                       encap=u'unknown',
                                       encapMode=u'auto',
                                       resImedcy=u'immediate')
                vmmSecP = SecP(fvRsDomAtt1,
                               ownerKey=u'',
                               name=u'',
                               descr=u'',
                               forgedTransmits=u'reject',
                               ownerTag=u'',
                               allowPromiscuous=u'reject',
                               macChanges=u'reject')
            if pd.isnull(row['Associated VMM2']) == False:
                fvRsDomAtt2 = RsDomAtt(fvAEPg,
                                       tDn='uni/vmmp-VMware/dom-' +
                                       row['Associated VMM2'],
                                       primaryEncap=u'unknown',
                                       classPref=u'encap',
                                       delimiter=u'',
                                       instrImedcy=u'lazy',
                                       encap=u'unknown',
                                       encapMode=u'auto',
                                       resImedcy=u'immediate')
                vmmSecP2 = SecP(fvRsDomAtt2,
                                ownerKey=u'',
                                name=u'',
                                descr=u'',
                                forgedTransmits=u'reject',
                                ownerTag=u'',
                                allowPromiscuous=u'reject',
                                macChanges=u'reject')
        cfgRequest = ConfigRequest()
        cfgRequest.addMo(fvAp)
        logon.commit(cfgRequest)
        json_data = toJSONStr(fvAp, prettyPrint=True)
        file.write(
            '\n-------------------------------------------------------------------\n'
        )
        file.write(json_data)
    file.close()
Exemplo n.º 8
0
def setupApp(spec, apicMoDir, gwConfig):
    logging.debug('Inside setupApp function')
    # create an app prof if it does not exist.
    appName = spec['app-prof']
    tenant = spec['tenant']
    tenMo = tenantDict[tenant]
    epgList = spec['epgs']

    logging.debug('Nodes : %s' % gwConfig.nodes)
    logging.debug('Paths : %s' % gwConfig.paths)

    physDom = gwConfig.physDom
    vmmDom = gwConfig.vmmDom
    if physDom == "not_specified" and vmmDom == "not_specified":
        return ['failed', 'Physical and VMM domain not specified']

    # Check if the APIC already knows about this application profile
    # within this tenant context
    appProfDn = formAppProfDn(tenant, appName)
    exists, fvApMo = checkDnExists(apicMoDir, appProfDn)
    if exists:
        # The appProfile already exists in the APIC. Stash what we got.
        logging.info('App-prof %s,%s already exists.' % (tenant, appName))
        appDict[appName] = fvApMo
    else:
        logging.info('Creating application profile %s in tenant %s' % (appName, tenant))
        fvApMo = Ap(tenMo, appName)
        appDict[appName] = fvApMo

    cR = ConfigRequest()
    cR.addMo(fvApMo)

    # Walk the EPG list and create them.
    for epg in epgList:
        # Get the bridge domain for this epg, will create if needed
        comTen = gwConfig.includeCommonTenant
        bdName = getBridgeDomain(tenant, epg, apicMoDir, comTen)
        epgName = epg['name']
        fvEpg = AEPg(fvApMo, epgName)
        # associate to BD
        RsBd(fvEpg, tnFvBDName=bdName)
        vlan = epg['vlan-tag']
        encapid = 'vlan-' + vlan
        
        if vmmDom != "not_specified":
            # associate to vmm domain
            logging.info("VMM Domain: {}".format(vmmDom))
            contivClusterDom = 'uni/vmmp-VMware/dom-' + vmmDom
            logging.debug("Bind VMM : {} on {}".format(vmmDom, encapid))
            rsDomAtt = RsDomAtt(fvEpg, tDn=contivClusterDom, instrImedcy='immediate', encap=encapid, resImedcy='immediate')
            SecP(rsDomAtt, forgedTransmits='accept', allowPromiscuous='accept', macChanges='accept')
        
        if physDom != "not_specified":
            # associate to phy domain
            contivClusterDom = 'uni/phys-' + physDom
            RsDomAtt(fvEpg, contivClusterDom)
            # TODO: add static binding
            logging.info('Nodes : %s' % gwConfig.nodes)
            for leaf in gwConfig.nodes:
                logging.debug('Bind Leaf : %s' % leaf)
                RsNodeAtt(fvEpg, tDn=leaf, encap=encapid)

            logging.info('Paths : %s' % gwConfig.paths)
            for path in gwConfig.paths:
                logging.debug('Path = %s' % path)
                RsPathAtt(fvEpg, tDn=path, instrImedcy='immediate', encap=encapid)

    apicMoDir.commit(cR)

    enforce = gwConfig.enforcePolicies
    if enforce.lower() == "no":
        logging.info('Setting up EPG in un-enforced mode.')
        setupUnenforcedMode(spec, apicMoDir)
    else:
        logging.debug('Establishing policy contracts.')
        addDefinedContracts(spec, apicMoDir)
        logging.debug('Establishing consumer/provider links.')
        ret = addContractLinks(spec, apicMoDir)
        if ret[0] != 'success':
            return ret

    return ['success', 'ok']