Пример #1
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)
Пример #2
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()
Пример #3
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))
Пример #4
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)
Пример #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)
Пример #6
0
# Set just the URLLIB3 logging level to INFO
requests_log.setLevel(logging.INFO)
requests_log.propagate = True

requests.packages.urllib3.disable_warnings()

aci_class = sys.argv[1]
session = LoginSession('https://172.21.208.173', 'admin','C1sc0123')
moDir = MoDirectory(session)
moDir.login()

from cobra.mit.request import ConfigRequest

#import the tenant class from the model
from cobra.model.fv import Tenant
# Get the top level policy universe directory
uniMo = moDir.lookupByDn('uni')

## create the tenant object
#fvTenantMo = Tenant(uniMo, 'test1111111111')
#fvTenantMo.delete()#

#configReq = ConfigRequest()
#configReq.addMo(fvTenantMo)
#moDir.commit(configReq)

obj_list = moDir.lookupByClass(aci_class)
#
for mo in obj_list:
	print "{} -> {}".format(mo.name,mo.dn)
Пример #7
0
# APIC Login Credentials
apicUrl = 'https://ssacimn010a02apic01.ss.astontech.com'
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)
                },
                {
                    'name': 'db3'
                },
            ]
        },
    ]
}]

# CONNECT TO APIC
print('Initializing connection to APIC.\n**')
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'])
Пример #9
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!')
Пример #10
0
# Login to the APIC
loginSession = LoginSession(apic_url, apic_user, apic_password)
md = MoDirectory(loginSession)
md.login()

# 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)
Пример #11
0
# Set just the URLLIB3 logging level to INFO
requests_log.setLevel(logging.INFO)
requests_log.propagate = True

requests.packages.urllib3.disable_warnings()

aci_class = sys.argv[1]
session = LoginSession('https://172.21.208.173', 'admin', 'C1sc0123')
moDir = MoDirectory(session)
moDir.login()

from cobra.mit.request import ConfigRequest

#import the tenant class from the model
from cobra.model.fv import Tenant
# Get the top level policy universe directory
uniMo = moDir.lookupByDn('uni')

## create the tenant object
#fvTenantMo = Tenant(uniMo, 'test1111111111')
#fvTenantMo.delete()#

#configReq = ConfigRequest()
#configReq.addMo(fvTenantMo)
#moDir.commit(configReq)

obj_list = moDir.lookupByClass(aci_class)
#
for mo in obj_list:
    print "{} -> {}".format(mo.name, mo.dn)
Пример #12
0
host = "10.10.10.33"

apic = "{0}://{1}".format(protocol, host)

session = LoginSession(apic, username, password)
moDir = MoDirectory(session)
moDir.login()

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)
Пример #13
0
if get_inputs == 'y':
    # okay, let's do this
    # APIC login
    session = cobra.mit.session.LoginSession(apic_1_URL,
                                             apic_user,
                                             apic_pw,
                                             secure=False,
                                             timeout=180)
    md = MoDirectory(session)

    print "Trying to log in ..."
    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())
Пример #14
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
Пример #15
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}')
Пример #17
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)
Пример #18
0
host = "10.10.10.33"

apic = "{0}://{1}".format(protocol, host)

session = LoginSession(apic, username, password)
moDir = MoDirectory(session)
moDir.login()

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'