def create_single_access(self, epg_dn, switch_dn, port_dn, vlan_number, aep_name, if_policy_group_name, switch_p_name): """ Creates the switch profile, policy group and the interface profile needed to assign a specific port to a end point group via static binding. Creates the relationship between the EPG and the port as wll :param epg_dn: :param switch_dn: :param port_dn: :param vlan_number: :param aep_name: :param if_policy_group_name: :param switch_p_name: :return: """ # Creates interface policy group if_policy_group = self.create_if_policy_group(if_policy_group_name, aep_name) # Creates interface profile if_profile = self.create_interface_profile(port_dn, if_policy_group.dn) # Creates switch profile self.create_single_access_switch_profile(switch_dn, if_profile.dn, switch_p_name) # Creates static binding fabric_path_dn = port_dn.replace('node', 'paths').replace( 'sys/phys', 'pathep') rspathatt_mo = RsPathAtt(epg_dn, fabric_path_dn, encap=VLAN_PREFIX + str(vlan_number)) self.commit(rspathatt_mo)
def attach_vpc(moEPG, vNum, port): vlan = 'vlan-' + vNum try: fvInt = RsPathAtt(moEPG, tDn=port, encap=vlan, instrImedcy='immediate') print '[+] Port successfully attached to EPG' CONFIG.addMo(fvInt) except: print '[-] Error attaching port <%s> to EPG' % port exit(1)
def associate_epg_vpc(self, epg_dn, vpc_dn, vlan_number): """ Creates an static binding between a virtual port channel and an end point group :param epg_dn: :param vpc_dn: :param vlan_number: :return: """ rspath = RsPathAtt(epg_dn, vpc_dn, encap=VLAN_PREFIX + str(vlan_number)) self.commit(rspath)
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
def create_static_path(tenant_name, app_name, epg_name, path_name, encap_id, mode_name): vlan_id = 'vlan-' + encap_id uni_mo = moDir.lookupByDn('uni') tenant_mo = Tenant(uni_mo, tenant_name) app_mo = Ap(tenant_mo, app_name) epg_mo = AEPg(app_mo, epg_name) rspathatt_mo = RsPathAtt(epg_mo, tDn=path_name, instrImedcy=u'immediate', encap=vlan_id, mode=mode_name) config = ConfigRequest() config.addMo(tenant_mo) moDir.commit(config)
def create_bindings_from_excel(): global count try: if path.exists(excel_file): apic_id = re.sub(r"http(s)?://(.*)", r"\2", main.auth_info[0]) print("\n" + "%s".rjust(len("%s") + 4) % colored(f" The '{excel_file}' file was found in the local " f"directory.", color="green")) print("%s".rjust(len("%s") + 4) % colored(" The script will proceed to deploy the Static Path Bindings " "from the file to the following ACI fabric:", color="green")) print("\n" + "%s".rjust(len("%s") + 4) % colored(f" ACI Fabric IP/Hostname/FQDN: {apic_id}", color="green", attrs=["bold"])) input("\n" + "%s" % colored(" Please hit 'Enter' when you are ready to start... ", color="magenta")) clear() epg_without_binding = pd.read_excel(excel_file) epg_without_binding['encap'] = ["vlan-%s" % value for idx, value in epg_without_binding['encap'].iteritems()] epg_without_binding = epg_without_binding.set_index('epgDn') cfg_request = ConfigRequest() for epg_dn, value in epg_without_binding[['tDn', 'encap']].iterrows(): this_tn, this_app_p, this_epg = (re.sub(epg_regex, r'\2 \3 \4', epg_dn)).split() fv_rs_path_att_mo = RsPathAtt(epg_dn, tDn=value[0], instrImedcy="immediate", encap=value[1]) cfg_request.addMo(fv_rs_path_att_mo) response = main.mo_dir.commit(cfg_request) print("\n" + "%s" % colored(f" Deploying on {this_epg}... ", color="blue", attrs=["bold"])) count += 1 with open(filename, "a+") as file: file.write("%s: %s fvRsPathAtt_dn: %s %s\n" % (datetime.now().strftime("%Y/%m/%d %H:%M:%S"), apic_id, fv_rs_path_att_mo.dn, response)) sleep(2) remove(excel_file) sleep(2) else: pass except Exception as error: print(colored("%s" % f"\n Error in function 'create_bindings_from_excel': {error}", color="red"))
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()
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')
def main(): module = AnsibleModule(argument_spec=dict( host=dict(required=True), username=dict(type='str', default=''), password=dict(type='str', default=''), protocol=dict(choices=['http', 'https'], default='https'), state=dict(choices=['present', 'absent'], default='present'), leaf_profile=dict(type='str', required=True), tenant=dict(type='str', required=True), path_type=dict(choices=['individual', 'pc', 'vpc'], default='individual'), path_port=dict(type='str', default=''), path_name=dict(type='str', default=''), path_description=dict(type='str', default=''), path_ap=dict(type='str', required=True), path_epg=dict(type='str', required=True), path_encap=dict(type='str', default=''), path_mode=dict(choices=['regular', 'untagged', 'native'], default='native'), path_fex=dict(type='str', default=''), path_immediancy=dict(choices=['immediate', 'lazy'], default='lazy')), supports_check_mode=True) if not HAS_COBRA: module.fail_json(msg='Ensure you have the ACI Cobra SDK installed', error=str(ie)) username = module.params['username'] password = module.params['password'] host = module.params['host'] path_type = module.params['path_type'].lower() state = module.params['state'].lower() leaf_profile = module.params['leaf_profile'] tenant = module.params['tenant'] path_type = module.params['path_type'] path_port = module.params['path_port'] path_name = module.params['path_name'] path_description = module.params['path_description'] path_ap = module.params['path_ap'] path_epg = module.params['path_epg'] path_encap = module.params['path_encap'] path_mode = module.params['path_mode'] path_fex = module.params['path_fex'] path_immediancy = module.params['path_immediancy'] moDir = apic_login(host, username, password) fv_aepg = None fv_rsnodeatt = None port_name = '' policy_group = '' aep = '' # Verify tenant is valid if check_if_tenant_exist(moDir, tenant, return_boolean=True, set_mo=False): fv_tenant = check_if_tenant_exist(moDir, tenant, return_boolean=False, set_mo=False) else: module.fail_json(msg=tenant + ' does not exist. Check Tenants.') # Verify Application Profile is valid if check_if_mo_exist(moDir, 'uni/tn-' + fv_tenant.name + '/ap-', path_ap, Ap, 'Application Profile', return_false=True, set_mo=False): fv_ap = check_if_mo_exist(moDir, 'uni/tn-' + fv_tenant.name + '/ap-', path_ap, Ap, return_false=False, set_mo=False) else: module.fail_json( msg=path_ap + ' application profile does not exist. Check Tenants -> Tenant ' + fv_tenant.name + ' -> Application Profiles') # Verify End Point Group is valid in the AP if check_if_mo_exist(moDir, 'uni/tn-' + fv_tenant.name + '/ap-' + fv_ap.name + '/epg-', path_epg, AEPg, 'Application Endpoint Group', return_false=True, set_mo=False): uri = 'uni/tn-' + fv_tenant.name + '/ap-' + fv_ap.name + '/epg-' fv_aepg = check_if_mo_exist(moDir, uri, path_epg, AEPg, return_false=False, set_mo=False) else: module.fail_json( msg=path_epg + ' application EPG does not exist. Check Tenants -> Tenant ' + fv_tenant.name + ' -> Application Profiles -> ' + fv_ap.name + ' -> Application EPGs') if path_type == 'individual': # Get the node id of the leaf_profile try: if path_fex: node_id = get_nodeid(moDir, leaf_profile[:-8]) else: node_id = get_nodeid(moDir, leaf_profile) except IndexError: module.fail_json(msg='unable to find Node. Verify syntax.') if node_id == '0': module.fail_json(msg=leaf_profile + ' does not have a node id.') if path_fex: path = 'topology/pod-1/paths-' + node_id + '/extpaths-' + path_fex + '/pathep-[eth' + path_port + ']' else: path = 'topology/pod-1/paths-' + node_id + '/pathep-[eth' + path_port + ']' # if adding a port-channel elif path_type == 'pc': try: if path_fex: node_id = get_nodeid(moDir, leaf_profile[:-8]) else: node_id = get_nodeid(moDir, leaf_profile) except IndexError: module.fail_json(msg='unable to find Node. Verify syntax.') aep = get_policy_group_aep(moDir, path_name, 'accbundle-') if node_id == '0': module.fail_json(msg=leaf_profile + ' does not have a node id.') if path_fex: path = 'topology/pod-1/paths-' + node_id + '/extpaths-' + path_fex + '/pathep-[' + path_name + ']' else: path = 'topology/pod-1/paths-' + node_id + '/pathep-[' + path_name + ']' # if adding a virtual port-channel elif path_type == 'vpc': # check for vpc switch ids try: node_ids = get_vpcnodeid(moDir, leaf_profile) except IndexError: module.fail_json(msg='unable to find Node. Verify syntax.') if node_ids == '0': module.fail_json(msg=leaf_profile + ' is not a valid VPC domain.') if path_fex: path = 'topology/pod-1/protpaths-' + node_ids + '/extpaths-' + path_fex + '/pathep-[' + path_name + ']' else: path = 'topology/pod-1/protpaths-' + node_ids + '/pathep-[' + path_name + ']' else: module.fail_json( msg= 'Invalid interface type. Options are "individual", "pc", or "vpc"' ) if state == 'present': if check_if_port_in_epg( moDir, 'uni/tn-' + fv_tenant.name + '/ap-' + fv_ap.name + '/epg-' + fv_aepg.name + '/rspathAtt-[' + path + ']', path_mode, path_encap): module.fail_json( msg='Port already in EPG with conflicting configuration') if path_fex and path_type == 'individual': fex_profile = leaf_profile if check_if_mo_exist(moDir, 'uni/infra/fexprof-', fex_profile, FexP, 'FEX Profile', return_false=True, set_mo=False): if check_if_fexport_configured(moDir, fex_profile, path_port): port_name = get_fex_port_name(moDir, fex_profile, path_port) else: module.fail_json( msg='Port is not configured in FEX Number ' + path_fex) if not port_name: module.fail_json( msg='Port ' + path_port + ' is not configured. Check Fabric -> Access Policies -> ' + fex_profile) policy_group = get_fexport_policy_group( moDir, fex_profile, port_name) if policy_group == '0': module.fail_json(msg='Check Port Policy Group.') aep = get_policy_group_aep(moDir, policy_group, 'accportgrp-') elif path_type == 'individual': if check_if_mo_exist(moDir, 'uni/infra/accportprof-', leaf_profile + '_ifselector', AccPortP, 'Interface Profile', return_false=True, set_mo=False): if check_if_switchport_configured(moDir, leaf_profile, path_port): port_name = get_switchport_name(moDir, leaf_profile, path_port) else: module.fail_json( msg='Port is not configured in Leaf Profile ' + leaf_profile) if not port_name: module.fail_json( msg='Port ' + path_port + ' is not configured. Check Fabric -> Access Policies -> ' + leaf_profile + '_ifselector') policy_group = get_switchport_policy_group(moDir, leaf_profile, port_name) if policy_group == '0': module.fail_json(msg='Check Port Policy Group.') aep = get_policy_group_aep(moDir, policy_group, 'accportgrp-') else: if check_if_bundle_configured(moDir, path_name): aep = get_policy_group_aep(moDir, path_name, 'accbundle-') else: module.fail_json(msg='Bundle ' + path_name + ' on ' + leaf_profile + ' is not configured') if aep == '0': module.fail_json(msg='AEP not found for ' + path_name + ' path: ' + path) domains = get_epg_dom(moDir, uri, path_epg) aep_domain = False encap_domain = False for domain in domains: if check_policy_group_in_domain(moDir, domain, aep): aep_domain = True if check_static_vlan_in_domain(moDir, domain, path_encap): encap_domain = True fv_rsnodeatt = RsPathAtt(fv_aepg, path, descr=path_description, encap=path_encap, mode=path_mode, instrImedcy=path_immediancy) break if not aep_domain: module.fail_json(msg='Policy group AEP domain does not match EPG.') if not encap_domain: module.fail_json(msg='Domain for ' + path_encap + ' is not in the EPG. Check Tenants -> Tenant ' + fv_tenant.name + ' -> Application Profiles -> ' + fv_ap.name + ' -> Application EPGs -> ' + fv_aepg.name + ' -> Domains') #module will remove static port from epg elif state == 'absent': fv_rsnodeatt = check_if_mo_exist(moDir, uri + path_epg + '/rspathAtt-', '[' + path + ']', RsPathAtt, ' Static Port ', return_false=True, set_mo=False) if fv_rsnodeatt: fv_rsnodeatt.delete() else: module.fail_json(msg=' Path does not exist in AP ' + fv_ap.name + ' EPG ' + fv_aepg.name) else: module.fail_json( msg='Invalid path status. Options are "present" or "absent"') results = {} xmldoc = '' factsdict = {} changed = False # Build configuration and commit if not run in check-mode if fv_aepg and state == 'present': xmldoc = print_query_xml(fv_aepg) factsdict['configuration'] = xmldoc if module.check_mode: module.exit_json(changed=True, ansible_facts=factsdict) else: changed = True commit_change(moDir, fv_aepg, print_xml=False) elif fv_rsnodeatt and state == 'absent': xmldoc = print_query_xml(fv_rsnodeatt) factsdict['configuration'] = xmldoc if module.check_mode: module.exit_json(changed=True, ansible_facts=factsdict) else: changed = True commit_change(moDir, fv_rsnodeatt, print_xml=False) results['xmldoc'] = xmldoc results['state'] = state results['changed'] = changed module.exit_json(ansible_facts=factsdict, **results)
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']
def create_bindings_from_ready_df(binding_ready_to_deploy, bind_tdn): global count apic_id = re.sub(r"http(s)?://(.*)", r"\2", main.auth_info[0]) try: binding_ready_to_deploy['size'] = '' binding_ready_to_deploy['size'] = [value.size for epg_dn, value in binding_ready_to_deploy.encap.iteritems()] binding_ready_to_deploy = binding_ready_to_deploy.sort_values(by='size', ascending=False) cfg_request = ConfigRequest() for epg_dn, value in binding_ready_to_deploy['encap'].iteritems(): this_tn, this_app_p, this_epg = (re.sub(epg_regex, r'\2 \3 \4', epg_dn)).split() if value.size >= 2: clear() print( "%s" % colored( "\n The following EPG has Static Path Bindings with multiple encapsulation values:\n\n", color="yellow") + " Tenant: %(this_tn)s\n" " App Profile: %(this_appProf)s\n" " EPG: %(this_epg)s\n" % dict(this_tn=this_tn, this_appProf=this_app_p, this_epg=this_epg) + "%s" % colored("\n Please select the encapsulation value to be deployed from the list below, " "or enter a new one:\n", color="yellow") ) opt_dict = {} opt_idx = 1 while opt_idx <= value.size: for item in value: opt_dict["%s" % opt_idx] = item opt_idx += 1 opt_dict["%s" % opt_idx] = "Enter a new encapsulation value" opt_idx = 1 for opt in opt_dict.values(): print("%s".rjust(len("%s") + 4) % f" {opt_idx}) {opt}") opt_idx += 1 print() selection = select(value.size + 1) if opt_dict[str(selection)] == "Enter a new encapsulation value": print("\n" + "%s" % colored(f" Please enter an encapsulation value for {this_epg}", color="magenta") + "\n%s" % colored(" IMPORTANT: ", color="magenta", attrs=["bold"]) + "%s\n" % colored("Please make sure to enter only numeric values " "(e.g. 2, 50, 101, 2050)", color="yellow") ) encap_value = input("%s" % colored(" --> ", color="magenta")) is_good_number = encap_value.isnumeric() and 1 <= int(encap_value) <= 4096 while is_good_number is False: print("%s" % colored(" The provided encapsulation value '", color="yellow") + "%s" % colored(f"{encap_value}", color="magenta", attrs=["bold"]) + "%s" % colored("' is not numeric OR is zero OR is higher than 4096.", color="yellow")) encap_value = input("\n" + "%s" % colored(f" Please enter an encapsulation value for {this_epg} --> ", color="magenta")) is_good_number = encap_value.isnumeric() and 1 <= int(encap_value) <= 4096 vlan_value = "vlan-%s" % encap_value fv_rs_path_att_mo = RsPathAtt(epg_dn, tDn=bind_tdn, instrImedcy="immediate", encap=vlan_value) cfg_request.addMo(fv_rs_path_att_mo) print("\n" + "%s" % colored(f" Deploying on {this_epg}... ", color="blue", attrs=["bold"])) response = main.mo_dir.commit(cfg_request) count += 1 with open(filename, "a+") as file: file.write("%s: %s fvRsPathAtt_dn: %s %s\n" % (datetime.now().strftime("%Y/%m/%d %H:%M:%S"), apic_id, fv_rs_path_att_mo.dn, response)) sleep(2) else: vlan_value = opt_dict[str(selection)] fv_rs_path_att_mo = RsPathAtt(epg_dn, tDn=bind_tdn, instrImedcy="immediate", encap=vlan_value) cfg_request.addMo(fv_rs_path_att_mo) response = main.mo_dir.commit(cfg_request) print("\n" + "%s" % colored(f" Deploying on {this_epg}... ", color="blue", attrs=["bold"])) count += 1 with open(filename, "a+") as file: file.write("%s: %s fvRsPathAtt_dn: %s %s\n" % (datetime.now().strftime("%Y/%m/%d %H:%M:%S"), apic_id, fv_rs_path_att_mo.dn, response)) sleep(2) elif value.size == 1: fv_rs_path_att_mo = RsPathAtt(epg_dn, tDn=bind_tdn, instrImedcy="immediate", encap=value[0]) cfg_request.addMo(fv_rs_path_att_mo) response = main.mo_dir.commit(cfg_request) print("\n" + "%s" % colored(f" Deploying on {this_epg}... ", color="blue", attrs=["bold"])) count += 1 with open(filename, "a+") as file: file.write("%s: %s fvRsPathAtt_dn: %s %s\n" % (datetime.now().strftime("%Y/%m/%d %H:%M:%S"), apic_id, fv_rs_path_att_mo.dn, response)) sleep(2) except Exception as error: print(colored("%s" % f"\n Error in function 'creating_bindings_from_ready_df': {error}", color="red"))