apic dc api deep dive
TRANSCRIPT
APIC DC API Deep Dive
DevNet-10031029
Paul Lesiak Solutions Architect
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Agenda
bull Introduction
ndash ACI and APIC DC
ndash Programmatic Interfaces
ndash APISDK Features and Functionality
bull Getting Started
bull Best Practices
bull Applicability
bull Conclusion
3
Introduction
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Introduction
bull Goal for this session
ndash Introduce attendees to Cisco ACI and APIC DC
ndash Educate about the programmatic interfaces available
ndash Give steps to get started with developing for APIC
ndash Provide best practices for working with the API and SDK
bull Out of scope for this session
ndash Comprehensive course on ACI
ndash Teach Python programming
5
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Leveraging Programmability
bull Speed
bull Efficiency Cost
bull Quality
bull Automate common tasks
bull Troubleshooting tasks
bull Deployment workflows
bull Partners
bull Customers
bull Integrators
bull Cisco
bull Everyone
6
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Physical
Virtualization
Network
APP DBPOLICY WEB
HYPERVISORHYPERVISOR HYPERVISOR
APICApplication
External Network POLICY POLICY
ACI Solution Overview
7
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
ACI and APIC DC
bull Application Centric Infrastructure (ACI) represents network configuration with application based semantics
bull Fabric functions as single switch Scale Mobility Telemetry Automation
bull Cisco APIC is a centralized point of management for physical virtual and cloud infrastructure
bull Robust implementation designed around open standards and open APIs
8
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
A word on the Object Model
bull A modeled representation of everything APIC knows
ndash Network Compute Application etc
bull Management Information Tree (MIT) Tree based structure
bull MIT has distinct branches for different functional areas
bull Every node is a managed object
ndash has a class amp distinguished name
bull Critical component to working with APIC beyond programmatic interaction
9
topRoot
polUni compUni
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Programmatic Interfaces
bull Northbound API accepts configuration and provides access to management functions for controller
bull Northbound API
ndash Native REST API
ndash Python SDK (ldquoCobrardquo)
bull Southbound APIs extend declarative intent from fabric to subordinate devices
bull Southbound API
ndash L4-7 Device Packages
ndash OpFlex
bull Not in scope for this session
10
Automation
Tools
Provisioning
Scripts
APICREST
Firewall Switch
OpFlex
APIC
Dev Pkg
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST Interface
GUI
CLI
Web Browser
API Tools
ObjectBrowser(visore)
APIC Cluster +
Leaves amp Spines
REST
PythonSDK
11
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Features and Functionality
bull Native REST interface
ndash GUI can be used as reference how to get things done guide
bull Robust querying and filtering interface
bull Configured and operational state provided through same interface
bull Object model supports parameters useful for overloading application state
bull Event driven notification via websockets
12
Getting Started
13
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Agenda
bull Introduction
ndash ACI and APIC DC
ndash Programmatic Interfaces
ndash APISDK Features and Functionality
bull Getting Started
bull Best Practices
bull Applicability
bull Conclusion
3
Introduction
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Introduction
bull Goal for this session
ndash Introduce attendees to Cisco ACI and APIC DC
ndash Educate about the programmatic interfaces available
ndash Give steps to get started with developing for APIC
ndash Provide best practices for working with the API and SDK
bull Out of scope for this session
ndash Comprehensive course on ACI
ndash Teach Python programming
5
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Leveraging Programmability
bull Speed
bull Efficiency Cost
bull Quality
bull Automate common tasks
bull Troubleshooting tasks
bull Deployment workflows
bull Partners
bull Customers
bull Integrators
bull Cisco
bull Everyone
6
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Physical
Virtualization
Network
APP DBPOLICY WEB
HYPERVISORHYPERVISOR HYPERVISOR
APICApplication
External Network POLICY POLICY
ACI Solution Overview
7
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
ACI and APIC DC
bull Application Centric Infrastructure (ACI) represents network configuration with application based semantics
bull Fabric functions as single switch Scale Mobility Telemetry Automation
bull Cisco APIC is a centralized point of management for physical virtual and cloud infrastructure
bull Robust implementation designed around open standards and open APIs
8
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
A word on the Object Model
bull A modeled representation of everything APIC knows
ndash Network Compute Application etc
bull Management Information Tree (MIT) Tree based structure
bull MIT has distinct branches for different functional areas
bull Every node is a managed object
ndash has a class amp distinguished name
bull Critical component to working with APIC beyond programmatic interaction
9
topRoot
polUni compUni
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Programmatic Interfaces
bull Northbound API accepts configuration and provides access to management functions for controller
bull Northbound API
ndash Native REST API
ndash Python SDK (ldquoCobrardquo)
bull Southbound APIs extend declarative intent from fabric to subordinate devices
bull Southbound API
ndash L4-7 Device Packages
ndash OpFlex
bull Not in scope for this session
10
Automation
Tools
Provisioning
Scripts
APICREST
Firewall Switch
OpFlex
APIC
Dev Pkg
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST Interface
GUI
CLI
Web Browser
API Tools
ObjectBrowser(visore)
APIC Cluster +
Leaves amp Spines
REST
PythonSDK
11
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Features and Functionality
bull Native REST interface
ndash GUI can be used as reference how to get things done guide
bull Robust querying and filtering interface
bull Configured and operational state provided through same interface
bull Object model supports parameters useful for overloading application state
bull Event driven notification via websockets
12
Getting Started
13
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
Introduction
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Introduction
bull Goal for this session
ndash Introduce attendees to Cisco ACI and APIC DC
ndash Educate about the programmatic interfaces available
ndash Give steps to get started with developing for APIC
ndash Provide best practices for working with the API and SDK
bull Out of scope for this session
ndash Comprehensive course on ACI
ndash Teach Python programming
5
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Leveraging Programmability
bull Speed
bull Efficiency Cost
bull Quality
bull Automate common tasks
bull Troubleshooting tasks
bull Deployment workflows
bull Partners
bull Customers
bull Integrators
bull Cisco
bull Everyone
6
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Physical
Virtualization
Network
APP DBPOLICY WEB
HYPERVISORHYPERVISOR HYPERVISOR
APICApplication
External Network POLICY POLICY
ACI Solution Overview
7
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
ACI and APIC DC
bull Application Centric Infrastructure (ACI) represents network configuration with application based semantics
bull Fabric functions as single switch Scale Mobility Telemetry Automation
bull Cisco APIC is a centralized point of management for physical virtual and cloud infrastructure
bull Robust implementation designed around open standards and open APIs
8
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
A word on the Object Model
bull A modeled representation of everything APIC knows
ndash Network Compute Application etc
bull Management Information Tree (MIT) Tree based structure
bull MIT has distinct branches for different functional areas
bull Every node is a managed object
ndash has a class amp distinguished name
bull Critical component to working with APIC beyond programmatic interaction
9
topRoot
polUni compUni
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Programmatic Interfaces
bull Northbound API accepts configuration and provides access to management functions for controller
bull Northbound API
ndash Native REST API
ndash Python SDK (ldquoCobrardquo)
bull Southbound APIs extend declarative intent from fabric to subordinate devices
bull Southbound API
ndash L4-7 Device Packages
ndash OpFlex
bull Not in scope for this session
10
Automation
Tools
Provisioning
Scripts
APICREST
Firewall Switch
OpFlex
APIC
Dev Pkg
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST Interface
GUI
CLI
Web Browser
API Tools
ObjectBrowser(visore)
APIC Cluster +
Leaves amp Spines
REST
PythonSDK
11
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Features and Functionality
bull Native REST interface
ndash GUI can be used as reference how to get things done guide
bull Robust querying and filtering interface
bull Configured and operational state provided through same interface
bull Object model supports parameters useful for overloading application state
bull Event driven notification via websockets
12
Getting Started
13
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Introduction
bull Goal for this session
ndash Introduce attendees to Cisco ACI and APIC DC
ndash Educate about the programmatic interfaces available
ndash Give steps to get started with developing for APIC
ndash Provide best practices for working with the API and SDK
bull Out of scope for this session
ndash Comprehensive course on ACI
ndash Teach Python programming
5
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Leveraging Programmability
bull Speed
bull Efficiency Cost
bull Quality
bull Automate common tasks
bull Troubleshooting tasks
bull Deployment workflows
bull Partners
bull Customers
bull Integrators
bull Cisco
bull Everyone
6
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Physical
Virtualization
Network
APP DBPOLICY WEB
HYPERVISORHYPERVISOR HYPERVISOR
APICApplication
External Network POLICY POLICY
ACI Solution Overview
7
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
ACI and APIC DC
bull Application Centric Infrastructure (ACI) represents network configuration with application based semantics
bull Fabric functions as single switch Scale Mobility Telemetry Automation
bull Cisco APIC is a centralized point of management for physical virtual and cloud infrastructure
bull Robust implementation designed around open standards and open APIs
8
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
A word on the Object Model
bull A modeled representation of everything APIC knows
ndash Network Compute Application etc
bull Management Information Tree (MIT) Tree based structure
bull MIT has distinct branches for different functional areas
bull Every node is a managed object
ndash has a class amp distinguished name
bull Critical component to working with APIC beyond programmatic interaction
9
topRoot
polUni compUni
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Programmatic Interfaces
bull Northbound API accepts configuration and provides access to management functions for controller
bull Northbound API
ndash Native REST API
ndash Python SDK (ldquoCobrardquo)
bull Southbound APIs extend declarative intent from fabric to subordinate devices
bull Southbound API
ndash L4-7 Device Packages
ndash OpFlex
bull Not in scope for this session
10
Automation
Tools
Provisioning
Scripts
APICREST
Firewall Switch
OpFlex
APIC
Dev Pkg
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST Interface
GUI
CLI
Web Browser
API Tools
ObjectBrowser(visore)
APIC Cluster +
Leaves amp Spines
REST
PythonSDK
11
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Features and Functionality
bull Native REST interface
ndash GUI can be used as reference how to get things done guide
bull Robust querying and filtering interface
bull Configured and operational state provided through same interface
bull Object model supports parameters useful for overloading application state
bull Event driven notification via websockets
12
Getting Started
13
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Leveraging Programmability
bull Speed
bull Efficiency Cost
bull Quality
bull Automate common tasks
bull Troubleshooting tasks
bull Deployment workflows
bull Partners
bull Customers
bull Integrators
bull Cisco
bull Everyone
6
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Physical
Virtualization
Network
APP DBPOLICY WEB
HYPERVISORHYPERVISOR HYPERVISOR
APICApplication
External Network POLICY POLICY
ACI Solution Overview
7
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
ACI and APIC DC
bull Application Centric Infrastructure (ACI) represents network configuration with application based semantics
bull Fabric functions as single switch Scale Mobility Telemetry Automation
bull Cisco APIC is a centralized point of management for physical virtual and cloud infrastructure
bull Robust implementation designed around open standards and open APIs
8
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
A word on the Object Model
bull A modeled representation of everything APIC knows
ndash Network Compute Application etc
bull Management Information Tree (MIT) Tree based structure
bull MIT has distinct branches for different functional areas
bull Every node is a managed object
ndash has a class amp distinguished name
bull Critical component to working with APIC beyond programmatic interaction
9
topRoot
polUni compUni
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Programmatic Interfaces
bull Northbound API accepts configuration and provides access to management functions for controller
bull Northbound API
ndash Native REST API
ndash Python SDK (ldquoCobrardquo)
bull Southbound APIs extend declarative intent from fabric to subordinate devices
bull Southbound API
ndash L4-7 Device Packages
ndash OpFlex
bull Not in scope for this session
10
Automation
Tools
Provisioning
Scripts
APICREST
Firewall Switch
OpFlex
APIC
Dev Pkg
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST Interface
GUI
CLI
Web Browser
API Tools
ObjectBrowser(visore)
APIC Cluster +
Leaves amp Spines
REST
PythonSDK
11
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Features and Functionality
bull Native REST interface
ndash GUI can be used as reference how to get things done guide
bull Robust querying and filtering interface
bull Configured and operational state provided through same interface
bull Object model supports parameters useful for overloading application state
bull Event driven notification via websockets
12
Getting Started
13
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Physical
Virtualization
Network
APP DBPOLICY WEB
HYPERVISORHYPERVISOR HYPERVISOR
APICApplication
External Network POLICY POLICY
ACI Solution Overview
7
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
ACI and APIC DC
bull Application Centric Infrastructure (ACI) represents network configuration with application based semantics
bull Fabric functions as single switch Scale Mobility Telemetry Automation
bull Cisco APIC is a centralized point of management for physical virtual and cloud infrastructure
bull Robust implementation designed around open standards and open APIs
8
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
A word on the Object Model
bull A modeled representation of everything APIC knows
ndash Network Compute Application etc
bull Management Information Tree (MIT) Tree based structure
bull MIT has distinct branches for different functional areas
bull Every node is a managed object
ndash has a class amp distinguished name
bull Critical component to working with APIC beyond programmatic interaction
9
topRoot
polUni compUni
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Programmatic Interfaces
bull Northbound API accepts configuration and provides access to management functions for controller
bull Northbound API
ndash Native REST API
ndash Python SDK (ldquoCobrardquo)
bull Southbound APIs extend declarative intent from fabric to subordinate devices
bull Southbound API
ndash L4-7 Device Packages
ndash OpFlex
bull Not in scope for this session
10
Automation
Tools
Provisioning
Scripts
APICREST
Firewall Switch
OpFlex
APIC
Dev Pkg
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST Interface
GUI
CLI
Web Browser
API Tools
ObjectBrowser(visore)
APIC Cluster +
Leaves amp Spines
REST
PythonSDK
11
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Features and Functionality
bull Native REST interface
ndash GUI can be used as reference how to get things done guide
bull Robust querying and filtering interface
bull Configured and operational state provided through same interface
bull Object model supports parameters useful for overloading application state
bull Event driven notification via websockets
12
Getting Started
13
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
ACI and APIC DC
bull Application Centric Infrastructure (ACI) represents network configuration with application based semantics
bull Fabric functions as single switch Scale Mobility Telemetry Automation
bull Cisco APIC is a centralized point of management for physical virtual and cloud infrastructure
bull Robust implementation designed around open standards and open APIs
8
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
A word on the Object Model
bull A modeled representation of everything APIC knows
ndash Network Compute Application etc
bull Management Information Tree (MIT) Tree based structure
bull MIT has distinct branches for different functional areas
bull Every node is a managed object
ndash has a class amp distinguished name
bull Critical component to working with APIC beyond programmatic interaction
9
topRoot
polUni compUni
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Programmatic Interfaces
bull Northbound API accepts configuration and provides access to management functions for controller
bull Northbound API
ndash Native REST API
ndash Python SDK (ldquoCobrardquo)
bull Southbound APIs extend declarative intent from fabric to subordinate devices
bull Southbound API
ndash L4-7 Device Packages
ndash OpFlex
bull Not in scope for this session
10
Automation
Tools
Provisioning
Scripts
APICREST
Firewall Switch
OpFlex
APIC
Dev Pkg
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST Interface
GUI
CLI
Web Browser
API Tools
ObjectBrowser(visore)
APIC Cluster +
Leaves amp Spines
REST
PythonSDK
11
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Features and Functionality
bull Native REST interface
ndash GUI can be used as reference how to get things done guide
bull Robust querying and filtering interface
bull Configured and operational state provided through same interface
bull Object model supports parameters useful for overloading application state
bull Event driven notification via websockets
12
Getting Started
13
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
A word on the Object Model
bull A modeled representation of everything APIC knows
ndash Network Compute Application etc
bull Management Information Tree (MIT) Tree based structure
bull MIT has distinct branches for different functional areas
bull Every node is a managed object
ndash has a class amp distinguished name
bull Critical component to working with APIC beyond programmatic interaction
9
topRoot
polUni compUni
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Programmatic Interfaces
bull Northbound API accepts configuration and provides access to management functions for controller
bull Northbound API
ndash Native REST API
ndash Python SDK (ldquoCobrardquo)
bull Southbound APIs extend declarative intent from fabric to subordinate devices
bull Southbound API
ndash L4-7 Device Packages
ndash OpFlex
bull Not in scope for this session
10
Automation
Tools
Provisioning
Scripts
APICREST
Firewall Switch
OpFlex
APIC
Dev Pkg
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST Interface
GUI
CLI
Web Browser
API Tools
ObjectBrowser(visore)
APIC Cluster +
Leaves amp Spines
REST
PythonSDK
11
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Features and Functionality
bull Native REST interface
ndash GUI can be used as reference how to get things done guide
bull Robust querying and filtering interface
bull Configured and operational state provided through same interface
bull Object model supports parameters useful for overloading application state
bull Event driven notification via websockets
12
Getting Started
13
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Programmatic Interfaces
bull Northbound API accepts configuration and provides access to management functions for controller
bull Northbound API
ndash Native REST API
ndash Python SDK (ldquoCobrardquo)
bull Southbound APIs extend declarative intent from fabric to subordinate devices
bull Southbound API
ndash L4-7 Device Packages
ndash OpFlex
bull Not in scope for this session
10
Automation
Tools
Provisioning
Scripts
APICREST
Firewall Switch
OpFlex
APIC
Dev Pkg
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST Interface
GUI
CLI
Web Browser
API Tools
ObjectBrowser(visore)
APIC Cluster +
Leaves amp Spines
REST
PythonSDK
11
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Features and Functionality
bull Native REST interface
ndash GUI can be used as reference how to get things done guide
bull Robust querying and filtering interface
bull Configured and operational state provided through same interface
bull Object model supports parameters useful for overloading application state
bull Event driven notification via websockets
12
Getting Started
13
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST Interface
GUI
CLI
Web Browser
API Tools
ObjectBrowser(visore)
APIC Cluster +
Leaves amp Spines
REST
PythonSDK
11
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Features and Functionality
bull Native REST interface
ndash GUI can be used as reference how to get things done guide
bull Robust querying and filtering interface
bull Configured and operational state provided through same interface
bull Object model supports parameters useful for overloading application state
bull Event driven notification via websockets
12
Getting Started
13
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Features and Functionality
bull Native REST interface
ndash GUI can be used as reference how to get things done guide
bull Robust querying and filtering interface
bull Configured and operational state provided through same interface
bull Object model supports parameters useful for overloading application state
bull Event driven notification via websockets
12
Getting Started
13
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
Getting Started
13
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Basics
bull Standard REST methods supported bull Stateless
ndash No state for requests or sessions
bull HTTP11 HTTPS (default)
bull Handled by any APIC in cluster
bull Access to switches via APIC
bull Create read update amp delete Managed Objects
Method Action Behavior
GET Read Nullipotent
POST Create
Update
Idempotent
DELETE Delete Idempotent
bull Payloads can be either XML or JSON
ndash Specified by the file extension in URI
ndash Content-Type and Accept header is ignored
14
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API Read Operations
api
API
Operator
mo|class
Specify
Managed
Object or Class
Operator
dn|classname
Distinguished
name or Object
Class
xml|json
Encoding for
response
[options]
Specify filters
selectors or
modifiers to query
joined using
ampersand (amp)
hostport
APIC host
and port
http(s)
http or
https
protocol
httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml
Read properties for an EPG by Distinguished Name
httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)
Find all 10G ports on Fabric
15
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
REST API CreateUpdate Operations
api mo dn xml|json [options]hostporthttp(s)
ltfvTenant name=NewTenantgt
ltfvAp name=NewApplicationgt
ltfvAEPg name=WebTiergt
ltfvRsPathAtt encap=vlan-1 mode=regular
tDn=topologypod-1paths-17pathep-[eth11]gt
ltfvAEPggt
ltfvApgt
ltfvTenantgt
Payload is XMLJSON representation of API Command Body
16
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Object Browser Visore
bull APIC has built in object browser to navigate the object tree and inspect the state of objects
bull Point the web browser to Visore httpltapicgtvisorehtml
bull Search for a particular object or dn (fvTenant topSystem topologypod-1node-101)
17
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sniffer API Inspector
bull API calls made by GUI are captured
ndash GET POST
bull Navigating through panes fetches data with GET requests
bull Submitting configuration changes uses POST requests
18
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Capturing API Calls
19
POST
url http172233215apinodemounitn-Ciscojson
fvTenant
attributes
name Cisco
status created
children []
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Getting Started
1 Get the Cobra SDK
2 Get the documentation
3 Establish authenticated session
4 Simple queries
5 Inserting data into object store
20
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
SDK and Documentation
bull Available on DevNetndash httpsdeveloperciscocomsiteapic-dcndash Downloads -gt Python Egg Files
bull Can be downloaded from APIC atndash httpsltapicgtcobrandash Remember to rename the eggrsquos before
installing
bull You will need to reference the Management Information Model Bookmark it
ndash httpsdeveloperciscocommediamim-ref or httpsltapicgtdochtml
bull Python SDK docs (and install directions)
ndash httpsdeveloperciscocomsiteapic-dcdocumentspythonapi or
ndash httpsltapicgtcobra
bull APIC REST API User Guide
ndash httpwwwciscocomcenustddocsswitchesdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml
21
httpcsco9006xDw6 Python SDK docs and eggs are included on the APIC in 10(2) code but theres a catch
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Establish authenticated session
REST
bull Login with username and password in payload
POST apimoaaaLoginxml
ltaaaUser name=admin pwd=insiemegt
bull Response headers include Cookie ldquoAPIC-cookierdquo
ndash Store this and use it for future requests
Cobra
import cobramitaccess
import cobramitsession
ls = cobramitsessionLoginSession(
httpsapic admin insieme)
md = cobramitaccessMoDirectory(ls)
mdlogin()
bull md now contains an authenticated APIC session
bull
22
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Simple Queries
REST
bull Query for all client endpoint objects
GET apiclassfvCEpxml
ltxmlgtltimdatagtltfvCEp dn=unitn-
Ciscoap-Blogepg-MySQLcep-
00505682D2FE encap=vlan-501
id=0 ip=0000 lcC=vmm
lcOwn=local mac=00505682D2FE
mcastAddr=not-applicable
name=00505682D2FErdquo
uid=0gtltimdatagt
bull Parse XML results and process as needed
Cobra
bull Use the ldquolookupByClassrdquo method to find all endpoints (fvCEp)
endpoints = mdlookupByClass(fvCEp)
print([str(epdn) for ep in endpoints])
[unitn-Ciscoap-Blogepg-MySQLcep-
00505682D2FE unitn-Ciscoap-
Blogepg-MySQLcep-00505682C3D0]
23
Tip To inspect http requests use debuglevel on httplib
import httplib
httplibHTTPConnectiondebuglevel =
1
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters in Cobra
bull Built in helpers lookupByClass and lookupByDn use query under the covers
bull For advanced queries you can use query directly
bull In this example we recursively print a full subtree for all endpoints
24
def printtree(mos indent=0)
for mo in mos
print indent str(mometaclassName)
printtree(mochildren indent=indent+2)
cq = cobramitaccessClassQuery(fvCEp)
cqsubtree = full
endpoints = mdquery(cq)
printtree(endpoints)
gtgtgt printtree(endpoints)
cobramodelfvCEp
cobramodelfvRsNic
cobramodelfvRsVm
cobramodelfvRsCEpToPathEp
cobramodelfvRsHyper
cobramodelfvReportingNode
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Query Filters
bull Usually more efficient as less number of MOs need to be serialized and returned
bull Filter the response returned using the supplied condition(s)
ndash Syntax httpURIcondition[ampcondition[amp]]
bull Returns only the MOs that satisfies the condition(s)
Filter type Syntax Cobra Query Property Description
query-target self | children | subtree AbstractQueryqueryTarget Define the scope of query
target-subtree-class ltclass namegt AbstractQueryclassFilter Respond only elements including specified class
query-target-filter ltfilter expressionsgt AbstractQuerypropFilter Respond only elements matching conditions
rsp-subtree no | children | full AbstractQuerysubtree specifies child object level included in the response
rsp-subtree-class ltclass namegt AbstractQuerysubtreeClassFilter Respond only specified classes
rsp-subtree-filter ltfilter expressionsgt AbstractQuerysubtreePropFilter (gt102m) Respond only classes matching conditions
rsp-subtree-include faults | health stats hellip AbstractQuerysubtreeInclude Request additional objects
order-by ltclassnamepropertygt| asc | desc NotImplemented Sort the response based on the property values
25
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Committing Configuration Changes
REST
bull Create a new tenant belonging to policy universe
POST apimounixml
ltfvTenant name=Ciscogt
Cobra
bull Build your objects and commit them
26
Tip To get the configured XML body for the object youve createdmodified add the rsp-include query parameter
POST apimounixmlrsp-subtree=modified
topMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo name=Cisco)
c = cobramitrequestConfigRequest()
caddMo(fvTenant)
mdcommit(c)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
APIC REST to Python Adapter aryapy
bull GUI creates REST
bull API Inspector shows REST
bull aryapy creates code from REST
bull Auto-generate code to automate tasks without heavy lifting
bull Available at
httpgithubcomdatacenterACI
XMLJSON
aryapy
Python code
fvTenantattributesdnunitn-
CisconameCiscorntn-
Ciscostatuscreatedchildren[fvBDattribut
esdnunitn-CiscoBD-
CiscoBdmac0022BDF819FFnameCiscoBdrn
BD-
CiscoBdstatuscreatedchildren[fvRsCtxatt
ributestnFvCtxNameCiscoNetworkstatuscreated
modifiedchildren[]fvSubnetattributesdn
unitn-CiscoBD-CiscoBdsubnet-
[100018]ip100018rnsubnet-
[100018]statuscreatedchildren[]]fv
Ctxattributesdnunitn-Ciscoctx-
CiscoNetworknameCiscoNetworkrnctx-
CiscoNetworkstatuscreatedchildren[]]
fvTenant = cobramodelfvTenant(topMo name=Cisco)
fvCtx = cobramodelfvCtx(fvTenant name=CiscoNetwork)
fvBD = cobramodelfvBD(fvTenant
mac=0022BDF819FF name=CiscoBd)
fvRsCtx = cobramodelfvRsCtx(fvBD
tnFvCtxName=fvCtxname)
fvSubnet = cobramodelfvSubnet(fvBD ip=100018)
27
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Sample Get fabric OSPF neighbors
bull Typical operations task is to check neighbors
bull Want to have the same look and feel
bull Take advantage of single fabric API to get details from entire fabric
bull Solution Query fabric for all OSPF neighbors and output status in IOSNX-OS fashion
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Code
29
def showOspf(md)
cq = cobramitrequestClassQuery(ospfAdjEp)
cqsubtreeInclude = faults
return mdquery(cq)
neis = showOspf(md)
fields = [(Neighbor ID id) (Pri prio) (State
operSt) (Address peerIp) (Node dn)]
for field in fields
print ltwidthformat(field[0] width=len(field[0]))
for ne in neis
for f in fields
print ltwidthformat(getattr(ne f[1]) width=len(f[0]))
for fault in nechildren
print Fault Present faultdescr
Fetch Neighbors
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Get fabric OSPF neighbors Results
bull Proper IOSNX-OS style results with fault detailsNeighbor ID Pri State Address Node
2221 1 exstart 1111 topologypod-1node-103
Fault Present OSPF adjacency is not full current state Exstart
2226 1 full 1116 topologypod-1node-103
2223 1 exstart 1115 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Exstart
2226 1 initializing 1116 topologypod-1node-102
Fault Present OSPF adjacency is not full current state Initializing
30
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
Best Practices
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Best Practices
1 Utilize built in naming and Dn methods
2 Be granularspecific with your commits and queries
3 Avoid hard coding Dnrsquos that contain naming properties
4 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving
5 Build sparse trees and leverage default values
6 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions
7 Use REST API filtering to reduce result set
32
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
1 Built in naming and Dn methods
bull When making references between Managed Objects do not manually build Dn strings
bull Instead lookup the object and use the dn property
33
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
encap=vlan-2 tDn=topologypod-
1paths-101pathep-[eth11])
fvRsPathAtt =
cobramodelfvRsPathAtt(fvAEPg
tDn=interfacedn)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
2 Commit and Query Granularity
bull The API uses a directory based architecture
ndash Closer to your target means less time and more accurate queries
bull Following this practice also helps avoid context root issues
ndash APIC stores data in distributed data stores
ndash If you go up too high no single APIC can own the data
34
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
21 Commit and Query Granularity
35
bull Want to add a new end point group
Do thiscaddMo(fvAEPg)
Dont do thistopMo = cobramodelpolUni()
fvTenant = cobramodelfvTenant(topMo
name=Cisco)
fvAp = cobramodelfvAp(fvTenant NewApp)
fvAEPg = cobramodelfvAEPg(fvAp NewEpg)
c = cobramitrequestConfigRequest()
caddMo(topMo)
mdcommit(c)
Tip This technique will not work if the parent Mo does not exist
Eg if the Tenant and App Profile do not exist you cannot add an EPG
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
3 Avoid hard coded Distinguished Names
bull Naming might change in an environment
bull Avoid re-writing code and bugs
ndash by doing lookups when applicable
ndash Referencing classes instead of instances
bull Note Most important classes have static Dns so you can use the static definition method shown here
36
Dont do thistopDn = cobramitnamingDnfromString(uniinfra)
lacpLagPol = cobramodellacpLagPol(topDn
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
Do thistopMo = cobramodelpolUni()
infraMo = cobramodelinfraInfra(topMo )
lacpLagPol = cobramodellacpLagPol(infraMo
name=active ctrl=graceful-convsusp-
individualfast-sel-hot-stdby mode=active)
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
4 Avoid lookups when you can
bull Issuing a remote query will always be slower than defining locally
bull As shown in the last example you can build static Mos for many context roots
bull Avoid two REST queries by building your object locally
37
Dont do thistopMo = mdlookupByClass(polUni)
Do thistopMo = cobramodelpolUni()
lookupByClass and lookupByDn both call query() and incur a lookup penalty
Built in local memory and available for immediate usage
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
5 Build sparse trees and use defaults
bull The REST API is smart and populates defaults as needed
bull Many values read back from the APIC are configuration defaults (eg monitoring policies)
bull Passing all these defaults will add bloat to your code and slow down API calls
38
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
6 Dont import and avoid from in imports
bull Basic Python practice
bull Name space collisions are annoying
bull The Object Model contains ~5k objects there are object name collisions
bull Avoid them by using namespaces
bull Or use from hellip import hellip as hellip
39
Dont do thisfrom cobramodelactrl import Inst
from cobramodelaction import Inst
a = Inst() We clobbered actrlInst
Do thisimport cobramodelactrl
import cobramodelaction
a = cobramodelactrlInst()
Or this
from cobramodelactrl import Inst as
ActrlInst
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
7 Server side filtering
bull Its possible to perform multiple lookups process results and repeat for complex searches
bull The powerful filtering on the REST API allows concise queries
40
Get Mo for interface eth11 on node 101cq = cobramitrequestClassQuery(fabricPathEpCont)
cqpropFilter = eq(fabricPathEpContnodeId 101)
cqsubtree = children
cqsubtreeClassFilter = fabricPathEp
interface = [i for i in mdquery(cq)[0]children if iname == eth11][0]
print interfacedn
topologypod-1paths-101pathep-[eth11]
Tip Cobra gt102m supports subtreePropFilterattribute allowing this loop to be avoided
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
Applicability
41
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
How others are using these
bull Partners with application and business modeling
ndash Direct translation of business rules to application policy
bull Customers with large repeated deployments
ndash Repeated EPG-as-VLAN build outs
ndash Template based definitions for new tenant onboarding
bull Within Cisco
ndash Fully automated QA solution test process
ndash Advanced Services rapid testbed deployment
ndash Cisco IT heavily leveraging APIC automation
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
Conclusion
43
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping
copy 2015 Cisco andor its affiliates All rights reservedPresentation_ID Cisco Public
Conclusion
bull APIC APIs are being used today
bull Cisco APIC provides open API for complete platform access
bull Powerful data manipulation and processing
bull True object oriented interface
bull Rapid development and prototyping