def send_to_apic(): """ Login to APIC and push the config :param tenant: Tenant class instance :return: request response object """ description = 'Basic Connectivity Example' creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password, False) session.login() tenants = aci.Tenant.get(session) user_tenant = "OneView-APIC-Tenant-1" user_appProfile = "OneView-APIC-AppProfile-1" for tenant in tenants: if str(tenant) == user_tenant.strip(): apps = aci.AppProfile.get(session, tenant) for app in apps: if str(app) == user_appProfile: epg1 = "EPG" for number in range(0, 10): epgg = epg1 + str(number) epg = EPG(epgg, app) domains = aci.VmmDomain.get(session) for domain in domains: if str(domain) == "OneView-APIC-vSwitch-Bay1": epg.attach(domain) resp = tenant.push_to_apic(session)
def main(argv): global session, tenant, vmmInput if len(argv) > 2: vmmInput = argv[2] argv.remove(vmmInput) if len(argv) > 1: tenant = argv[1] argv.remove(tenant) # Setup or credentials and session description = ('Create some stuff.') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) session.login() # Get a good Virtual Domain to use while True: if check_virtual_domain(): break else: collect_vmmdomain() create_base() create_common_contracts.create_all_contracts(theTenant, session) create_ospf_egress.create_interface(theTenant, session, { 'provide': 'Outbound_Server', 'consume': 'Web' }) create_application_profiles() print("Everything seems to have worked if you are seeing this.")
def main(): global session # Setup or credentials and session description = ('Duplicate an application profile with the associate BD and PN') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) session.login() oldTenant = getOldTenant() newTenant = raw_input('Please enter the new Tenant name: ') if newTenant == '': error_message ([3,'You must specify a new tenant name.', True]) if oldTenant.name == newTenant: error_message ([3,'The same Tenant name can not be used.', True]) fullTenantInfo = getFullTeanantInfo(oldTenant) # Login to the system again so I can make direct rest calls without the acitoolkit admin = {"ip_addr":args.url,"user":args.login,"password":args.password} add_admin = oldSchoolLogin(admin) ''' Add the session urlToken for future use with security, and the refresh timeout for future use ''' admin.update({'urlToken':add_admin[0],'refreshTimeoutSeconds':add_admin[1], 'APIC-cookie':add_admin[2]}) createTenant(admin, newTenant, oldTenant.name, fullTenantInfo)
def main(): """ Main execution routine :return: None """ # Take login credentials from the command line if provided # Otherwise, take them from your environment variables description = "Simple application that logs on to the APIC and displays" " the physical inventory." creds = Credentials("apic", description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print("%% Could not login to APIC") sys.exit(0) # Print the inventory of each Pod pods = Pod.get(session) for pod in pods: pod.populate_children(deep=True) pod_name = "Pod: %s" % pod.name print(pod_name) print("=" * len(pod_name)) print_inventory(pod)
def main(): """ Create 2 EPGs within the same Context and have 1 EPG provide a contract to the other EPG. """ description = ('Create 2 EPGs within the same Context and have' '1 EPG provide a contract to the other EPG.') creds = Credentials('apic', description) args = creds.get() # Create the Tenant tenant = Tenant('aci-toolkit-demo') # Create the Application Profile app = AppProfile('my-demo-app', tenant) # Create the EPGs web_epg = EPG('web-frontend', app) db_epg = EPG('database-backend', app) web_epg.set_intra_epg_isolation(False) db_epg.set_intra_epg_isolation(True) # 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) web_epg.add_bd(bd) db_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 and consume from the other db_epg.provide(contract) web_epg.consume(contract) # Login to APIC and push the config session = Session(args.url, args.login, args.password) session.login() # Cleanup (uncomment the next line to delete the config) #tenant.mark_as_deleted() resp = tenant.push_to_apic(session) if resp.ok: # Print what was sent print('Pushed the following JSON to the APIC') print('URL: ' + str(tenant.get_url())) print('JSON: ' + str(tenant.get_json()))
def main(): """ Main execution routine :return: None """ # Take login credentials from the command line if provided # Otherwise, take them from your environment variables description = ('Simple application that logs on to the APIC and displays' ' the physical inventory.') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print('%% Could not login to APIC') sys.exit(0) # Print the inventory of each Pod pods = Pod.get(session) for pod in pods: pod.populate_children(deep=True) pod_name = 'Pod: %s' % pod.name print(pod_name) print('=' * len(pod_name)) print_inventory(pod)
def main(): global session # Setup or credentials and session description = ( 'Converts an IOS config to ACI EPGs in a Applicaiton Profile.') creds = Credentials('apic', description) args = creds.get() readconfigfile() print "\n\n" # printsvis() # Login to APIC session = Session(args.url, args.login, args.password) session.login() # Get a Tenant name while not get_tenant(): pass # Get a good Virtual Domain to use while not check_virtual_domain(): collect_vmmdomain() print "\nPushing configuration into the APIC now. Please wait." build_base() print("\nCreated {} SVIs from a total of {} SVIs that we found.".format( pushcount, str(len(all_svi))))
def main(): global session # Setup or credentials and session description = ('Converts an IOS config to ACI EPGs in a Applicaiton Profile.') creds = Credentials('apic', description) args = creds.get() readconfigfile() print "\n\n" # printsvis() # Login to APIC session = Session(args.url, args.login, args.password) session.login() # Get a Tenant name while not get_tenant(): pass # Get a good Virtual Domain to use while not check_virtual_domain(): collect_vmmdomain() print "\nPushing configuration into the APIC now. Please wait." build_base() print ("\nCreated {} SVIs from a total of {} SVIs that we found.".format(pushcount, str(len(all_svi))))
def main(): """ Main execution routine :return: None """ # Take login credentials from the command line if provided # Otherwise, take them from your environment variables file ~/.profile description = ( 'Simple application that logs on to the APIC and displays all' ' of the physical nodes; both belonging to and connected to the fabric.' ) creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print('%% Could not login to APIC') sys.exit(0) # List of classes to get and print phy_classes = (Node, ENode) for phy_class in phy_classes: # Print the class name class_name = phy_class.__name__ print(class_name) print('=' * len(class_name)) # Get and print all of the items from the APIC items = phy_class.get(session) for item in items: print(item.info())
def main(argv): global session, tenant, vmmInput if len(argv) > 2: vmmInput = argv[2] argv.remove(vmmInput) if len(argv) > 1: tenant = argv[1] argv.remove(tenant) # Setup or credentials and session description = ('Create some stuff.') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) session.login() # Get a good Virtual Domain to use while True: if check_virtual_domain(): break else: collect_vmmdomain() create_base() create_common_contracts.create_all_contracts(theTenant, session) create_ospf_egress.create_interface(theTenant, session, {'provide':'Outbound_Server', 'consume':'Web'}) create_application_profiles() print ("Everything seems to have worked if you are seeing this.")
def main(): """ Main execution routine :return: None """ # Take login credentials from the command line if provided # Otherwise, take them from your environment variables file ~/.profile description = ('Simple application that logs on to the APIC and displays all' ' of the physical nodes; both belonging to and connected to the fabric.') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print('%% Could not login to APIC') sys.exit(0) # List of classes to get and print phy_classes = (Node, ExternalSwitch) for phy_class in phy_classes: # Print the class name class_name = phy_class.__name__ print(class_name) print('=' * len(class_name)) # Get and print all of the items from the APIC items = phy_class.get(session) for item in items: print(item.info())
def get_apic_session(self): description = 'Basic Connectivity Example' creds = Credentials('apic', description) args = creds.get() apic_session = Session(args.url, args.login, args.password, False) apic_session.login() return apic_session
def main(): """ Create 2 Tenants with a single EPG in each. Between the 2 tenants, the EPGs communicate through an exported contract. """ description = ('Create 2 Tenants with a single EPG in each. Between the 2 tenants,' 'the EPGs communicate through an exported contract.Create 2 EPGs ' 'within the same Context and have 1 EPG provide a contract to the ' 'other EPG.') creds = Credentials('apic', description) args = creds.get() # Create the first Tenant tenant1 = Tenant('common') app1 = AppProfile('app-1', tenant1) web_epg = EPG('web-frontend', app1) # Create the second Tenant tenant2 = Tenant('aci-2') app2 = AppProfile('app-2', tenant2) db_epg = EPG('database-backend', app2) # Define a contract with a single entry contract = Contract('mysql-contract', tenant2) 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 db_epg.provide(contract) # Import the contract into the other tenant imported_contract = ContractInterface('mysql-imported-contract', tenant1) imported_contract.import_contract(contract) # Consume the contract in the second tenant web_epg.consume_cif(imported_contract) # Login to APIC and push the config session = Session(args.url, args.login, args.password) session.login() # Cleanup (uncomment the next 2 lines to delete the config) # tenant1.mark_as_deleted() # tenant2.mark_as_deleted() for tenant in [tenant2, tenant1]: resp = tenant.push_to_apic(session) if resp.ok: # Print what was sent print('Pushed the following JSON to the APIC') print('URL: ' + str(tenant.get_url())) print('JSON: ' + str(tenant.get_json()))
def main(): creds = Credentials('apic') args = creds.get() session = Session(args.url, args.login, args.password) session.login() tenant = 'A_SCRIPT_MADE_ME' theTenant = Tenant(tenant) create_interface(theTenant, session, {'provide':'Outbound_Server', 'consume':'Web'}) print ("Created a Layer 3 External gateway in tenant {}.".format(theTenant)) print ("Everything seems to have worked if you are seeing this.")
def main(): """ Main execution routine """ creds = Credentials('apic') args = creds.get() session = Session(args.url, args.login, args.password) session.login() tenant = Tenant('ATX16_l3Out') context = Context('vrf', tenant) outside_l3 = OutsideL3('out-1', tenant) outside_l3.add_context(context) phyif = Interface('eth', '1', '104', '1', '41') phyif.speed = '1G' l2if = L2Interface('eth 1/104/1/41', 'vlan', '1330') l2if.attach(phyif) l3if = L3Interface('l3if') #l3if.set_l3if_type('l3-port') l3if.set_l3if_type('sub-interface') l3if.set_mtu('1500') l3if.set_addr('1.1.1.2/30') l3if.add_context(context) l3if.attach(l2if) rtr = OSPFRouter('rtr-1') rtr.set_router_id('23.23.23.23') rtr.set_node_id('101') ifpol = OSPFInterfacePolicy('myospf-pol', tenant) ifpol.set_nw_type('p2p') ospfif = OSPFInterface('ospfif-1', router=rtr, area_id='1') ospfif.set_area_type('nssa') ospfif.auth_key = 'password' ospfif.int_policy_name = ifpol.name ospfif.auth_keyid = '1' ospfif.auth_type = 'simple' tenant.attach(ospfif) ospfif.networks.append('55.5.5.0/24') ospfif.attach(l3if) contract1 = Contract('contract-1') outside_epg = OutsideEPG('outepg', outside_l3) outside_epg.provide(contract1) contract2 = Contract('contract-2') outside_epg.consume(contract2) outside_l3.attach(ospfif) print(tenant.get_json()) 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 """ creds = Credentials('apic') args = creds.get() session = Session(args.url, args.login, args.password) session.login() tenant = Tenant('Cisco-Demo') context = Context('ctx1', tenant) outside_l3 = OutsideL3('out-1', tenant) outside_l3.add_context(context) phyif = Interface('eth', '1', '101', '1', '46') phyif.speed = '1G' l2if = L2Interface('eth 1/101/1/46', 'vlan', '1') l2if.attach(phyif) l3if = L3Interface('l3if') l3if.set_l3if_type('l3-port') l3if.set_mtu('1500') l3if.set_addr('1.1.1.2/30') l3if.add_context(context) l3if.attach(l2if) rtr = OSPFRouter('rtr-1') rtr.set_router_id('23.23.23.23') rtr.set_node_id('101') ifpol = OSPFInterfacePolicy('myospf-pol', tenant) ifpol.set_nw_type('p2p') ospfif = OSPFInterface('ospfif-1', router=rtr, area_id='1') ospfif.set_area_type('nssa') ospfif.auth_key = 'password' ospfif.int_policy_name = ifpol.name ospfif.auth_keyid = '1' ospfif.auth_type = 'simple' tenant.attach(ospfif) ospfif.networks.append('55.5.5.0/24') ospfif.attach(l3if) contract1 = Contract('contract-1') outside_epg = OutsideEPG('outepg', outside_l3) outside_epg.provide(contract1) contract2 = Contract('contract-2') outside_epg.consume(contract2) outside_l3.attach(ospfif) print(tenant.get_json()) 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(): creds = Credentials('apic') args = creds.get() session = Session(args.url, args.login, args.password) session.login() tenant = 'A_SCRIPT_MADE_ME' theTenant = Tenant(tenant) create_interface(theTenant, session, { 'provide': 'Outbound_Server', 'consume': 'Web' }) print("Created a Layer 3 External gateway in tenant {}.".format(theTenant)) print("Everything seems to have worked if you are seeing this.")
def acilint(): """ Main execution routine :return: None """ description = ('acilint - A static configuration analysis tool. ' 'Checks can be individually disabled by generating' ' and editing a configuration file. If no config ' 'file is given, all checks will be run.') creds = Credentials('apic', description) # this should get the creds from environment # Login to APIC session = Session(os.environ['APIC_URL'], os.environ['APIC_LOGIN'], os.environ['APIC_PASSWORD']) resp = session.login() html = None checker = Checker(session, 'html', html) if not resp.ok: checker.output_handler('%% Could not login to APIC') sys.exit(1) else: msg = "Successfully able to authenticate to the APIC APIC with status code {}".format( resp.status_code) print json.dumps({ "result": "Passed", "pluginResponse": msg, "pluginHTMLResponse": "<h1>{}</h1>".format(msg) })
def main(): # Setup or credentials and session description = ('Common contracts and filters') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) session.login() # This creates the tenant object theTenant = Tenant(tenant) create_all_contracts(theTenant, session) print ("Created common contracts and filters in the {} tenant.".format(theTenant)) print ("Everything seems to have worked if you are seeing this.")
def main(): global session # Setup or credentials and session description = ('Find the VMM Domain to use for EPGs') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) session.login() # Get a good Virtual Domain to use while True: if check_virtual_domain(): break else: collect_vmmdomain()
def send_to_apic(tenant): """ Login to APIC and push the config :param tenant: Tenant class instance :return: request response object """ description = 'Basic Connectivity Example' creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password, False) session.login() resp = tenant.push_to_apic(session) if resp.ok: print('Success') return resp
def main(): # Setup or credentials and session description = ('Common contracts and filters') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) session.login() # This creates the tenant object theTenant = Tenant(tenant) create_all_contracts(theTenant, session) print("Created common contracts and filters in the {} tenant.".format( theTenant)) print("Everything seems to have worked if you are seeing this.")
def main(): """ Main execution routine :return: None """ creds = Credentials('apic') args = creds.get() session = Session(args.url, args.login, args.password) session.login() tenant = Tenant('cisco') context = Context('ctx1', tenant) outside_l3 = OutsideL3('out-1', tenant) phyif = Interface('eth', '1', '101', '1', '46') phyif.speed = '1G' l2if = L2Interface('eth 1/101/1/46', 'vlan', '1') l2if.attach(phyif) l3if = L3Interface('l3if') l3if.set_l3if_type('l3-port') l3if.set_addr('1.1.1.2/30') l3if.add_context(context) l3if.attach(l2if) bgpif = BGPSession('test', peer_ip='1.1.1.1', node_id='101') bgpif.router_id = '172.1.1.1' bgpif.attach(l3if) bgpif.options = 'send-ext-com' bgpif.networks.append('0.0.0.0/0') contract1 = Contract('icmp') outside_epg = OutsideEPG('outepg', outside_l3) outside_epg.provide(contract1) outside_l3.add_context(context) outside_epg.consume(contract1) outside_l3.attach(bgpif) bgp_json = bgpif.get_json() 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 acilint(): """ Main execution routine :return: None """ description = ('acilint - A static configuration analysis tool. ' 'Checks can be individually disabled by generating' ' and editing a configuration file. If no config ' 'file is given, all checks will be run.') creds = Credentials('apic', description) # this should get the creds from environment # Login to APIC session = Session(os.environ['APIC_URL'], os.environ['APIC_LOGIN'], os.environ['APIC_PASSWORD']) resp = session.login() if not resp.ok: print('%% Could not login to APIC') sys.exit(1) html = open("tmp.html", "w") checker = Checker(session, 'html', html) methods = [] for method in dir(Checker): if method.startswith(('warning_', 'error_', 'critical_')): methods.append(method) if LIVE: html.write(""" <table border="2" style="width:100%"> <tr> <th>Severity</th> <th>Rule</th> <th>Description</th> </tr> """) checker.execute(methods) html.close() with open('tmp.html', 'r') as html: # resp = { "result": checker.result, "pluginHTMLResponse": html.read() } print json.dumps(resp) else: print json.dumps({"result": STATIC_RESULT})
def EPG_deletion(): description = 'Basic Connectivity Example' creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password, False) session.login() tenants = aci.Tenant.get(session) for tenant in tenants: apps = aci.AppProfile.get(session, tenant) for app in apps: epgs = aci.EPG.get(session, app, tenant) for epg in epgs: if re.match("EPG\d+", str(epg)): epg.mark_as_deleted() resp = tenant.push_to_apic(session) if resp.ok: print "Deleted", str(epg) else: print 'Could not delete tenant', str(epg) print resp.text
def acilint(): """ Main execution routine :return: None """ description = ('acilint - A static configuration analysis tool. ' 'Checks can be individually disabled by generating' ' and editing a configuration file. If no config ' 'file is given, all checks will be run.') creds = Credentials('apic', description) creds.add_argument('-c', '--configfile', type=argparse.FileType('r')) creds.add_argument('-g', '--generateconfigfile', type=argparse.FileType('w')) args = creds.get() if args.generateconfigfile: print 'Generating configuration file....' f = args.generateconfigfile f.write(('# acilint configuration file\n# Remove or comment out any ' 'warnings or errors that you no longer wish to see\n')) methods = dir(Checker) for method in methods: if method.startswith(('warning_', 'critical_', 'error_')): f.write(method + '\n') f.close() sys.exit(0) methods = [] if args.configfile: f = args.configfile for line in f: method = line.split('\n')[0] if method in dir(Checker) and method.startswith( ('warning_', 'error_', 'critical_')): methods.append(method) f.close() else: for method in dir(Checker): if method.startswith(('warning_', 'error_', 'critical_')): methods.append(method) if args.snapshotfiles: session = FakeSession(filenames=args.snapshotfiles) else: # Login to APIC session = Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print '%% Could not login to APIC' sys.exit(0) checker = Checker(session) checker.execute(methods)
def main(): global session # Setup or credentials and session description = ('Create a number of demo application profiles.') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) session.login() # Get a good Virtual Domain to use while True: if check_virtual_domain(): break else: collect_vmmdomain() create_base() create_application_profiles() print("Everything seems to have worked if you are seeing this.")
def main(): global session # Setup or credentials and session description = ('Create a number of demo application profiles.') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) session.login() # Get a good Virtual Domain to use while True: if check_virtual_domain(): break else: collect_vmmdomain() create_base() create_application_profiles() print ("Everything seems to have worked if you are seeing this.")
def main(): global session # Setup or credentials and session description = ( 'Duplicate an application profile with the associate BD and PN') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) session.login() oldTenant = getOldTenant() newTenant = raw_input('Please enter the new Tenant name: ') if newTenant == '': error_message([3, 'You must specify a new tenant name.', True]) if oldTenant.name == newTenant: error_message([3, 'The same Tenant name can not be used.', True]) fullTenantInfo = getFullTeanantInfo(oldTenant) # Login to the system again so I can make direct rest calls without the acitoolkit admin = { "ip_addr": args.url, "user": args.login, "password": args.password } add_admin = oldSchoolLogin(admin) ''' Add the session urlToken for future use with security, and the refresh timeout for future use ''' admin.update({ 'urlToken': add_admin[0], 'refreshTimeoutSeconds': add_admin[1], 'APIC-cookie': add_admin[2] }) createTenant(admin, newTenant, oldTenant.name, fullTenantInfo)
def acilint(): """ Main execution routine :return: None """ description = ('acilint - A static configuration analysis tool. ' 'Checks can be individually disabled by generating' ' and editing a configuration file. If no config ' 'file is given, all checks will be run.') creds = Credentials('apic', description) creds.add_argument('-c', '--configfile', type=argparse.FileType('r')) creds.add_argument('-g', '--generateconfigfile', type=argparse.FileType('w')) args = creds.get() if args.generateconfigfile: print 'Generating configuration file....' f = args.generateconfigfile f.write(('# acilint configuration file\n# Remove or comment out any ' 'warnings or errors that you no longer wish to see\n')) methods = dir(Checker) for method in methods: if method.startswith(('warning_', 'critical_', 'error_')): f.write(method + '\n') f.close() sys.exit(0) methods = [] if args.configfile: f = args.configfile for line in f: method = line.split('\n')[0] if method in dir(Checker) and method.startswith(('warning_', 'error_', 'critical_')): methods.append(method) f.close() else: for method in dir(Checker): if method.startswith(('warning_', 'error_', 'critical_')): methods.append(method) if args.snapshotfiles: session = FakeSession(filenames=args.snapshotfiles) else: # Login to APIC session = Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print '%% Could not login to APIC' sys.exit(0) checker = Checker(session) checker.execute(methods)
#local_site.register_for_callbacks('contracts', update_contract_db) update_contract_db() #local_site.register_for_callbacks('epgs', update_epg_db) update_epg_db() def dbfile_exists(): app_dir = op.realpath(os.path.dirname(__file__)) database_path = op.join(app_dir, app.config['DATABASE_FILE']) if os.path.exists(database_path): return True if __name__ == '__main__': description = ('ACI Multisite tool.') creds = Credentials('server', description) args = creds.get() LAB_TEST_MODE = args.test if dbfile_exists(): # Discard contract table as we will repopulate from APIC since it may be stale SiteContracts.query.delete() db.session.commit() SiteEpgs.query.delete() db.session.commit() # Initialize the collector if database file already exists at initial run sites = SiteCredentials.query.all() for site in sites: creds = SiteLoginCredentials(site.ip_address, site.user_name, site.password, site.use_https)
def get_interface_stats_from_nodes(): """ Main execution routine :return: None """ description = ('get_stats - A program to fetch statistics from an ACI ' 'Fabric.') creds = Credentials('apic', description) creds.add_argument('-f', '--format', required=False, default='text', help='Specify output format [csv, text]') creds.add_argument('-i', '--interval', required=False, default='15min', help='Specify the aggregation interval') creds.add_argument('-n', '--node_type', required=False, default='spine', help='Specify the type of node [spine, leaf, both]') creds.add_argument('-t', '--threshold', required=False, default=60, type=int, help='Specify the threshold for printing usage.') creds.add_argument('-v', '--verbose', action='count', help='Specify verbosity of debug output.') args = creds.get() if args.format not in ['text', 'csv']: print >> sys.stderr, "Error: Unknown output format: '{}'".format( args.format) sys.exit(3) if args.interval not in [ '5min', '15min', '1h', '1d', '1w', '1mo', '1qtr', '1year' ]: print >> sys.stderr, "Error: Unknown interval '{}'".format( args.interval) sys.exit(4) if args.node_type in ['spine', 'leaf']: node_type = [args.node_type] elif args.node_type in ['both']: node_type = ['spine', 'leaf'] else: print >> sys.stderr, "Error: Unknown node type: '{}'".format( args.node_type) sys.exit(5) if args.threshold > 100: threshold = 100 elif args.threshold < 0: threshold = 0 else: threshold = args.threshold # Login to APIC session = Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print '%% Could not login to APIC' sys.exit(0) statistics = Stats(session, args.format, args.verbose) statistics.get_int_traffic(node_type, args.interval, threshold)
def acilint(): """ Main execution routine :return: None """ description = ('acilint - A static configuration analysis tool. ' 'Checks can be individually disabled by generating' ' and editing a configuration file. If no config ' 'file is given, all checks will be run.') creds = Credentials('apic', description) creds.add_argument('-c', '--configfile', type=argparse.FileType('r')) creds.add_argument('-g', '--generateconfigfile', type=argparse.FileType('w')) creds.add_argument('-o', '--output', required=False, default='console') args = creds.get() if args.generateconfigfile: print('Generating configuration file....') f = args.generateconfigfile f.write(('# acilint configuration file\n# Remove or comment out any ' 'warnings or errors that you no longer wish to see\n')) methods = dir(Checker) for method in methods: if method.startswith(('warning_', 'critical_', 'error_')): f.write(method + '\n') f.close() sys.exit(0) methods = [] if args.configfile: f = args.configfile for line in f: method = line.split('\n')[0] if method in dir(Checker) and method.startswith(('warning_', 'error_', 'critical_')): methods.append(method) f.close() else: for method in dir(Checker): if method.startswith(('warning_', 'error_', 'critical_')): methods.append(method) if args.snapshotfiles: session = FakeSession(filenames=args.snapshotfiles) else: # Login to APIC session = Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print('%% Could not login to APIC') sys.exit(0) html = None if args.output == 'html': print('Creating file lint.html') html = open('lint.html', 'w') html.write(""" <table border="2" style="width:100%"> <tr> <th>Severity</th> <th>Rule</th> <th>Description</th> </tr> """) checker = Checker(session, args.output, html) checker.execute(methods)
# Start of the execution if __name__ == "__main__": items = {'left': {}, 'right': {}} # Argument parsing. We use the ACI toolkit logic here, which tries to # retrieve credentials from the following places: # 1. Command line options # 2. Configuration file called credentials.py # 3. Environment variables # 4. Interactively querying the user # At the end, we should have an object args with all the necessary info. description = 'APIC credentials' creds = Credentials('apic', description) creds.add_argument('-L', "--left", default=None, help='Object on the left') creds.add_argument('-R', "--right", default=None, help='Object on the right') creds.add_argument('-t', "--type", default=None, help='Object type') args = creds.get() # Arg validation if args.right is None: fatal( "[E] Right object missing. Please pass it using --right <obj_name>" ) if args.left is None: fatal(
# Start of the execution if __name__ == "__main__": items = {"left": {}, "right": {}} # Argument parsing. We use the ACI toolkit logic here, which tries to # retrieve credentials from the following places: # 1. Command line options # 2. Configuration file called credentials.py # 3. Environment variables # 4. Interactively querying the user # At the end, we should have an object args with all the necessary info. description = "APIC credentials" creds = Credentials("apic", description) creds.add_argument("-L", "--left", default=None, help="Object on the left") creds.add_argument("-R", "--right", default=None, help="Object on the right") creds.add_argument("-t", "--type", default=None, help="Object type") args = creds.get() # Arg validation if args.right is None: fatal("[E] Right object missing. Please pass it using --right <obj_name>") if args.left is None: fatal("[E] Left object missing. Please pass it using --left <obj_name>") if args.type is None: sys.stderr.write("[W] WARNING: No type supplied. Defaulting to 'Tenant'\n") args.type = "Tenant" # Process the supplied left and right data, according to the supplied type
from acitoolkit.acitoolkit import Session, Credentials, Tenant creds = Credentials('apic', 'Opis co skrypt robi.') args = creds.get() session = Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print 'Could not login to APIC' tenant = Tenant('mytenat') resp = session.push_to_apic(tenant.get_url(), tenant.get_json()) if not resp.ok: print 'Could not push configuration to APIC' print resp.text tenants = Tenant.get(session) for tenant in tenants: print tenant.name session.close()
def get_interface_stats_from_nodes(): """ Main execution routine :return: None """ description = ('get_stats - A program to fetch statistics from an ACI ' 'Fabric.') creds = Credentials('apic', description) creds.add_argument('-f', '--format', required=False, default='text', help='Specify output format [csv, text]') creds.add_argument('-i', '--interval', required=False, default='15min', help='Specify the aggregation interval') creds.add_argument('-n', '--node_type', required=False, default='spine', help='Specify the type of node [spine, leaf, both]') creds.add_argument('-t', '--threshold', required=False, default=60, type=int, help='Specify the threshold for printing usage.') creds.add_argument('-v', '--verbose', action='count', help='Specify verbosity of debug output.') args = creds.get() if args.format not in ['text', 'csv']: print >> sys.stderr, "Error: Unknown output format: '{}'".format( args.format) sys.exit(3) if args.interval not in ['5min', '15min', '1h', '1d', '1w', '1mo', '1qtr', '1year']: print >> sys.stderr, "Error: Unknown interval '{}'".format( args.interval) sys.exit(4) if args.node_type in ['spine', 'leaf']: node_type = [args.node_type] elif args.node_type in ['both']: node_type = ['spine', 'leaf'] else: print >> sys.stderr, "Error: Unknown node type: '{}'".format( args.node_type) sys.exit(5) if args.threshold > 100: threshold = 100 elif args.threshold < 0: threshold = 0 else: threshold = args.threshold # Login to APIC session = Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print('%% Could not login to APIC') sys.exit(0) statistics = Stats(session, args.format, args.verbose) statistics.get_int_traffic(node_type, args.interval, threshold)
def main(): required = collect_required() # Setup or credentials and session description = ('Create 5 EPGs within the same Context, have them ' 'provide and consume the same contract so that they ' 'can communicate between eachother.') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) session.login() # Get the virtual domain we are going to use try: vdomain = EPGDomain.get_by_name(session,required[1]) except: print "There was an error using " + required[1] + " as the VMMDomain. Are you sure it exists?" exit() # Create the Tenant tenant = Tenant(required[0]) # Create the Application Profile app = AppProfile(this_app, tenant) # Create the EPGs t1_epg = EPG(tier1_epg, app) t2_epg = EPG(tier2_epg, app) t3_epg = EPG(tier3_epg, app) t4_epg = EPG(tier4_epg, app) t5_epg = EPG(tier5_epg, app) # Create a Context and BridgeDomain # Place all EPGs in the Context and in the same BD context = Context(private_net, tenant) bd = BridgeDomain(bridge_domain, tenant) bd.add_context(context) # Add all the IP Addresses to the bridge domain bd_subnet5 = Subnet(tier1_epg, bd) bd_subnet5.set_addr(tier1_subnet) bd_subnet5.set_scope(subnet_scope) bd.add_subnet(bd_subnet5) bd_subnet6 = Subnet(tier2_epg, bd) bd_subnet6.set_addr(tier2_subnet) bd_subnet6.set_scope(subnet_scope) bd.add_subnet(bd_subnet6) bd_subnet7 = Subnet(tier3_epg, bd) bd_subnet7.set_addr(tier3_subnet) bd_subnet7.set_scope(subnet_scope) bd.add_subnet(bd_subnet7) bd_subnet8 = Subnet(tier4_epg, bd) bd_subnet8.set_addr(tier4_subnet) bd_subnet8.set_scope(subnet_scope) bd.add_subnet(bd_subnet8) bd_subnet9 = Subnet(tier5_epg, bd) bd_subnet9.set_addr(tier5_subnet) bd_subnet9.set_scope(subnet_scope) bd.add_subnet(bd_subnet9) t1_epg.add_bd(bd) t1_epg.add_infradomain(vdomain) t2_epg.add_bd(bd) t2_epg.add_infradomain(vdomain) t3_epg.add_bd(bd) t3_epg.add_infradomain(vdomain) t4_epg.add_bd(bd) t4_epg.add_infradomain(vdomain) t5_epg.add_bd(bd) t5_epg.add_infradomain(vdomain) ''' Define a contract with a single entry Additional entries can be added by duplicating "entry1" ''' contract1 = Contract('allow_all', tenant) entry1 = FilterEntry('all', applyToFrag='no', arpOpc='unspecified', dFromPort='unspecified', dToPort='unspecified', etherT='unspecified', prot='unspecified', tcpRules='unspecified', parent=contract1) # All the EPGs provide and consume the contract t1_epg.consume(contract1) t1_epg.provide(contract1) t2_epg.consume(contract1) t2_epg.provide(contract1) t3_epg.consume(contract1) t3_epg.provide(contract1) t4_epg.consume(contract1) t4_epg.provide(contract1) t5_epg.consume(contract1) t5_epg.provide(contract1) # Finally, push all this to the APIC # Cleanup (uncomment the next line to delete the config) # CAUTION: The next line will DELETE the tenant # tenant.mark_as_deleted() resp = tenant.push_to_apic(session) if resp.ok: # Print some confirmation print('The configuration was sucessfully pushed to the APIC.') # Uncomment the next lines if you want to see the configuration # print('URL: ' + str(tenant.get_url())) # print('JSON: ' + str(tenant.get_json())) else: print resp print resp.text print('URL: ' + str(tenant.get_url())) print('JSON: ' + str(tenant.get_json()))
def run(): # Argument parsing. We use the ACI toolkit logic here, which tries to # retrieve credentials from the following places: # 1. Command line options # 2. Configuration file called credentials.py # 3. Environment variables # 4. Interactively querying the user # At the end, we should have an object args with all the necessary info. description = 'APIC credentials' creds = Credentials('apic', description) creds.add_argument('-d', "--debug", default=None, help='Enable debug mode') creds.add_argument('-A', "--address", default=None, help='Local IP address') creds.add_argument('-P', "--port", default=None, help='Local Port for FTP connections') creds.add_argument('-K', "--key", default=None, help='ACI encryption key') args = creds.get() # Print welcome banner ACIExport.print_banner() # Let's check if the user passed all relevant parameters if args.debug is not None: debug_enable() if args.address is None: # If the user didn't pass any IP address, let's figure out what IPs we # have configured locally. If it's only one, use it. Otherwise, ask # the user interactively to pick one candidates = {} for iface in netifaces.interfaces(): for addr in netifaces.ifaddresses(iface): addr_str = netifaces.ifaddresses(iface)[addr][0]['addr'] # Skip IPv6 addresses if addr_str.count(":") > 0: continue # Skip localhost and unassigned addresses elif addr_str == "0.0.0.0" or addr_str == "127.0.0.1": continue # Skip Microsoft auto-assigned addresses elif addr_str.startswith("169.254."): continue else: candidates[addr_str] = addr_str output( "Please indicate which local IP address should be used (enter its sequence number):" ) for i in range(0, len(candidates)): print(" -> [%i] %s" % (i, candidates.keys()[i])) answer = -1 while (not (answer >= 0 and answer < len(candidates))): try: answer = int(input("$: ")) except: continue args.address = candidates[candidates.keys()[answer]] output("Address selected: %s" % args.address) if args.port is None: args.port = DEFAULT_FTP_PORT else: args.port = int(args.port) if args.key is None: args.key = DEFAULT_KEY # Now, we log into the APIC fabric = Fabric(args.url, args.login, args.password) fabric.connect() # Instance our FTP server ftplistener = FTPListener(addr=args.address, port=args.port) ftplistener.daemon = True ftplistener.start() # Nasty thing: sleep for 1 sec to give enough time to the FTP server to # initialize @todo: use decent concurrency control mechanisms time.sleep(1) # Push config to the fabric pols = ConfExportPolicy(addr=args.address, port=args.port, key=args.key) fabric.push_to_apic(pols) output( "Waiting for the ACI fabric to send its configuration export file..." ) while g_do_exit is False: time.sleep(1) output("File '%s' was successfully received. Closing..." % g_recv_file) output("Please make a note of the encryption key: '%s'" % args.key) # Finally, stop the server and quit ftplistener.stop() return True
output(" |_| |___/ ") output(" ") output(" == A tool to deploy physical configuration on an ACI fabric == \n") # Start of the execution if __name__ == "__main__": # Argument parsing. We use the ACI toolkit logic here, which tries to # retrieve credentials from the following places: # 1. Command line options # 2. Configuration file called credentials.py # 3. Environment variables # 4. Interactively querying the user # At the end, we should have an object args with all the necessary info. description = 'APIC credentials' creds = Credentials('apic', description) creds.add_argument('-i', "--input", default=None, help='Input file') creds.add_argument('-d', "--debug", default=None, help='Input file') args = creds.get() # Let's check if the user passed all relevant parameters if args.input is None: fatal("[E] Input filename missing. Please pass it using --input <filename>") if args.debug is not None: debug_enable() # First of all, parse the input file. data = parse_spreadsheet(args.input) interfaces = [] # List of interfaces to push to the fabric
if "Rs" not in key and key not in not_interesting_classes: output("%s:%s was %s" % (key, obj[key]['attributes']['dn'], obj[key]['attributes']['status']) ) # Start of the execution if __name__ == "__main__": # Argument parsing. We use the ACI toolkit logic here, which tries to # retrieve credentials from the following places: # 1. Command line options # 2. Configuration file called credentials.py # 3. Environment variables # 4. Interactively querying the user # At the end, we should have an object args with all the necessary info. description = 'APIC credentials' creds = Credentials('apic', description) creds.add_argument('-d', "--debug", default=None, help='Enable Debug mode') args = creds.get() # Process all relevant command-line parameters and print our welcome banner if args.debug is not None: debug_enable() print_banner() # Now, we log into the APIC session = Session(args.url, args.login, args.password) response = session.login() if response.ok is False: fatal(response.content) else: output("Successfully connected to %s" % args.url)
def main(): """ Create 2 Tenants with a single EPG in each. Between the 2 tenants, the EPGs communicate through an exported contract. """ description = ( "Create 2 Tenants with a single EPG in each. Between the 2 tenants," "the EPGs communicate through an exported contract.Create 2 EPGs " "within the same Context and have 1 EPG provide a contract to the " "other EPG." ) creds = Credentials("apic", description) args = creds.get() # Create the first Tenant tenant1 = Tenant("aci-toolkit-demo-1") app1 = AppProfile("my-demo-app-1", tenant1) web_epg = EPG("web-frontend", app1) # Create the second Tenant tenant2 = Tenant("aci-toolkit-demo-2") app2 = AppProfile("my-demo-app-2", tenant2) db_epg = EPG("database-backend", app2) # Define a contract with a single entry contract = Contract("mysql-contract", tenant2) 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 db_epg.provide(contract) # Import the contract into the other tenant imported_contract = ContractInterface("mysql-imported-contract", tenant1) imported_contract.import_contract(contract) # Consume the contract in the second tenant web_epg.consume_cif(imported_contract) # Login to APIC and push the config session = Session(args.url, args.login, args.password) session.login() # Cleanup (uncomment the next 2 lines to delete the config) # tenant1.mark_as_deleted() # tenant2.mark_as_deleted() for tenant in [tenant2, tenant1]: resp = tenant.push_to_apic(session) if resp.ok: # Print what was sent print("Pushed the following JSON to the APIC") print("URL: " + str(tenant.get_url())) print("JSON: " + str(tenant.get_json()))
</tfoot> <tbody> %s </tbody> </table> </div> <script type="text/javascript"> // For demo to fit into DataTables site builder... $('#example') .removeClass( 'display' ) .addClass('table table-striped table-bordered'); </script> </body> </html> """ % populate_data(args.mysqlip, args.mysqllogin, args.mysqlpassword) if __name__ == '__main__': global args # Take login credentials from the command line if provided # Otherwise, take them from your environment variables file ~/.profile description = 'Simple application that logs on to the APIC and displays all of the Endpoints.' creds = Credentials('mysql', description) args = creds.get() app.run(debug=True)
from acitoolkit.aciphysobject import * from acitoolkit.acitoolkit import Credentials def print_inventory(item): for child in item.get_children(): print_inventory(child) print item.info() # Take login credentials from the command line if provided # Otherwise, take them from your environment variables description = ('Simple application that logs on to the APIC and displays' ' the physical inventory.') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) resp = session.login() if not resp.ok: print '%% Could not login to APIC' sys.exit(0) # Print the inventory of each Pod pods = Pod.get(session) for pod in pods: pod.populate_children(deep=True) pod_name = 'Pod: %s' % pod.name print pod_name
versions = cdb.get_versions(with_changes=True) if versions is None: return for (version, additions, deletions) in versions: for (filename, adds, dels) in cdb.get_filenames(version, prev_version=prev_version, with_changes=True): snapshot = Snapshots() snapshot.version = version snapshot.filename = filename snapshot.changes = adds + '/' + dels is_latest = (version == cdb.get_latest_file_version(filename)) snapshot.latest = is_latest db.session.add(snapshot) prev_version = version db.session.commit() return if __name__ == '__main__': description = ('ACI Configuration Snapshot and Rollback tool.') creds = Credentials('server', description) args = creds.get() # Build the database build_db() # Start app app.run(debug=True, host=args.ip, port=int(args.port))
def main(): """ Main execution routine :return: None """ creds = Credentials('apic') creds.add_argument('--tenant', help='The name of Tenant') creds.add_argument('--vrf', help='The name of VRF') creds.add_argument('--bd', help='The name of BridgeDomain') creds.add_argument('--address', help='Subnet IPv4 Address') creds.add_argument('--scope', help='The scope of subnet ("public", "private", "shared", "public,shared", "private,shared", "shared,public", "shared,private")') args = creds.get() session = Session(args.url, args.login, args.password) session.login() tenant = Tenant(args.tenant) vrf = Context(args.vrf) bd = BridgeDomain(args.bd, tenant) bd.add_context(vrf) if args.address is None: bd.set_arp_flood('yes') bd.set_unicast_route('no') else: bd.set_arp_flood('no') bd.set_unicast_route('yes') subnet = Subnet('', bd) subnet.addr = args.address if args.scope is None: subnet.set_scope("private") else: subnet.set_scope(args.scope) 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(): # Setup or credentials and session description = ('Create 3 EPGs within the same Context, have them ' 'provide and consume contracts and attach them to ' 'a vmm domain.') creds = Credentials('apic', description) args = creds.get() # Login to APIC session = Session(args.url, args.login, args.password) session.login() # Get the virtual domain we are going to use vdomain = EPGDomain.get_by_name(session,vmmdomain) # Create the Tenant tenant = Tenant(this_tenant) # Create the Application Profile app = AppProfile(this_app, tenant) # Create the EPGs t1_epg = EPG(tier1_epg, app) t2_epg = EPG(tier2_epg, app) t3_epg = EPG(tier3_epg, app) # Create a Context and BridgeDomain # Place all EPGs in the Context and in the same BD context = Context(private_net, tenant) bd = BridgeDomain(bridge_domain, tenant) bd.add_context(context) t1_epg.add_bd(bd) t1_epg.add_infradomain(vdomain) t2_epg.add_bd(bd) t2_epg.add_infradomain(vdomain) t3_epg.add_bd(bd) ''' Define a contract with a single entry Additional entries can be added by duplicating the FilterEntry Push to APIC after each FilterEntry if it is not the last ''' contract1 = Contract('mysql-contract', tenant) entry1 = FilterEntry('SQL', applyToFrag='no', arpOpc='unspecified', dFromPort='3306', dToPort='3306', etherT='ip', prot='tcp', tcpRules='unspecified', parent=contract1) contract2 = Contract('app-contract', tenant) contract2.set_scope('application-profile') entry1 = FilterEntry('Flask', applyToFrag='no', arpOpc='unspecified', dFromPort='5000', dToPort='5000', etherT='ip', prot='tcp', tcpRules='unspecified', parent=contract2) tenant.push_to_apic(session) entry2 = FilterEntry('Flask2', applyToFrag='no', arpOpc='unspecified', dFromPort='5050', dToPort='5050', etherT='ip', prot='tcp', tcpRules='unspecified', parent=contract2) contract3 = Contract('web-contract', tenant) contract3.set_scope('application-profile') entry1 = FilterEntry('HTTPS', applyToFrag='no', arpOpc='unspecified', dFromPort='443', dToPort='443', etherT='ip', prot='tcp', tcpRules='unspecified', parent=contract3) # Provide the contract from 1 EPG and consume from the other t3_epg.provide(contract1) t2_epg.consume(contract1) t2_epg.provide(contract2) t1_epg.consume(contract2) t1_epg.provide(contract3) # Finally, push all this to the APIC # Cleanup (uncomment the next line to delete the config) # CAUTION: The next line will DELETE the tenant # tenant.mark_as_deleted() resp = tenant.push_to_apic(session) if resp.ok: # Print some confirmation print('The configuration was sucessfully pushed to the APIC.')
def main(): description = ('Create 3 EPGs within the same Bridge Domain and have' '2 EPGs provide a contract to the other EPG.') creds = Credentials('apic', description) args = creds.get() # Login to APIC and push the config session = Session(args.url, args.login, args.password, verify_ssl=False) log = session.login() if log.ok: print('Login to APIC successful !!!') if not log.ok: print('Error: Could not login to APIC') print(log.status_code) # Create the Tenant name_tenant = input('Enter Tenant name: ') tenant = Tenant(name_tenant) tenant_resp = tenant.push_to_apic(session) if tenant_resp.ok: print('Tenant created successfully !!!') if not tenant_resp.ok: print('Error: Could not create Tenant') print(tenant_resp.status_code) # Gets vmm domain from APIC vmm = VmmDomain.get_by_name(session, 'vCenter-ACI') vmm_resp = tenant.push_to_apic(session) if vmm_resp.ok: print('VmmDomain: vCenter-ACI, opened successfully !!!') if not vmm_resp.ok: print('Error: Could not open VmmDomain: vCenter-ACI') print(vmm_resp.status_code) # Create the Application Profile name_ap = input('Enter Application Profile name: ') app = AppProfile(name_ap, tenant) app_resp = tenant.push_to_apic(session) if app_resp.ok: print('Application Profile created successfully !!!') if not app_resp.ok: print('Error: Could not create Application Profile') print(app_resp.status_code) # Create the WEB EPG web_epg = EPG('WEB', app) web_resp = tenant.push_to_apic(session) if web_resp.ok: print('WEB epg created successfully !!!') if not web_resp.ok: print('Error: Could not create WEB epg') print(web_resp.status_code) # Create the DATA EPG db_epg = EPG('DATA', app) db_resp = tenant.push_to_apic(session) if db_resp.ok: print('DATA epg created successfully !!!') if not db_resp.ok: print('Error: Could not create DATA epg') print(db_epg.status_code) # Create the APP EPG app_epg = EPG('APP', app) app_resp = tenant.push_to_apic(session) if app_resp.ok: print('APP epg created successfully !!!') if not app_resp.ok: print('Error: Could not create APP epg') print(app_epg.status_code) # Associating EPGs to Vmm Domain web_epg.attach(vmm) db_epg.attach(vmm) app_epg.attach(vmm) # Create a BridgeDomain # Place both EPGs in the Context and in the same BD bd = BridgeDomain('BD-1', tenant) web_epg.add_bd(bd) db_epg.add_bd(bd) app_epg.add_bd(bd) # Define web-to app contract contract1 = Contract('web-to-app', tenant) entry1 = FilterEntry('entry1', applyToFrag='no', arpOpc='unspecified', dFromPort='443', dToPort='443', etherT='ip', prot='tcp', sFromPort='1', sToPort='65535', tcpRules='unspecified', parent=contract1) # Define app-to-data contract contract2 = Contract('app-to-data', tenant) entry2 = FilterEntry('entry2', applyToFrag='no', arpOpc='unspecified', dFromPort='1433', dToPort='1433', etherT='ip', prot='tcp', sFromPort='1', sToPort='65535', tcpRules='unspecified', parent=contract2) # Provide the contract from 1 EPG and consume from the other db_epg.provide(contract2) web_epg.provide(contract1) app_epg.consume(contract1) app_epg.consume(contract2) ########### ClEANUP (uncomment the next line to delete the tenant) #tenant.mark_as_deleted() #################################### #Push all the config to apic resp = tenant.push_to_apic(session) if resp.ok: print('All the configuration was pushed to APIC !!!') if not resp.ok: print('Error: Could not push configuration to APIC') print(resp.status_code)
def run(): # Argument parsing. We use the ACI toolkit logic here, which tries to # retrieve credentials from the following places: # 1. Command line options # 2. Configuration file called credentials.py # 3. Environment variables # 4. Interactively querying the user # At the end, we should have an object args with all the necessary info. description = "APIC credentials" creds = Credentials("apic", description) creds.add_argument("-d", "--debug", default=None, help="Enable debug mode") creds.add_argument("-A", "--address", default=None, help="Local IP address") creds.add_argument("-P", "--port", default=None, help="Local Port for FTP connections") creds.add_argument("-K", "--key", default=None, help="ACI encryption key") args = creds.get() # Print welcome banner ACIExport.print_banner() # Let's check if the user passed all relevant parameters if args.debug is not None: debug_enable() if args.address is None: # If the user didn't pass any IP address, let's figure out what IPs we # have configured locally. If it's only one, use it. Otherwise, ask # the user interactively to pick one candidates = {} for iface in netifaces.interfaces(): for addr in netifaces.ifaddresses(iface): addr_str = netifaces.ifaddresses(iface)[addr][0]["addr"] # Skip IPv6 addresses if addr_str.count(":") > 0: continue # Skip localhost and unassigned addresses elif addr_str == "0.0.0.0" or addr_str == "127.0.0.1": continue # Skip Microsoft auto-assigned addresses elif addr_str.startswith("169.254."): continue else: candidates[addr_str] = addr_str output("Please indicate which local IP address should be used (enter its sequence number):") for i in range(0, len(candidates)): print(" -> [%i] %s" % (i, candidates.keys()[i])) answer = -1 while not (answer >= 0 and answer < len(candidates)): try: answer = int(input("$: ")) except: continue args.address = candidates[candidates.keys()[answer]] output("Address selected: %s" % args.address) if args.port is None: args.port = DEFAULT_FTP_PORT else: args.port = int(args.port) if args.key is None: args.key = DEFAULT_KEY # Now, we log into the APIC fabric = Fabric(args.url, args.login, args.password) fabric.connect() # Instance our FTP server ftplistener = FTPListener(addr=args.address, port=args.port) ftplistener.daemon = True ftplistener.start() # Nasty thing: sleep for 1 sec to give enough time to the FTP server to # initialize @todo: use decent concurrency control mechanisms time.sleep(1) # Push config to the fabric pols = ConfExportPolicy(addr=args.address, port=args.port, key=args.key) fabric.push_to_apic(pols) output("Waiting for the ACI fabric to send its configuration export file...") while g_do_exit is False: time.sleep(1) output("File '%s' was successfully received. Closing..." % g_recv_file) output("Please make a note of the encryption key: '%s'" % args.key) # Finally, stop the server and quit ftplistener.stop() return True