def main(): # Get the APIC login credentials description = 'testing tags' creds = aci.Credentials('apic', description) creds.add_argument('--tag', help='Add tag to all objects in this configuration') creds.add_argument('--tenant', help='Tenant name to be created') args = creds.get() #Create the Tenant if args.tenant: tenant = aci.Tenant(args.tenant) else: tenant = aci.Tenant('tutorial-tag') # Create the Application Profile app = aci.AppProfile('myapp', tenant) # Create the EPG epg1 = aci.EPG('myepg1', app) epg2 = aci.EPG('myepg2', app) # Create a Context and BridgeDomain context = aci.Context('myvrf', tenant) bd = aci.BridgeDomain('mybd', tenant) bd.add_context(context) # Place the EPG in the BD epg1.add_bd(bd) epg2.add_bd(bd) # Add Tag to the EPGs epg1.add_tag("web server") epg2.add_tag("database") # test app2 = aci.AppProfile('myapp2', tenant) epg21 = aci.EPG('myepg21', app2) epg22 = aci.EPG('myepg22', app2) # Add Tag to all objects in this configuration if args.tag: tenant.add_tag(args.tag) context.add_tag(args.tag) bd.add_tag(args.tag) epg1.add_tag(args.tag) epg2.add_tag(args.tag) # Login to APIC and push the config session = aci.Session(args.url, args.login, args.password) session.login() resp = tenant.push_to_apic(session) if resp.ok: print('Success') # Print what was sent print('Pushed the following JSON to the APIC') print('URL:', tenant.get_url()) print('JSON:', tenant.get_json())
def main(): """ Main show EPGs routine :return: None """ # Login to APIC description = ('Simple application that logs on to the APIC' ' and add static-binding-leaves.') creds = aci.Credentials('apic', description) creds.add_argument('-t', '--tenant', help='Tenant name', default=DEFAULT_TENANT) creds.add_argument('-a', '--app', help='Application profile name', default=DEFAULT_APP) creds.add_argument('-e', '--epg', help='EPG name', default=DEFAULT_EPG) creds.add_argument('-n', '--node', help='Node ID (e.g. 101)', default=DEFAULT_NODE_ID) creds.add_argument('-y', '--type', help='Encapsulation type (vlan | vxlan | nvgre)', default=DEFAULT_ENCAP_TYPE) creds.add_argument('-i', '--id', help='Specific identifier representing the virtual L2 network (e.g. 100)', default=DEFAULT_ENCAP_ID) creds.add_argument('-m', '--mode', help='Encapsulation mode (regular | untagged | native)', default=DEFAULT_ENCAP_MODE) creds.add_argument('-d', '--deploy', help='Deployment immediacy (immediate | lazy)', default=DEFAULT_IMMEDIACY) creds.add_argument('-o', '--pod', help='Pod number (e.g. 1)', default=DEFAULT_POD) args = creds.get() session = aci.Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print('%% Could not login to APIC') tenant = aci.Tenant(args.tenant) app = aci.AppProfile(args.app, tenant) epg = aci.EPG(args.epg, app) epg.add_static_leaf_binding(args.node, args.type, args.id, args.mode, args.deploy, args.pod) # Push it all to the APIC resp = session.push_to_apic(tenant.get_url(), tenant.get_json())
def create_tenant_for_scalabilityTest(self, session, numberOfTenants_toBecreated, domain_toBe_attached): tenant_Prefix = "FVT_TenantScale_Test" app_Profile_name = "FVT_ApPScale_Test" epg_name = "FVT_epgScale_Test" domainflg = False for tenant_no in range(0, int(numberOfTenants_toBecreated)): tenant_toBe_created = tenant_Prefix + str(tenant_no) appP_toBe_created = app_Profile_name + str(tenant_no) epg_toBe_created = epg_name + str(tenant_no) tenant = aci.Tenant(tenant_toBe_created) app = aci.AppProfile(appP_toBe_created, tenant) epg = EPG(epg_toBe_created, app) domains = aci.VmmDomain.get(session) for domain in domains: if str(domain) == domain_toBe_attached: domainflg = True epg.attach(domain) if domainflg: resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) time.sleep(1) if resp.ok: print("*** {} Tenant Created".format(str(tenant))) else: print('%% Error: Could not push configuration to APIC')
def main(): """ Main execution routine """ description = 'Simple application that takes a tenant json from a configfile and returns a tenant object.' parser = argparse.ArgumentParser(description=description) parser.add_argument('-t', '--tenantname', required=True, help='name of the tenant') parser.add_argument('-config', '--tenantconfigfile', required=True, help='file containing tenant json') args = parser.parse_args() tenantObject = None if args.tenantconfigfile: with open(args.tenantconfigfile) as data_file: tenant_json = json.load(data_file) tenant = ACI.Tenant(args.tenantname) ACI.Tenant.get_from_json(tenant, tenant_json, parent=tenant) print(tenant.get_json())
def main(): """ Main create tenant routine :return: None """ # Get all the arguments description = 'It logs in to the APIC and will create the tenant.' creds = aci.Credentials('apic', description) creds.add_argument('-t', '--tenant', help='The name of tenant', default=DEFAULT_TENANT_NAME) args = creds.get() # Login to the APIC session = aci.Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print('%% Could not login to APIC') # Create the Tenant tenant = aci.Tenant(args.tenant) # Push the tenant to the APIC resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) if not resp.ok: print('%% Error: Could not push configuration to APIC') print(resp.text)
def Create_Contract(aci_sheet, row): # call login function and return session session = apic_login() # create variables by importing values from spreadsheet tn_name = ACI.Tenant(aci_sheet.cell_value(row, 1)) print tn_name contract_name = ACI.Contract(aci_sheet.cell_value(row, 2), tn_name) print contract_name filter_entry = ACI.FilterEntry('PythonFilter', applyToFrag='no', arpOpc='unspecified', dFromPort=str(aci_sheet.cell_value(row, 8)), dToPort=str(aci_sheet.cell_value(row, 9)), etherT='ip', prot=(aci_sheet.cell_value(row, 7)), sFromPort='1', sToPort='65535', tcpRules='unspecified', parent=contract_name) print filter_entry resp = session.push_to_apic(tn_name.get_url(), data=tn_name.get_json()) if resp.ok: print 'Contract %s deployed' % contract_name print '=' * 20 else: print 'contract %s not deployed' % contract_name
def CreateTenant(tenant_name): tenants = ACI.Tenant.get(session) if TenantExists_CaseInsensitive(tenant_name, tenants): print '\nTenant already exists. Skipping' else: print '\nCreating tenant...' tenant = ACI.Tenant(tenant_name) # Push it all to the APIC resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) if not resp.ok: print '%% Error: Could not push configuration to APIC' print resp.text
def DeleteTenant(tenant_name): if tenant_name.lower() in ['infra', 'common', 'mgmt']: print '\nInfrastructure tenants cannot be deleted.' else: tenants = ACI.Tenant.get(session) if TenantExists_CaseSensitive(tenant_name, tenants): print '\nDeleting tenant.' tenant = ACI.Tenant(tenant_name) tenant.mark_as_deleted() # Push it all to the APIC resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) if not resp.ok: print '%% Error: Could not push configuration to APIC' print resp.text else: print '\nTenant does not exist. Skipping'
def main(): """ Main create tenant routine :return: None """ # Get all the arguments description = 'It logs in to the APIC and will create the tenant.' creds = aci.Credentials('apic', description) creds.add_argument('-t', '--tenant', help='The name of tenant', default=DEFAULT_TENANT_NAME) creds.add_argument('-f', '--filter', help='The name of contract', default=DEFAULT_FILTER_NAME) args = creds.get() # Login to the APIC session = aci.Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print('%% Could not login to APIC') # Create the Tenant tenant = aci.Tenant(args.tenant) # Create Filter filter = aci.Filter(args.filter, tenant) entry1 = aci.FilterEntry(args.filter, applyToFrag='no', arpOpc='unspecified', dFromPort='3306', dToPort='3306', etherT='ip', prot='tcp', sFromPort='1', sToPort='65535', tcpRules='unspecified', parent=filter) # Push the Contract to the APIC resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) if not resp.ok: print('%% Error: Could not push configuration to APIC') print(resp.text)
def main(): """ Main create tenant routine :return: None """ # Get all the arguments description = 'It logs in to the APIC and will create the tenant.' creds = aci.Credentials('apic', description) creds.add_argument('-t', '--tenant', help='The name of tenant', default=DEFAULT_TENANT_NAME) creds.add_argument('-c', '--contract', help='The name of contract', default=DEFAULT_CONTRACT_NAME) creds.add_argument('-s', '--contract_sub', help='The name of contract \ subject', default=DEFAULT_CONTRACT_SUB_NAME) creds.add_argument('-f', '--filter', help='The name of filter', default=DEFAULT_CONTRACT_SUB_NAME) args = creds.get() # Login to the APIC session = aci.Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print('%% Could not login to APIC') # Create the Tenant tenant = aci.Tenant(args.tenant) # Create Contract contract = aci.Contract(args.contract, tenant) contract_sub = aci.ContractSubject(args.contract_sub, contract) # Create Filter filter = aci.Filter(args.filter, contract_sub) # Push the Contract to the APIC resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) if not resp.ok: print('%% Error: Could not push configuration to APIC') print(resp.text)
def main(): """ Main execution routine """ # Login to the APIC session = aci.Session(credentials.URL, credentials.LOGIN, credentials.PASSWORD) resp = session.login() if not resp.ok: print('%% Could not login to APIC') # Create the Tenant, App Profile, and EPG tenant = aci.Tenant(TENANT_NAME) app = aci.AppProfile(APP_NAME, tenant) epg = aci.EPG(EPG_NAME, app) # Create the physical interface object intf = aci.Interface(INTERFACE['type'], INTERFACE['pod'], INTERFACE['node'], INTERFACE['module'], INTERFACE['port']) # Create a VLAN interface and attach to the physical interface vlan_intf = aci.L2Interface(VLAN['name'], VLAN['encap_type'], VLAN['encap_id']) vlan_intf.attach(intf) # Attach the EPG to the VLAN interface epg.attach(vlan_intf) # Create the Endpoint mac = '00:11:11:11:11:11' ip = '10.10.5.5' ep = aci.Endpoint(name=mac, parent=epg) ep.mac = mac ep.ip = ip # Assign it to the L2Interface ep.attach(vlan_intf) print('JSON to be pushed: ' + str(tenant.get_json())) # Push it all to the APIC resp = tenant.push_to_apic(session) if not resp.ok: print('%% Error: Could not push configuration to APIC') print(resp.text)
def migration_tenant(self, tenant_name, app_name, provision=True): self.tenant = aci.Tenant(tenant_name) self.app = aci.AppProfile(app_name, self.tenant) self.context = aci.Context('default', self.tenant) self.contract = aci.Contract('allow-any', self.tenant) entry1 = aci.FilterEntry('default', applyToFrag='no', arpOpc='unspecified', etherT='unspecified', parent=self.contract) if provision: self.session.push_to_apic(self.tenant.get_url(), self.tenant.get_json()) else: self.tenant.get_json() return self.tenant
def lab2(course_partecipants, tenant_list = []): new_tenant_list = [] for cp in range(1, course_partecipants+1): tenant = aci.Tenant("MMTENANT{}".format(cp)) vrf = aci.Context("VRF-INSIDE", tenant) bd1 = aci.BridgeDomain("BD100", tenant) bd1.add_context(vrf) bd2 = aci.BridgeDomain("BD200", tenant) bd2.add_context(vrf) new_tenant_list.append(tenant) return new_tenant_list
def handle_create(self): tenant = aci.Tenant(self.tenant) contract = aci.Contract(str(self.properties['Contract']), tenant) rules = self.properties['Rules'] logger.info(rules) for entry in rules: entry = str(entry) if entry == 'any': aci.FilterEntry(entry, etherT='unspecified', parent=contract) break protocol_port = entry.split('-') aci.FilterEntry(entry, dFromPort=protocol_port[1], dToPort=protocol_port[1], etherT='ip', prot=protocol_port[0], parent=contract) url = tenant.get_url() data = tenant.get_json() logger.info(data) self.push_to_apic(url, data)
def Create_BD(aci_sheet, row): # call login function and return session session = apic_login() # create variables by importing values from spreadsheet tn_name = ACI.Tenant(aci_sheet.cell_value(row, 1)) VRF_name = ACI.Context(aci_sheet.cell_value(row, 3), tn_name) BD_name = ACI.BridgeDomain(aci_sheet.cell_value(row, 2), tn_name) advertise = aci_sheet.cell_value(row, 7) subnet = ACI.Subnet((aci_sheet.cell_value(row, 2) + '_subnet'), BD_name) subnet.set_addr(aci_sheet.cell_value(row, 6)) OutsideL3 = ACI.OutsideL3(aci_sheet.cell_value(row, 8), tn_name) L3_out = aci_sheet.cell_value(row, 8) BD_name.add_context(VRF_name) BD_name.add_subnet(subnet) if advertise == "yes": BD_name.add_l3out(OutsideL3) resp = session.push_to_apic(tn_name.get_url(), data=tn_name.get_json()) if resp.ok: print 'Bridge Domain %s deployed' % BD_name print '=' * 20
'type': 'eth', 'pod': '1', 'node': '101', 'module': '1', 'port': '65' } VLAN = {'name': 'vlan5', 'encap_type': 'vlan', 'encap_id': '5'} # Login to the APIC session = ACI.Session(credentials.URL, credentials.LOGIN, credentials.PASSWORD) resp = session.login() if not resp.ok: print '%% Could not login to APIC' # Create the Tenant, App Profile, and EPG tenant = ACI.Tenant(TENANT_NAME) app = ACI.AppProfile(APP_NAME, tenant) epg = ACI.EPG(EPG_NAME, app) # Create the physical interface object intf = ACI.Interface(INTERFACE['type'], INTERFACE['pod'], INTERFACE['node'], INTERFACE['module'], INTERFACE['port']) # Create a VLAN interface and attach to the physical interface vlan_intf = ACI.L2Interface(VLAN['name'], VLAN['encap_type'], VLAN['encap_id']) vlan_intf.attach(intf) # Attach the EPG to the VLAN interface epg.attach(vlan_intf) # Push it all to the APIC
URL = 'https://sandboxapicdc.cisco.com' LOGIN = '******' PASSWORD = '******' from credentials import * from acitoolkit import acitoolkit # connect to the apic session = acitoolkit.Session(URL, LOGIN, PASSWORD) session.login() # Create a Variable for your Tenant Name # Use your initials in the name # Example: "tenant_name = "js_Toolkit_Tenant"" tenant_name = "INITIALS_Toolkit_Tenant" # create a new tenant new_tenant = acitoolkit.Tenant(tenant_name) # commit the new configuration session.push_to_apic(new_tenant.get_url(), new_tenant.get_json())
def main(): """ Main create tenant routine :return: None """ # Get all the arguments description = 'It logs in to the APIC and will create the tenant.' creds = aci.Credentials('apic', description) creds.add_argument('-t', '--tenant', help='The name of tenant', default=TENANT_NAME) args = creds.get() # Login to the APIC session = aci.Session(args.url, args.login, args.password, subscription_enabled=False) resp = session.login() if not resp.ok: print('%% Could not login to APIC') # Create the Tenant tenant = aci.Tenant(TENANT_NAME) app = aci.AppProfile(APP_NAME, tenant) epg = aci.EPG(EPG_NAME, app) # Create a Context and BridgeDomain # Place both EPGs in the Context and in the same BD context = Context('VRF-1', tenant) bd = BridgeDomain('BD-1', tenant) bd.add_context(context) epg.add_bd(bd) # Define a contract with a single entry contract = Contract('mysql-contract', tenant) entry1 = FilterEntry('entry1', applyToFrag='no', arpOpc='unspecified', dFromPort='3306', dToPort='3306', etherT='ip', prot='tcp', sFromPort='1', sToPort='65535', tcpRules='unspecified', parent=contract) # Provide the contract from 1 EPG epg.provide(contract) # Create the physical interface object intf = aci.Interface(INTERFACE['type'], INTERFACE['pod'], INTERFACE['node'], INTERFACE['module'], INTERFACE['port']) # Create a VLAN interface and attach to the physical interface vlan_intf = aci.L2Interface(VLAN['name'], VLAN['encap_type'], VLAN['encap_id']) vlan_intf.attach(intf) # Attach the EPG to the VLAN interface epg.attach(vlan_intf) # Create the Endpoint mac = '00:11:11:11:11:11' ip = '10.2.1.4' # Assign it to the L2Interface #ep.attach(vlan_intf) # Push the tenant to the APIC resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) # Download all of the tenants print("-------------------------") print("LIST OF AVAILABLE TENANTS") print("-------------------------") tenants = aci.Tenant.get(session) for tenant in tenants: print(tenant.name) if not resp.ok: print('%% Error: Could not push configuration to APIC') print(resp.text)
description = 'It logs in to the APIC and will create the tenant.' parser = get_login_info(description) parser.add_argument('-t', '--tenant', help='The name of tenant', default=DEFAULT_TENANT_NAME) args = parser.parse_args() # Login to the APIC #session = ACI.Session(args.url, args.login, args.password) url = 'https://10.75.44.208:443' login = '******' password = '******' session = ACI.Session(url, login, password) resp = session.login() if not resp.ok: print '%% Could not login to APIC' # Create the Tenant, App Profile, and EPG tenant = ACI.Tenant(args.tenant) # Push it all to the APIC resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) if not resp.ok: print '%% Error: Could not push configuration to APIC' print resp.text
def main(): """ Main create tenant routine :return: None """ # Get all the arguments description = 'It logs in to the APIC and will create the tenant.' creds = aci.Credentials('apic', description) creds.add_argument('-t', '--tenant', help='The name of tenant', default=DEFAULT_TENANT_NAME) creds.add_argument('-a', '--app', help='The name of application profile', default=DEFAULT_APP_NAME) creds.add_argument('-e', '--epg', help='The name of EPG', default=DEFAULT_EPG_NAME) creds.add_argument('-b', '--bd', help='The name of bridge domain', default=DEFAULT_BD_NAME) creds.add_argument('-c', '--contract', help='The name of contract', default=DEFAULT_CONTRACT_NAME) args = creds.get() # Login to the APIC session = aci.Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print('%% Could not login to APIC') # Create the Tenant tenant = aci.Tenant(args.tenant) # Create the Application Profile app = aci.AppProfile(args.app, tenant) # Create the EPG epg = aci.EPG(args.epg, app) # Create the Bridge Domain bd = aci.BridgeDomain(args.bd, tenant) epg.add_bd(bd) # Create Contract contract = aci.Contract(args.contract, tenant) # Provide the contract from 1 EPG and consume from the other epg.provide(contract) epg.consume(contract) # Push the Application Profile EPG to the APIC resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) if not resp.ok: print('%% Error: Could not push configuration to APIC') print(resp.text)
from acitoolkit.acitoolkit import * import acitoolkit.acitoolkit as ACI #import credentials import csv # Define static values for VLAN encapsulation type VLAN = {'encap_type': 'vlan'} # Define Tenant, AppProfile, and EPG classes tenant = ACI.Tenant('ATX16-Tenant') app = ACI.AppProfile('myapp', tenant) epg = ACI.EPG('APP', app) # Get the APIC login credentials description = 'acitoolkit tutorial application' creds = Credentials('apic', description) creds.add_argument('--delete', action='store_true', help='Delete the configuration from the APIC') args = creds.get() # Delete the configuration if desired if args.delete: tenant.mark_as_deleted() # Login to APIC and push the config session = Session(args.url, args.login, args.password) session.login() resp = tenant.push_to_apic(session) if resp.ok: print ('Success')
def main(): # We're going to prompt the user for a desired tenant name to build from # and then return the name to ensure that its correct tenant = ACI.Tenant(input("Enter desired tenant name: ")) print("Tenant name is: " + tenant.name) # Application profile name is built from the tenant name # and printed to validate ap = ACI.AppProfile(tenant.name + "-AP", tenant) print("AppProfile name is: " + ap.name) # Two EGPs are created and tied to the previously created AP web_epg = ACI.EPG('web', ap) db_epg = ACI.EPG('db', ap) # A VRF is built from the tenant name and printed vrf = ACI.Context(tenant.name + "-CTX", tenant) print("VRF name is: " + vrf.name) # Build a bridge domain from tenant name, print tenant_bd = ACI.BridgeDomain(tenant.name + "-BD", tenant) print("BD name is: " + tenant_bd.name) # Finally, build the subnet from tenant name, print tenant_bd_subnet = ACI.Subnet(tenant.name + "-Subnet", tenant_bd) print("Subnet name is: " + tenant_bd_subnet.name) # For sake of exercise, we'll just statically assign the subnet for # the BD tenant_bd_subnet.addr = "10.1.1.1/24" # The BD is attached to the VRF, and options are set for flooding tenant_bd.add_context(vrf) tenant_bd.set_arp_flood('no') tenant_bd.set_unicast_route('yes') # Each of the EPGs is added to the previously created BD web_epg.add_bd(tenant_bd) db_epg.add_bd(tenant_bd) # The first contract, defining SQL and tied to our tenant. # The entry is tied to the contract and includes port and other info sql_contract = ACI.Contract('mssql-contract', tenant) sql_entry_1 = ACI.FilterEntry('ms-sql', applyToFrag='no', arpOpc='unspecified', dFromPort='1433', dToPort='1433', etherT='ip', prot='tcp', sFromPort='1', sToPort='65535', tcpRules='unspecified', parent=sql_contract) # The second contract will be for web services. Include 80 and 443 web_contract = ACI.Contract('web-contract', tenant) web_entry_1 = ACI.FilterEntry('http', applyToFrag='no', arpOpc='unspecified', dFromPort='80', dToPort='80', etherT='ip', prot='tcp', sFromPort='1', sToPort='65535', tcpRules='unspecified', parent=web_contract) web_entry_2 = ACI.FilterEntry('https', applyToFrag='no', arpOpc='unspecified', dFromPort='443', dToPort='443', etherT='ip', prot='tcp', sFromPort='1', sToPort='65535', tcpRules='unspecified', parent=web_contract) # The contracts are attached to the EPGs are providers, consumers db_epg.provide(sql_contract) web_epg.consume(sql_contract) web_epg.provide(web_contract) # Physical interfaces for attachment intf1 = ACI.Interface('eth', '1', '101', '1', '1') intf2 = ACI.Interface('eth', '1', '102', '1', '1') # Create a single VLAN for these interfaces. Remember, EPGs do the allow-list vl10_intf1_web = ACI.L2Interface('vl10_intf1_web', 'vlan', '10') vl10_intf2_db = ACI.L2Interface('vl10_intf2_db', 'vlan', '10') # Attach the logical to physical interface config vl10_intf1_web.attach(intf1) vl10_intf2_db.attach(intf2) # Finally attach the EPGs to the layer-2 interface configs web_epg.attach(vl10_intf1_web) db_epg.attach(vl10_intf2_db) # Now the actual "configuration push" is setup description = 'ACIToolkit mock full tenant configuration script' creds = ACI.Credentials('apic', description) # Adding in pieces for JSON only or delete the tenant creds.add_argument('--delete', action='store_true', help='Delete the configuration from the APIC') creds.add_argument('--json', const='false', nargs='?', help='JSON output only') args = creds.get() session = ACI.Session(args.url, args.login, args.password) session.login() # Several if/else to delete the tenant or print the JSON payload if args.delete: tenant.mark_as_deleted() if args.json: print("The following JSON payload was created") print("URL: ", tenant.get_url()) print(json.dumps(tenant.get_json(), indent=2)) else: resp = session.push_to_apic(tenant.get_url(),tenant.get_json()) # Some error handling along the way if not resp.ok: print("%% Error: Could not push configuration to APIC") print(resp.text) else: print("Success")
def create_unique(session): # Objects for the ESXi servers in a tenant uni_pn = 'ESXi_PN' uni_bd = 'ESXi_BD' uni_app = 'ESXi_mgmt' uni_1_epg = 'Management' uni_2_epg = 'VMotion' uni_3_epg = 'Storage_acc' ip_segments = [ '10.1.1.1/24', ] # Valid options for the scape are 'private', 'public', and 'shared'. Comma seperated, and NO spaces subnet_scope = 'private,shared' # Connect to the VMM Domain # This must already exist. It should have been created in this script vmmdomain = vmm_name # Setup or credentials and session description = ('Create EPGs for ESXi servers in a tenant.') # Get the virtual domain we are going to use vdomain = ACI.EPGDomain.get_by_name(session, vmmdomain) tenant = ACI.Tenant(unique_tenant) app = ACI.AppProfile(uni_app, tenant) # Create the EPGs u1_epg = ACI.EPG(uni_1_epg, app) u2_epg = ACI.EPG(uni_2_epg, app) u3_epg = ACI.EPG(uni_3_epg, app) # Create a Context and BridgeDomain # Place all EPGs in the Context and in the same BD context = ACI.Context(uni_pn, tenant) ubd = ACI.BridgeDomain(uni_bd, tenant) ubd.add_context(context) for subnet_ip in ip_segments: ran_name = [random.choice(string.hexdigits).lower() for n in xrange(6)] sub_name = ''.join(ran_name) asubnet = ACI.Subnet(sub_name, ubd) asubnet.set_addr(subnet_ip) asubnet.set_scope(subnet_scope) u1_epg.add_bd(ubd) u1_epg.add_infradomain(vdomain) u2_epg.add_bd(ubd) u2_epg.add_infradomain(vdomain) u3_epg.add_bd(ubd) ''' Define contracts with a multiple entries ''' contract1 = ACI.Contract('esxi_clients', tenant) filters = [['HTTPS', '443', 'tcp'], ['HTTP', '80', 'tcp'], ['SSH', '22', 'tcp']] for filt in filters: entry = ACI.FilterEntry(filt[0], applyToFrag='no', arpOpc='unspecified', dFromPort=filt[1], dToPort=filt[1], etherT='ip', prot=filt[2], tcpRules='unspecified', parent=contract1) # Attach the contracts u1_epg.provide(contract1) # CAUTION: The next line will DELETE the tenant # tenant.mark_as_deleted() resp = tenant.push_to_apic(session) if resp.ok: # Uncomment the next lines if you want to see the configuration # print('URL: ' + str(tenant.get_url())) # print('JSON: ' + str(tenant.get_json())) return True else: return False
# ------------------------------------------------ # Import ACI Toolkit import acitoolkit.acitoolkit as ACI # Suppress HTTPS certificate validation warning message import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() # Define static value for Tenant name Tenant_Name = 'Test' # Login to the APIC session = ACI.Session('https://10.54.61.56', 'admin', 'Cisco123') resp = session.login() if not resp.ok: print '%% Could not login to APIC' sys.exit(0) # Create the Tenant tenant = ACI.Tenant(Tenant_Name) # Display JSON code being sent to the APIC print "\n %s \n" % tenant.get_json() # Push it all to the APIC resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) if not resp.ok: print '%% Error: Could not push configuration to APIC' print resp.text
def Create_EPG(aci_sheet, row): # call login function and return session session = apic_login() # create variables by importing values from spreadsheet tn_name = ACI.Tenant(aci_sheet.cell_value(row, 1)) ANP_name = ACI.AppProfile(aci_sheet.cell_value(row, 2), tn_name) EPG_name = ACI.EPG(aci_sheet.cell_value(row, 3), ANP_name) print EPG_name BD_name = ACI.BridgeDomain(aci_sheet.cell_value(row, 8), tn_name) contract = ACI.Contract(aci_sheet.cell_value(row, 9), tn_name) direction = aci_sheet.cell_value(row, 10) vmm_name = ACI.EPGDomain.get_by_name(session, (aci_sheet.cell_value(row, 7))) phy_domain_name = ACI.EPGDomain.get_by_name(session, (aci_sheet.cell_value(row, 6))) #associated EPG with Bridge Domain EPG_name.add_bd(BD_name) #associate EPG with VMM DOmain if vmm_name == None: print "no VMM domain selected" else: EPG_name.add_infradomain(vmm_name) print "EPG %s associated with vmm domain %s" % (EPG_name, vmm_name) #set EPG for intra-EPG isolation #EPG_name.set_intra_epg_isolation('enforced') # figure out direction of provider/consumer relationship if direction == 'consume': EPG_name.consume(contract) elif direction == 'provide': EPG_name.provide(contract) elif direction == '' or 'None': print 'No provider or consumer direction selected' # define the physical interfaces #single_port matches the format that should be on the spreadsheet for a single port with the pod,leaf,blade,port format single_port = re.compile('.*/.*/.*/.*') #The vpc_port matches any text vpc_port = re.compile('.*.') get_phys = aci_sheet.cell_value(row,4) #if the description matches the single port format, the string is split into the different values if single_port.match(get_phys) is not None: get_phys_split = get_phys.split('/') intf1 = ACI.Interface('eth', get_phys_split[0], get_phys_split[1], get_phys_split[2], get_phys_split[3]) # define the encapsulation get_vlan_id = int(aci_sheet.cell_value(row, 5)) print get_vlan_id static_encap_if = ACI.L2Interface('encap_' + str(get_vlan_id), 'vlan', get_vlan_id) # attach encap to physical interface static_encap_if.attach(intf1) # attach static port binding to EPG EPG_name.attach(static_encap_if) print 'EPG %s is associated with interface %s with encap vlan-' % (EPG_name, intf1, get_vlan_id) #if the vpc_port matches, the second sheet of the spreadsheet is consulted to get the physical interfaces of the VPC name elif vpc_port.match(get_phys): phys_aci_book = xlrd.open_workbook("EPG_Input.xlsx") phys_aci_sheet = phys_aci_book.sheet_by_index(1) for row in range(phys_aci_sheet.nrows): for column in range(phys_aci_sheet.ncols): if phys_aci_sheet.cell_value(row, column) == get_phys: vpc_pair = phys_aci_sheet.cell_value(row,1) interface_selector = phys_aci_sheet.cell_value(row,2) vpc_leaf_split = vpc_pair.split('-') intf_selector_split = interface_selector.split(',') intf1 = ACI.Interface('eth', '1', vpc_leaf_split[0],'1',intf_selector_split[0]) intf2 = ACI.Interface('eth', '1', vpc_leaf_split[1],'1',intf_selector_split[0]) pc1 = ACI.PortChannel(get_phys) pc1.attach(intf1) pc1.attach(intf2) # define the encapsulation get_vlan_id = int(aci_sheet.cell_value(row, 5)) static_encap_if = ACI.L2Interface('encap_' + str(get_vlan_id), 'vlan', get_vlan_id) # attach encap to physical interface static_encap_if.attach(pc1) # attach static port binding to EPG EPG_name.attach(static_encap_if) print 'EPG %s is associated with VPC %s with encap vlan-%s' % (EPG_name, get_phys, get_vlan_id) #associate EPG with physical domain if phy_domain_name == None: print 'no physical domain selected' else: EPG_name.add_infradomain(phy_domain_name) print 'EPG %s associated with physical domain %s' % (EPG_name, phy_domain_name) # ensure tenant exists and push configuration resp = session.push_to_apic(tn_name.get_url(), data=tn_name.get_json()) if resp.ok: print 'Tenant %s deployed' % tn_name print 'EPG %s deployed' % EPG_name print '=' * 20
def two_ports(): if not connected(): if not collect_login(): return print '\n\n' print '=========================' print '== Connect Two Ports ==' print '=========================\n' # Basic Connectivity Example # Equivalent to connecting to ports to the same VLAN new_tenant = raw_input('Please enter a Tenant name: ') new_app = raw_input('Please enter an Application name: ') new_epg = new_app + '_EPG' # Create a tenant tenant = ACI.Tenant(new_tenant) # Create a Context and a BridgeDomain context = ACI.Context('VRF-1', tenant) context.set_allow_all() bd = ACI.BridgeDomain('BD-1', tenant) bd.add_context(context) # Create an App Profile and an EPG app = ACI.AppProfile(new_app, tenant) epg = ACI.EPG(new_epg, app) interfaces = ACI.Interface.get(session) for i in xrange(len(interfaces) - 1, -1, -1): if interfaces[i].porttype != 'leaf': del interfaces[i] interface1_in = interface2_in = -1 while interface1_in == -1 or interface2_in == -1: for a in range(len(interfaces)): name = interfaces[a].if_name print str(a) + ': ' + name input1 = raw_input('\nEnter the first interface: ') input2 = raw_input('\nEnter the second interface: ') try: interface1_in = int(input1) interface2_in = int(input2) if (0 > interface1_in > len(interfaces)) or (0 > interface1_in > len(interfaces)): interface1_in = interface2_in == -1 except: print '\nError: Please enter a number on the left side of the screen.' # Attach the EPG to 2 interfaces using VLAN 5 as the encap if1 = interfaces[interface1_in] if2 = interfaces[interface2_in] # if1 = ACI.Interface('eth','1','101','1','62') # if2 = ACI.Interface('eth','1','101','1','63') vlan5_on_if1 = ACI.L2Interface('vlan5_on_if1', 'vlan', '5') vlan5_on_if2 = ACI.L2Interface('vlan5_on_if2', 'vlan', '5') vlan5_on_if1.attach(if1) vlan5_on_if2.attach(if2) epg.attach(vlan5_on_if1) epg.attach(vlan5_on_if2) resp = session.push_to_apic(tenant.get_url(), data=tenant.get_json()) if resp.ok: print '\nSuccess' input = raw_input('\nPress Enter to continue ')
def main(): """ This is the main function of the script. From here, other functions are called. This script will take in the IP and credentials for an APIC, a new Tenant name, and a filename of existing VLANS This script can be used when the initial ACI Policy will map EPGs to existing client vlans This script takes in a list of existing vlans and creates the Tenant and corresponding VRF,ANP, EPG, and BO based on naming best practice. This script configures one ANP, mapped to one EPG and its corresponding BD for each vlan. Each BD is a member of one VRF. """ # Put relevant arguments passed to the script when the script was called in variables with east to understand names hostname, username, password, tenant_name, vlan_csv = sys.argv[1:] # Initialize and empty dictionary to hold the ANP=>EPG key value pairs epg_anp_dict = {} print "\n\n" + "="*20 + 'Creating Application Network Profiles and End Point Groups for each existing Vlan.' + "="*20 print "="*10 + "Processing VLAN file " + vlan_csv +' for new Tenant ' + tenant_name + ' by user ' + username + " on APIC " + hostname + "="*10 # Call the extract_vlan function, pass it the filename provided in the command line # This function will return a dictionary of vlan_id keys and vlan_name values vlans = extract_vlans(vlan_csv) # Now that we have a dictionary of our anp=>epg pairs, generat the ANP and EPG names to be configured in the APIC # Store those names in the epg_anp_dict dictionary for later use. for vlan_id,vlan_name in vlans.items(): #print vlan_id, vlan_name epg_name = "v"+vlan_id.strip()+"_"+vlan_name.upper().strip()+"_EPG" anp_name = "v"+vlan_id.strip()+"_"+vlan_name.upper().strip()+"_ANP" epg_anp_dict[anp_name]=epg_name #print epg_anp_dict print "="*10 + "Attempting to create Tenant " + tenant_name + ' by user ' + username + " on APIC " + hostname + "="*10 print "\n\tLogging in to APIC" # Establish a session to the apic whose parameters/credentials were passed as arguments on the command line apic_session = apic_login_acitk(hostname, username, password) # Call the print_tenant function which will return a list of all the tenants currently configured on the APIC # This list will be used to check to see if the tenant to be configured provided via an argument already exists tenants = print_tenant(apic_session) #print "modir ",modir #print "tenant_name ", tenant_name # If the tenant we are supposed to create already exists, primt a status message, print all the existing tenants, and exit the script. if tenant_name in tenants: print "\n\t Tenant <"+tenant_name+ "> already exists and does not need to be created.\n" for t in tenants: print "\t Tenant "+t + " exists." delete = raw_input("\n**** Would you like to delete the existing tenant " + tenant_name + " (Yes/No)? ****: ") #print "delete", str(delete) if delete.lower().strip() == 'no': print "\t\n Exiting Script.\n" sys.exit() else: delete2 = raw_input("\n**** Are you absolutely sure you want to delete the existing tenant <" + tenant_name + "> (Yes/No)? ****: ") print "\nSorry, I still need to figure out how to delete a tenant." print "\t\nExiting Script.\n" sys.exit() # If the tenant does not exist, create it and create the corresponding VRF else: print "\n\tCreating Tenant " + tenant_name #create_tenant(modir, tenant_name) # Create the tenant tenant = ACI.Tenant(tenant_name) #Configure a Private Network/VRF for the Tenant tenant_vrf = tenant_name + "_VRF" print "\n\tCreating Private Network\VRF " + tenant_vrf + " for Tenant " + tenant_name + "\n" context = ACI.Context(tenant_vrf, tenant) for anp, epg in epg_anp_dict.items(): # Create the App Profile, Bridge Domain, and EPG bd_name = re.sub("_EPG","_BD",epg ) #print "bd_name: ",bd_name print "\tCreating Application Profile " + anp + " with EPG " + epg + " and BD " + bd_name aciapp = ACI.AppProfile(anp, tenant) aciepg = ACI.EPG(epg, aciapp) acibd = ACI.BridgeDomain(bd_name, tenant) #Add the BD to the context acibd.add_context(context) #Add the BD to the EPG aciepg.add_bd(acibd) # Push it all to the APIC resp = tenant.push_to_apic(apic_session) if not resp.ok: print('%% Error: Could not push configuration to APIC') print(resp.text) print "\nLogging out of APIC"
def main(): args = parse_args() session = aci.Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print('%% Could not login to APIC') sys.exit(1) # Collect list of tenants from APIC tenants = aci.Tenant.get(session) if not args.tenant: # Print tenants and exit print('\nPlease specify a tenant with --tenant TENANT_NAME') print_object_names(tenants, 'Tenants') sys.exit(0) tenant = [t for t in tenants if t.name == args.tenant] if not tenant: print('Tenant {0} not found on APIC'.format(args.tenant)) sys.exit(1) tenant = tenant[0] # Collect list of apps from APIC apps = aci.AppProfile.get(session, tenant) if (args.parameters or args.cleanup) and not args.app: # Print apps and exit print('\nPlease specify an AppProfile with --app APP_NAME') print_object_names(apps, 'AppProfiles') sys.exit(0) if args.parameters or args.cleanup: app = [a for a in apps if a.name == args.app] if not app: print('AppProfile {0} not found on APIC'.format(args.app)) sys.exit(1) app = app[0] if args.dry_run: print( 'This is a dry-run, so none of the following is actually happening...' ) if args.parameters or args.cleanup or (args.revert and args.parameters): # Pull entire tenant config with folders, params, and relations tenant = aci.Tenant.get_deep(session, [args.tenant], ['vnsFolderInst'], config_only=True)[0] else: tenant = aci.Tenant(args.tenant) changes_made = False # Perform in-memory migration if args.parameters and not args.revert: changes_made = migrate_interface_folder_keys(tenant, args.app) or changes_made changes_made = migrate_ip(tenant, args.app) or changes_made changes_made = migrate_zones_and_vlans(tenant, args.app) or changes_made changes_made = migrate_default_gateway(tenant, args.app) or changes_made clusters = [] if args.clusters and not args.revert: clusters = migrate_clusters(tenant, session) if clusters: changes_made = True # Cleanup old 1.2 parameters (after migration) if args.cleanup and not args.revert: changes_made = cleanup_interface_folders(tenant, args.app) or changes_made # Revert to 1.2 parameters if args.revert and args.parameters: changes_made = delete_migrated_folders(tenant, args.app) or changes_made if not args.dry_run and changes_made: resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) if not resp.ok: print('%% Error: Could not push configuration to APIC') print(resp.text) sys.exit(1) else: print('Pushed changes to APIC') changes_made = revert_interface_folders(tenant, args.app) or changes_made if args.revert and args.clusters: clusters = revert_clusters(tenant, session) if clusters: changes_made = True # Assemble json json = tenant.get_json() if args.clusters and clusters: json['fvTenant']['children'].extend(clusters) if args.debug: from pprint import pprint pprint(json) # Apply changes to APIC if not args.dry_run: if changes_made: resp = session.push_to_apic(tenant.get_url(), json) if not resp.ok: print('%% Error: Could not push configuration to APIC') print(resp.text) sys.exit(1) else: print('Pushed changes to APIC') else: print('No changes made') else: print('Skipping push to APIC due to dry-run mode')
def main(): # Take login credentials from the command line if provided # Otherwise, take them from your environment variables file ~/.profile description = ('Simple application to build a Tenant/AP/EPG/BD/VRF') creds = aci.Credentials('apic', description) creds.add_argument('--delete', action='store_true', help='Delete the configuration from the APIC') creds.add_argument('--prefix', help='Prefix to use for all objects', default="mipetrin_acitoolkit") creds.add_argument('--amount', nargs='?', const=1, type=int, default=3, help='The total amount of iterations to complete') creds.add_argument('--test', action='store_true', help='Don\'t write to APIC. Print JSON output only') creds.add_argument('--debug', action='store_true', help='Verbose output') args = creds.get() name_prefix = args.prefix total_amount = args.amount debug_enabled = args.debug # Login to APIC session = aci.Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print('%% Could not login to APIC') return # Start time count at this point, otherwise takes into consideration the amount of time taken to input the password start_time = time.time() count = 1 while (count <= total_amount): if debug_enabled: print 'The count is:', count tenant = aci.Tenant(name_prefix + "_t" + str(count)) app = aci.AppProfile(name_prefix + "_app" + str(count), tenant) bd = aci.BridgeDomain(name_prefix + "_bd" + str(count), tenant) context = aci.Context(name_prefix + "_vrf" + str(count), tenant) epg = aci.EPG(name_prefix + "_epg" + str(count), app) bd.add_context(context) epg.add_bd(bd) # Delete the configuration if desired # WARNING - NO VALIDATION TAKES PLACE CURRENTLY. SIMPLY DELETES CONFIG # # WARNING - READ THAT AGAIN # # WARNING - NO VALIDATION TAKES PLACE CURRENTLY. SIMPLY DELETES CONFIG aborted = False abort_count = 0 if args.delete: #selection = None # First pass, ensure selection exists but no choice yet if debug_enabled: print "Checkpoint: args.delete" while 1: # raw_input returns an empty string for "enter" yes = {'yes', 'y', 'ye'} no = {'no', 'n', ''} selection = raw_input( "Are you absolutely sure you want to DELETE the entire tenant: [" + tenant.name + "]??? [y|N] ").lower() if selection in yes: # Uncomment the below line with caution. Wipes all tenants that match the criteria tenant.mark_as_deleted() print("Delete action is being performed...") print("-" * 30) break elif selection in no: # everything else to default to NO print "Aborting delete..." aborted = True print("-" * 30) break else: print "error state" if aborted: count = count + 1 # Ensure that we do loop to the next iteration from name perspective in an aborted scenario abort_count += 1 # Keep track of how many we abort/skip over deleting, per user selection continue # to the next iteration of the loop as no config push is required elif args.test: print(tenant.get_json()) else: # Push our json configuration to the APIC (either to be created or deleted) unless aborted #if aborted: # continue # to the next iteration of the loop as no config push is required resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) if resp.ok: # print 'Success:', count # Print what was sent if debug_enabled: print 'Success:', count print 'Pushed the following JSON to the APIC' print 'URL:', tenant.get_url() print 'JSON:', tenant.get_json() if not resp.ok: print('%% Error: Could not push configuration to APIC') print(resp.text) exit(0) count = count + 1 # Loop to the next iteration from name perspective for Test/Update print "=" * 80 if args.delete: print 'Attempted to delete the following object count:', total_amount - abort_count elif args.test: print 'Printed test output for a total object count:', total_amount else: print 'Successfully pushed total object count to the APIC:', total_amount print "=" * 80 print("#" * 80) finish_time = time.time() print("Started @ {}".format(time.asctime(time.localtime(start_time)))) print("Ended @ {}".format(time.asctime(time.localtime(finish_time)))) print("--- Total Execution Time: %s seconds ---" % (finish_time - start_time)) print("#" * 80)
# Login to the APIC session = aci.Session(raw_input("APIC URL: "), raw_input("APIC User Name: "), getpass.getpass()) resp = session.login() if not resp.ok: print('%% Could not login to APIC') # Selecting Tenant tenants = aci.Tenant.get(session) print("List of available Tenants:") for temp_tenant in tenants: print(temp_tenant) tenant_name = raw_input("\nPlease enter the Tenant name: ") tenant = aci.Tenant(tenant_name) # Selecting Application Profile application_profiles = aci.AppProfile.get(session, tenant) for temp_app_profile in application_profiles: print(temp_app_profile) app = aci.AppProfile(raw_input("List of Application Profiles: "), tenant) contexts = aci.Context.get(session, tenant) # Selecting VRF or Context for BDs to be created print("\nList of contexts available under the current Tenant: ") for temp_context in contexts: print(temp_context) context_name = raw_input("\nPlease enter a context for the new BDs: ") # Select VPC path, defaults to node 101 & 102, edit if required