introduction to aci - amazon web services session will offer an introduction to application centric...

60

Upload: vuongdiep

Post on 31-Mar-2018

231 views

Category:

Documents


0 download

TRANSCRIPT

Introduction to ACI Programming and APIs

Paul Lesiak Solutions Architect

BRKDEV-2971

This session will offer an introduction to Application Centric Infrastructure It will present the basic constructs of ACI policy including application profiles endpoint groups and tenants It will also discuss the programmatic APIs including Python and REST available to create and manage ACI policy and best practices for programmatic interaction with ACI

AbstractIntroduction to ACI Programming and APIs

bull Introduction

bull Overview of ACI

bull ACI Object Constructs

bull Programmatic Interfaces

bull Use Cases

bull Best Practices

bull Conclusion

Agenda

Introduction

Introduction

bull Goal for this session

bull Introduce attendees to Cisco ACI and APIC DC

bull Educate about the programmatic interfaces available

bull Give steps to get started with developing for APIC

bull Provide best practices for working with the API and SDK

bull Out of scope for this session

bull Comprehensive course on ACI

bull Teach Python programming

Business Value Stack

$$$

Knowledge

Business

Applications

Infrastructure

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

Physical

Virtualization

Network

APP DBPOLICY WEB

HYPERVISORHYPERVISOR HYPERVISOR

APICApplication

External Network POLICY POLICY

ACI Solution Overview

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

Unflattening network configuration

bull Network configuration today is based around flat configurations

bull This does not represent the richness of applications and business

bull We need representation as something more flexible

ACI Object Model

bull A modeled representation of everything APIC knows

bull 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

bull has a class amp distinguished name

bull Critical component to working with APIC beyond programmatic interaction

topRoot

polUni compUni

Network Config as Object Model

bull Network configuration is represented as tiered objects

bull hellip And everything else

Root

Policy Universe

Tenants

Applications

Infra

VLANs

Fabric

Nodes

Virtual Network

Hypervisors

Tenant

VRF VRF

Bridge

Domain 11010124

Bridge

Domain 21020124

Bridge

Domain 1

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

This session will offer an introduction to Application Centric Infrastructure It will present the basic constructs of ACI policy including application profiles endpoint groups and tenants It will also discuss the programmatic APIs including Python and REST available to create and manage ACI policy and best practices for programmatic interaction with ACI

AbstractIntroduction to ACI Programming and APIs

bull Introduction

bull Overview of ACI

bull ACI Object Constructs

bull Programmatic Interfaces

bull Use Cases

bull Best Practices

bull Conclusion

Agenda

Introduction

Introduction

bull Goal for this session

bull Introduce attendees to Cisco ACI and APIC DC

bull Educate about the programmatic interfaces available

bull Give steps to get started with developing for APIC

bull Provide best practices for working with the API and SDK

bull Out of scope for this session

bull Comprehensive course on ACI

bull Teach Python programming

Business Value Stack

$$$

Knowledge

Business

Applications

Infrastructure

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

Physical

Virtualization

Network

APP DBPOLICY WEB

HYPERVISORHYPERVISOR HYPERVISOR

APICApplication

External Network POLICY POLICY

ACI Solution Overview

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

Unflattening network configuration

bull Network configuration today is based around flat configurations

bull This does not represent the richness of applications and business

bull We need representation as something more flexible

ACI Object Model

bull A modeled representation of everything APIC knows

bull 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

bull has a class amp distinguished name

bull Critical component to working with APIC beyond programmatic interaction

topRoot

polUni compUni

Network Config as Object Model

bull Network configuration is represented as tiered objects

bull hellip And everything else

Root

Policy Universe

Tenants

Applications

Infra

VLANs

Fabric

Nodes

Virtual Network

Hypervisors

Tenant

VRF VRF

Bridge

Domain 11010124

Bridge

Domain 21020124

Bridge

Domain 1

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

bull Introduction

bull Overview of ACI

bull ACI Object Constructs

bull Programmatic Interfaces

bull Use Cases

bull Best Practices

bull Conclusion

Agenda

Introduction

Introduction

bull Goal for this session

bull Introduce attendees to Cisco ACI and APIC DC

bull Educate about the programmatic interfaces available

bull Give steps to get started with developing for APIC

bull Provide best practices for working with the API and SDK

bull Out of scope for this session

bull Comprehensive course on ACI

bull Teach Python programming

Business Value Stack

$$$

Knowledge

Business

Applications

Infrastructure

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

Physical

Virtualization

Network

APP DBPOLICY WEB

HYPERVISORHYPERVISOR HYPERVISOR

APICApplication

External Network POLICY POLICY

ACI Solution Overview

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

Unflattening network configuration

bull Network configuration today is based around flat configurations

bull This does not represent the richness of applications and business

bull We need representation as something more flexible

ACI Object Model

bull A modeled representation of everything APIC knows

bull 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

bull has a class amp distinguished name

bull Critical component to working with APIC beyond programmatic interaction

topRoot

polUni compUni

Network Config as Object Model

bull Network configuration is represented as tiered objects

bull hellip And everything else

Root

Policy Universe

Tenants

Applications

Infra

VLANs

Fabric

Nodes

Virtual Network

Hypervisors

Tenant

VRF VRF

Bridge

Domain 11010124

Bridge

Domain 21020124

Bridge

Domain 1

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Introduction

Introduction

bull Goal for this session

bull Introduce attendees to Cisco ACI and APIC DC

bull Educate about the programmatic interfaces available

bull Give steps to get started with developing for APIC

bull Provide best practices for working with the API and SDK

bull Out of scope for this session

bull Comprehensive course on ACI

bull Teach Python programming

Business Value Stack

$$$

Knowledge

Business

Applications

Infrastructure

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

Physical

Virtualization

Network

APP DBPOLICY WEB

HYPERVISORHYPERVISOR HYPERVISOR

APICApplication

External Network POLICY POLICY

ACI Solution Overview

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

Unflattening network configuration

bull Network configuration today is based around flat configurations

bull This does not represent the richness of applications and business

bull We need representation as something more flexible

ACI Object Model

bull A modeled representation of everything APIC knows

bull 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

bull has a class amp distinguished name

bull Critical component to working with APIC beyond programmatic interaction

topRoot

polUni compUni

Network Config as Object Model

bull Network configuration is represented as tiered objects

bull hellip And everything else

Root

Policy Universe

Tenants

Applications

Infra

VLANs

Fabric

Nodes

Virtual Network

Hypervisors

Tenant

VRF VRF

Bridge

Domain 11010124

Bridge

Domain 21020124

Bridge

Domain 1

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Introduction

bull Goal for this session

bull Introduce attendees to Cisco ACI and APIC DC

bull Educate about the programmatic interfaces available

bull Give steps to get started with developing for APIC

bull Provide best practices for working with the API and SDK

bull Out of scope for this session

bull Comprehensive course on ACI

bull Teach Python programming

Business Value Stack

$$$

Knowledge

Business

Applications

Infrastructure

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

Physical

Virtualization

Network

APP DBPOLICY WEB

HYPERVISORHYPERVISOR HYPERVISOR

APICApplication

External Network POLICY POLICY

ACI Solution Overview

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

Unflattening network configuration

bull Network configuration today is based around flat configurations

bull This does not represent the richness of applications and business

bull We need representation as something more flexible

ACI Object Model

bull A modeled representation of everything APIC knows

bull 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

bull has a class amp distinguished name

bull Critical component to working with APIC beyond programmatic interaction

topRoot

polUni compUni

Network Config as Object Model

bull Network configuration is represented as tiered objects

bull hellip And everything else

Root

Policy Universe

Tenants

Applications

Infra

VLANs

Fabric

Nodes

Virtual Network

Hypervisors

Tenant

VRF VRF

Bridge

Domain 11010124

Bridge

Domain 21020124

Bridge

Domain 1

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Business Value Stack

$$$

Knowledge

Business

Applications

Infrastructure

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

Physical

Virtualization

Network

APP DBPOLICY WEB

HYPERVISORHYPERVISOR HYPERVISOR

APICApplication

External Network POLICY POLICY

ACI Solution Overview

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

Unflattening network configuration

bull Network configuration today is based around flat configurations

bull This does not represent the richness of applications and business

bull We need representation as something more flexible

ACI Object Model

bull A modeled representation of everything APIC knows

bull 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

bull has a class amp distinguished name

bull Critical component to working with APIC beyond programmatic interaction

topRoot

polUni compUni

Network Config as Object Model

bull Network configuration is represented as tiered objects

bull hellip And everything else

Root

Policy Universe

Tenants

Applications

Infra

VLANs

Fabric

Nodes

Virtual Network

Hypervisors

Tenant

VRF VRF

Bridge

Domain 11010124

Bridge

Domain 21020124

Bridge

Domain 1

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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

Physical

Virtualization

Network

APP DBPOLICY WEB

HYPERVISORHYPERVISOR HYPERVISOR

APICApplication

External Network POLICY POLICY

ACI Solution Overview

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

Unflattening network configuration

bull Network configuration today is based around flat configurations

bull This does not represent the richness of applications and business

bull We need representation as something more flexible

ACI Object Model

bull A modeled representation of everything APIC knows

bull 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

bull has a class amp distinguished name

bull Critical component to working with APIC beyond programmatic interaction

topRoot

polUni compUni

Network Config as Object Model

bull Network configuration is represented as tiered objects

bull hellip And everything else

Root

Policy Universe

Tenants

Applications

Infra

VLANs

Fabric

Nodes

Virtual Network

Hypervisors

Tenant

VRF VRF

Bridge

Domain 11010124

Bridge

Domain 21020124

Bridge

Domain 1

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Physical

Virtualization

Network

APP DBPOLICY WEB

HYPERVISORHYPERVISOR HYPERVISOR

APICApplication

External Network POLICY POLICY

ACI Solution Overview

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

Unflattening network configuration

bull Network configuration today is based around flat configurations

bull This does not represent the richness of applications and business

bull We need representation as something more flexible

ACI Object Model

bull A modeled representation of everything APIC knows

bull 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

bull has a class amp distinguished name

bull Critical component to working with APIC beyond programmatic interaction

topRoot

polUni compUni

Network Config as Object Model

bull Network configuration is represented as tiered objects

bull hellip And everything else

Root

Policy Universe

Tenants

Applications

Infra

VLANs

Fabric

Nodes

Virtual Network

Hypervisors

Tenant

VRF VRF

Bridge

Domain 11010124

Bridge

Domain 21020124

Bridge

Domain 1

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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

Unflattening network configuration

bull Network configuration today is based around flat configurations

bull This does not represent the richness of applications and business

bull We need representation as something more flexible

ACI Object Model

bull A modeled representation of everything APIC knows

bull 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

bull has a class amp distinguished name

bull Critical component to working with APIC beyond programmatic interaction

topRoot

polUni compUni

Network Config as Object Model

bull Network configuration is represented as tiered objects

bull hellip And everything else

Root

Policy Universe

Tenants

Applications

Infra

VLANs

Fabric

Nodes

Virtual Network

Hypervisors

Tenant

VRF VRF

Bridge

Domain 11010124

Bridge

Domain 21020124

Bridge

Domain 1

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Unflattening network configuration

bull Network configuration today is based around flat configurations

bull This does not represent the richness of applications and business

bull We need representation as something more flexible

ACI Object Model

bull A modeled representation of everything APIC knows

bull 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

bull has a class amp distinguished name

bull Critical component to working with APIC beyond programmatic interaction

topRoot

polUni compUni

Network Config as Object Model

bull Network configuration is represented as tiered objects

bull hellip And everything else

Root

Policy Universe

Tenants

Applications

Infra

VLANs

Fabric

Nodes

Virtual Network

Hypervisors

Tenant

VRF VRF

Bridge

Domain 11010124

Bridge

Domain 21020124

Bridge

Domain 1

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

ACI Object Model

bull A modeled representation of everything APIC knows

bull 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

bull has a class amp distinguished name

bull Critical component to working with APIC beyond programmatic interaction

topRoot

polUni compUni

Network Config as Object Model

bull Network configuration is represented as tiered objects

bull hellip And everything else

Root

Policy Universe

Tenants

Applications

Infra

VLANs

Fabric

Nodes

Virtual Network

Hypervisors

Tenant

VRF VRF

Bridge

Domain 11010124

Bridge

Domain 21020124

Bridge

Domain 1

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Network Config as Object Model

bull Network configuration is represented as tiered objects

bull hellip And everything else

Root

Policy Universe

Tenants

Applications

Infra

VLANs

Fabric

Nodes

Virtual Network

Hypervisors

Tenant

VRF VRF

Bridge

Domain 11010124

Bridge

Domain 21020124

Bridge

Domain 1

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Distinguished Name

bull DN is used as a globally unique identifier for an object in the MIT

bull Formed by getting relative name (RN) and appending it to parent RN until reaching topRoot

bull RN naming rule depends on object

bull Can be found in APIC model documentation

topRoot

polUni fvTenant

fvAp fvAEPg

vzFilter vzEntry

vzBrCP vzSubj

fabricTopology fabricPod

fabricPathEpCont fabricPathEp

fabricNode

vmmProvP vmmDomP vmmCtrlrP

Example

unitn-tenantap-app1epg-epg1

Example

topologypod-1paths-101pathep-[eth11]

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Programmatic Interfaces

bull Northbound API accepts configuration and provides access to management functions for controller

bull Northbound API

bull Native REST API

bull Python SDK (ldquoCobrardquo)

bull Southbound APIs extend declarative intent from fabric to subordinate devices

bull Southbound API

bull L4-7 Device Packages

bull OpFlex

bull Not in scope for this session

Automation

Tools

Provisioning

Scripts

APICREST

Firewall Switch

OpFlex

APIC

Dev Pkg

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

REST Interface

GUI

CLI

Web Browser

API Tools

ObjectBrowser(visore)

APIC Cluster +

Leaves amp Spines

REST

PythonSDK

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Features and Functionality

bull Native REST interface

bull 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

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Getting Started

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

REST API Basics

bull Standard REST methods supported bull Stateless

bull 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

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

bull Read properties for a specific EPG

ltimdata totalCount=1gt

ltfvAEPg childAction= configIssues= configSt=applied descr=dn=unitn-Ciscoap-Softwareepg-Download lcOwn=local matchT=AtleastOnemodTs=2015-05-23T221921173+0000 monPolDn=unitn-commonmonepg-defaultname=Download pcTag=49189 prio=unspecified scope=2293760 status=triggerSt=triggerable uid=0gt

ltimdatagt

Lookup by DN

httpapicapimounitn-Ciscoap-Softwareepg-Downloadxml

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

bull Read properties every L1 Physical Interface

ltimdata totalCount=1134gt

ltl1PhysIf adminSt=up autoNeg=on bw=0 childAction= delay=1 descr=dn=topologypod-1node-102sysphys-[eth132] dot1qEtherType=0x8100 ethpmCfgFailedBmp=ethpmCfgFailedTs=00000000000 ethpmCfgState=0 id=eth132 inhBw=unspecifiedlayer=Layer2 lcOwn=local linkDebounce=100 linkLog=default mdix=auto medium=broadcastmodTs=2015-06-03T220710513+0000 mode=trunk monPolDn=uniinframoninfra-defaultmtu=9000 name= portT=leaf routerMac=not-applicable snmpTrapSt=enable spanMode=not-a-span-dest speed=10G status= switchingSt=disabled trunkLog=default usage=discoverygt

hellip

ltimdatagt

Lookup by Class

httpapicapiclassl1PhysIfxmlquery-target-filter=eq(l1PhysIfspeed10G)

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

bull Read the object and complete subtree

ltimdata totalCount=1gt

ltcompVm cfgdOs=Ubuntu Linux (32-bit) childAction= descr= dn=compprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001 guid=5024a300-1fde-aa80-72d4-7c33ef63a688 id=0 lcOwn=local modTs=2015-06-05T170404471+0000 monPolDn= name=32bit_Ubuntu oid=vm-1001 os= state=poweredOn status=type=virtgt

ltcompVNic adapterType=Vmxnet3 addressType=assigned childAction= descr= guid= id=0ip=0000 lcOwn=local mac=005056A4D0D0 modTs=2015-06-05T170404471+0000 monPolDn=name=Network adapter 1 oid=4000 operSt=up rn=vnic-005056A4D0D0 status= type=virtgt

ltcompRsHv childAction= forceResolve=no lcOwn=local modTs=2015-06-04T223908435+0000rType=mo rn=rshv-[compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12] state=formed stateQual=nonestatus= tCl=compHv tDn=compprov-VMwarectrlr-[vc-1]-vCenter_1hv-host-12 tType=mogt

ltcompVmgt

ltimdatagt

Get all the properties

httpapicapimocompprov-VMwarectrlr-[vc-1]-vCenter_1vm-vm-1001xmlrsp-subtree=full

Response subtree query option is set to full to get everything under the object being queried

The target Dn references another object ndash in this case the hypervisor so you can get more information by querying this Dn

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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)

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Sniffer API Inspector

bull API calls made by GUI are captured

bull GET POST

bull Navigating through panes fetches data with GET requests

bull Submitting configuration changes uses POST requests

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Capturing API Calls

POST

url http172233215apinodemounitn-Ciscojson

fvTenant

attributes

name Cisco

status created

children []

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Getting Started

1 Get the Cobra SDK

2 Get the documentation

3 Establish authenticated session

4 Simple queries

5 Inserting data into object store

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

SDK and Documentation

bull Can be downloaded from APIC

bull httpsltapicgtcobra

bull Available on DevNet

bull httpsdeveloperciscocomsiteapic-dc

bull Downloads -gt Python Egg Files

bull You will need to reference the Management Information Model Bookmark itbull httpsdeveloperciscocommediamim-ref or

httpsltapicgtdochtml

bull Python SDK docs (and install directions)bull httpsdeveloperciscocomsiteapic-

dcdocumentspythonapi or

bull httpsltapicgtcobra

bull APIC REST API User Guidebull httpwwwciscocomcenustddocsswitche

sdatacenteraciapicsw1-xapirestb_APIC_RESTful_API_User_Guidehtml

httpcsco9006xDw6

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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

bull 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

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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]

Tip To inspect http requests use debuglevel on httplib

import httplib

httplibHTTPConnectiondebuglevel =

1

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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

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

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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)

bull 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

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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

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)

Another Tip Disable the annoying Requests Insecure Warning Put this at the top of your script

import requestspackagesurllib3

requestspackagesurllib3disable_warnings()

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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

httpgithubcomdatacenterarya

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)

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

bull Get input configuration

1 Right-click save XML

2 Monitor API inspector

3 Query APIC for config

bull Easiest Right-click save XML

Using arya (12)

Select only configuration and subtree

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Using arya (22)

aryapy -f accportprof-vm-vpc10xml

usrbinenv python

Autogenerated code using aryapy

Original Object Document Input

ltxml version=10 encoding=UTF-8gtltimdata totalCount=1gtltinfraAccPortP descr= dn=uniinfraaccportprof-vm-vpc10 name=vm-vpc10 ownerKey= ownerTag=gtltinfraHPortS descr= name=vm-vpc10

ownerKey= ownerTag= type=rangegtltinfraRsAccBaseGrp fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10gtltinfraPortBlk descr= fromCard=1 fromPort=10 name=block1 toCard=1

toPort=10gtltinfraHPortSgtltinfraAccPortPgtltimdatagt

raise RuntimeError(Please review the auto generated code before +

executing the output Some placeholders will +

need to be changed)

list of packages that should be imported for this code to work

import cobramitaccess

import cobramitrequest

import cobramitsession

import cobramodelinfra

import cobramodelpol

from cobrainternalcodecxmlcodec import toXMLStr

log into an APIC and create a directory object

ls = cobramitsessionLoginSession(https1111 admin password)

md = cobramitaccessMoDirectory(ls)

mdlogin()

the top level object on which operations will be made

polUni = cobramodelpolUni()

infraInfra = cobramodelinfraInfra(polUni)

build the request using cobra syntax

infraAccPortP = cobramodelinfraAccPortP(infraInfra ownerKey= name=vm-vpc10 descr= ownerTag=)

infraHPortS = cobramodelinfraHPortS(infraAccPortP ownerKey= type=range name=vm-vpc10 descr= ownerTag=)

infraRsAccBaseGrp = cobramodelinfraRsAccBaseGrp(infraHPortS fexId=101 tDn=uniinfrafuncprofaccbundle-vm-vpc10)

infraPortBlk = cobramodelinfraPortBlk(infraHPortS name=block1 descr= fromPort=10 fromCard=1 toPort=10 toCard=1)

commit the generated code to APIC

print toXMLStr(infraInfra)

c = cobramitrequestConfigRequest()

caddMo(infraInfra)

mdcommit(c)

Complete executable Cobra script to create the vPC profile

Now just substitute in APIC IP and credentials and remove this safety exception

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Get fabric OSPF neighbors Codedef 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

Print

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Sample Print all EPGs used on all Leafs

bull Need to perform impact analysis

bull Check which app tiers will be impacted by leaf downtime (code upgrade etc)

bull Quick way to find EPGs used on Leafs

bull REST API provides Trace method to find this

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Print all EPGs used on all Leafs Code

ls = cobramitsessionLoginSession(apicUri apicUser apicPassword)

md = cobramitaccessMoDirectory(ls)

mdlogin()

leaf_nodes = mdlookupByClass(fabricNode propFilter=eq(fabricNoderole leaf)

for leaf_node in leaf_nodes

epg_ref = mdquery(cobramitrequestTraceQuery(leaf_nodedn fvEpP))

print leaf_nodedn

for epg in epg_ref

print epgepgPKey

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Print all EPGs used on all Leafs

topologypod-1node-103

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-161

unitn-commonap-firewallepg-asa-ha

topologypod-1node-164

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

topologypod-1node-105

unitn-CiscoLiveap-Testepg-Test1

unitn-CiscoLiveap-Testepg-Test2

unitn-CiscoLiveap-Testepg-Test3

topologypod-1node-163

unitn-commonap-firewallepg-asa-ha

unitn-commonap-loadbalancerepg-F5

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Best Practices

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Best Practices

1 Utilize built in naming and Dn methods

2 Be granularspecific with your commits and queries

3 Avoid multiple lookups by starting off with static Dnrsquos instead of resolving

4 Donrsquot use lsquofromrsquo in imports to avoid namespace collisions

5 Use REST API filtering to reduce result set

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

encap=vlan-2 tDn=topologypod-

1paths-101pathep-[eth11])

fvRsPathAtt =

cobramodelfvRsPathAtt(fvAEPg

tDn=interfacedn)

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

2 Commit and Query Granularity

bull The API uses a directory based architecture

bull Closer to your target means less time and more accurate queries

bull Following this practice also helps avoid context root issues

bull APIC stores data in distributed data stores

bull If you go up too high no single APIC can own the data

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

21 Commit and Query Granularity

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

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

3 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

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

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

4 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

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

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

5 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

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

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Applicability

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

How others are using these

bull Partners with application and business modeling

bull Direct translation of business rules to application policy

bull Customers with large repeated deployments

bull Repeated EPG-as-VLAN build outs

bull Template based definitions for new tenant onboarding

bull Within Cisco

bull Fully automated QA solution test process

bull Advanced Services rapid testbed deployment

bull Cisco IT heavily leveraging APIC automation

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Conclusion

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

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

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Participate in the ldquoMy Favorite Speakerrdquo Contest

bull Promote your favorite speaker through Twitter and you could win $200 of Cisco Press products (CiscoPress)

bull Send a tweet and include

bull Your favorite speakerrsquos Twitter handle

bull Two hashtags CLUS MyFavoriteSpeaker

bull You can submit an entry for more than one of your ldquofavoriterdquo speakers

bull Donrsquot forget to follow CiscoLive and CiscoPress

bull View the official rules at httpbitlyCLUSwin

Promote Your Favorite Speaker and You Could Be a Winner

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Complete Your Online Session Evaluation

Donrsquot forget Cisco Live sessions will be available for viewing on-demand after the event at CiscoLivecomOnline

bull Give us your feedback to be entered into a Daily Survey Drawing A daily winner will receive a $750 Amazon gift card

bull Complete your session surveys though the Cisco Live mobile app or your computer on Cisco Live Connect

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Continue Your Education

bull Demos in the Cisco campus

bull Walk-in Self-Paced Labs

bull Table Topics

bull Meet the Engineer 11 meetings

bull Related sessions

bull BRKACI-3204 - Automating Operational Tasks in Cisco ACI

bull BRKACI-1024 - Dev-Ops and the Application Centric Infrastructure - Open Standards and Open APIs

Thank you

Thank you