Esempio n. 1
0
def create_add_server_EPG(tenant, app, epg, interface, vlan):

    # Create the Tenant, App Profile, and EPG
    #     tenant = ACI.Tenant(tenant_name)
    #     app = ACI.AppProfile(app_name, tenant_name)
    #     epg = ACI.EPG(epg_name, app_name)

    if not connected():
        if not collect_login():
            return

    # 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
    response = session.push_to_apic(tenant.get_url(), tenant.get_json())

    decoded_response = json.loads(response.text)

    if not response.ok:
        print '%% Error: Could not push configuration to APIC'
        error_message([
            decoded_response['imdata'][0]['error']['attributes']['code'],
            decoded_response['imdata'][0]['error']['attributes']['text'], -1
        ])
Esempio n. 2
0
    def remove_port_from_epg(self, pod, node, fex, module, port, vlan_id,
                             port_mode, tenant_name, app_profile_name,
                             epg_name):
        """

        :param pod:
        :param node:
        :param fex:
        :param module:
        :param port:
        :param vlan_id:
        :param port_mode:
        :param tenant_name:
        :param app_profile_name:
        :param epg_name:
        :return:
        """
        tenant = self.get_tenant(tenant_name)

        app = aci.AppProfile(app_profile_name, tenant)
        epg = aci.EPG(epg_name=epg_name, parent=app)

        # create the physical interface object
        if fex is None:
            intf = aci.Interface(interface_type=INTERFACE_TYPE,
                                 pod=pod,
                                 node=node,
                                 module=module,
                                 port=port)
        else:
            intf = FixedFexInterface(if_type=INTERFACE_TYPE,
                                     pod=pod,
                                     node=node,
                                     fex=fex,
                                     module=module,
                                     port=port)

        # create a VLAN interface and attach to the physical interface
        vlan_intf = aci.L2Interface(name=vlan_id,
                                    encap_type=L2_INTERFACE_ENCAP_TYPE,
                                    encap_id=vlan_id,
                                    encap_mode=PORT_MODE_MAP[port_mode])

        vlan_intf.attach(intf)

        # attach EPG to the VLAN interface
        epg.detach(vlan_intf)

        # push the tenant config to the APIC
        resp = tenant.push_to_apic(self._session)
        self._logger.info("Pushed Tenant data {}".format(tenant.get_json()))

        if not resp.ok:
            raise Exception(
                'Could not push tenant configuration to APIC. Error response: {}'
                .format(resp.content))
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)
        csv_port = row['Port']
        csv_epg = row['EPG']
        # if statements to assign the appropriate EPG to the EPG class
        # depedning on the contents of the EPG value in the csv file
        if csv_epg == 'APP':
            epg = ACI.EPG('APP', app)
        elif csv_epg == 'WEB':
            epg = ACI.EPG('WEB', app)
        elif csv_epg == 'DB':
            epg = ACI.EPG('DB', app)
        # Create interface dictionary with all the appropriate values
        INTERFACE = {'type': 'eth', 'pod': '1', 'node': csv_node, 'module': csv_module, 'port': csv_port}
        # 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(csv_vlan, VLAN['encap_type'], csv_vlan)
        vlan_intf.attach(intf)

        # Attach the EPG to the VLAN interface
        epg.attach(vlan_intf)

        # Push it all to the APIC
        resp = session.push_to_apic(tenant.get_url(),
                                    tenant.get_json())
        print (resp)
        print ('\r')
Esempio n. 5
0
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
Esempio n. 6
0
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")
Esempio n. 7
0
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)
Esempio n. 8
0
def working_epg_with_int(opt):
	# Login to the APIC
	URL = "https://x.x.x.x"
	#URL = raw_input('APIC Address: ')
	LOGIN = raw_input('Username: '******'Password: '******'%% Could not login to APIC')

	# Define static vlaues for VLAN encapsulation 
	VLAN = {'name': '',
        	'encap_type': 'vlan'}

	# Define Tenant, AppProfile, and EPG 
	tenant = ACI.Tenant('Corporate')

	with open('VLAN-Trunk-to-ESX.csv') as csvfile:
		reader = csv.DictReader(csvfile)
		for row in reader:
			# print all values as for loop works through CSV file
			print(20 * "=")
			print('Server: ' + str(row['Hostname']))
			print('Port: ' + str(row['Node']) + '/' + str(row['Module']) + '/' + str(row['Port']))
			print('')
			print('APP: ' + str(row['App']))
			print('EPG: ' + str(row['EPG']))
			print('VLAN: ' + str(row['VLAN']))
			print('\r')
			csv_vlan = row['VLAN']
			csv_node = row['Node']
			csv_module = row['Module']
			csv_port = row['Port']

			csv_app = row['App']
			csv_epg = row['EPG']
			app = ACI.AppProfile(csv_app, tenant)
			epg = ACI.EPG(csv_epg, app)

			INTERFACE = {'type': 'eth', 'pod': '1', 'node': csv_node, 'module': csv_module, 'port': csv_port}

			# 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'], csv_vlan, "regular")
			vlan_intf.attach(intf)

			domain = ACI.EPGDomain.get_by_name(session, 'Servers')
#			print(domain.name)
			epg.add_infradomain(domain)

			# Attach/Detach the EPG to the VLAN interface
			if opt == 1:
				print('Attaching the EPG from the Interface.')
				epg.attach(vlan_intf)
				# Push it all to the APIC
				print(tenant.get_json())
				resp = session.push_to_apic(tenant.get_url(),tenant.get_json())
				print resp
				print '\r'
				if not resp.ok:
					print('%% Error: Could not push configuration to APIC')
			elif opt == 2:
				print('Detaching the EPG from the Interface.')
				epg.detach(vlan_intf)
				# Push it all to the APIC
				print(tenant.get_json())
				resp = session.push_to_apic(tenant.get_url(),tenant.get_json())
				print resp
				print '\r'
				if not resp.ok:
					print('%% Error: Could not push configuration to APIC')
			elif opt == 3:
				print('Attach dry run.')
				epg.attach(vlan_intf)
				print(tenant.get_json())
			elif opt == 4:
				print('Detach dry run.')
				epg.detach(vlan_intf)
				print(tenant.get_json())