0% found this document useful (0 votes)
56 views766 pages

Cisco Network Programmability Course Guide

Uploaded by

Erdeniz Unvan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views766 pages

Cisco Network Programmability Course Guide

Uploaded by

Erdeniz Unvan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Designing and Implementing Cisco

Network Programmability (NPDESI)

v1.0
Course Introduction
Designing and Implementing Cisco Network Programmability (NPDESI)
v1.0
Learner Skills and Knowledge
• Baseline Python knowledge
• CCNA/CCNP level network background
Course Goal
Upon completing this course, you will be able to meet these objectives:
• Provides the student a foundation to get started with network programmability by
learning how to minimize the amount of manual interactions (“CLI”) with the network
and increase the use of scripts and automation tools to drive down operational
inefficiencies. Within these goals, the learner reviews network programmability
fundamentals such as using Linux and Python, common automation protocols such
as NETCONF and REST, how they relate to YANG data models, SDN controller
northbound and southbound APIs, how to use device APIs on various Cisco
platforms, and how to get started using automation tools such as Ansible and
Puppet.
Course Flow
AM PM

Day 1 Course Intro Network Programmability Fundamentals


Network Programmability Fundamentals
Day 2 APIs and Automation Protocols APIs and Automation Protocols

Day 3 APIs and Automation Protocols Data Models


Data Models SDN Controllers
Day 4 SDN Controllers SDN Controllers
Network Operations
Day 5 Network Operations Network Operations
Cisco Career Certifications
Expand Your Professional Options, Advance Your Career
Learner Introductions
• Your name
• Your company
• Job responsibilities
• Skills and knowledge
• Brief history
• Objective
Network Programmability
Fundamentals
Designing and Implementing Cisco Network Programmability (NPDESI)
v1.0
Introduction to Network
Programmability
Network Programmability Fundamentals
Understanding Software-Defined Networking
What is Software-Defined Networking?
• An approach and architecture in networking where control and data planes are
decoupled and intelligence and state are logically centralized.
• Enablement where underlying network infrastructure is abstracted from the
applications [network virtualization].
• A concept that leverages programmatic interfaces to enable external systems to
influence network provisioning, control, and operations.
• Is SDN one or more of these statements?
Understanding Software-Defined Networking (Cont.)
Software-Defined Networking is:
• An approach to network transformation
• Empowering external influencers to network design and operations
• Impacting the networking industry—challenging the way you think about
engineering, implementing and managing networks
• Providing new methods to interact with equipment/services via controllers, APIs
• Normalizing the interface with equipment/services
• Enabling high-scale, rapid network and service provisioning/management
• Generating a LOT of ‘buzz’ and attention
• Providing a catalyst for traditional Route/Switch engineers to branch-out
Understanding Software-Defined Networking (Cont.)
Software-Defined Networking is NOT:
• An easy button… [but is intended to make things easier for all!]
• A panacea or end-state
• Narrowly defined
• Designed to replace network engineers
• A mandate for all network engineers to become programmers
• A new attempt at network evolution
Traditional versus Software-Defined Networks
The Traditional Network
• Control plane learns/computes forwarding decisions.
• Data plane acts on the forwarding decisions.
Traditional versus Software-Defined Networks (Cont.)
The Network As It Could Be…to an SDN ‘Purist’
• Control plane becomes centralized
• Physical device retains data plane functions only
Traditional versus Software-Defined Networks (Cont.)
The Network As It Could Be…In a ‘Hybrid SDN’
• A Controller is centralized and separated from the Physical Device, but devices still
retain localized Control plane intelligence.
Traditional versus Software-Defined Networks (Cont.)
Why Change?
• Familiar Manual, CLI-driven, device-by-device approach is inefficient
• Increased need for programmatic interfaces which allow faster and automated
execution of processes and workflows with reduced errors
• Need for a ‘central source of truth’ and touch-point
Traditional versus Software-Defined Networks (Cont.)
Your Challenges:
• Pace of Change – Technology & Competition
• Globalization of the Marketplace
• Proliferation of Social Networking
• IT Budgets, Staffing, and Resources
• Accelerated Pace of Consumerization, Virtualization, and XaaS Options
• Consumption Economics
Current Industry Trends
Open Source Software
Programmable Infrastructure
Software Defined Networking
DevOps
DevOps (Cont.)
Cisco ACI
• Simplifies, optimizes, and
accelerates the application
deployment lifecycle.
• Employs an open-ecosystem
approach integrating physical
and virtual elements.
• Supports open APIs, open
standards, and open source
elements to enable greater
flexibility for development and
operations.
Network Programmability and Automation
Current Network Operation: Future Network Operation:
• CLI was built for manual human • Version controls all configurations
interaction monitoring changes
• Configuration is one device at a time • Version control is the source of the
• Copying and pasting are the standard truth
• Configuration is prone to error • Automated systems perform testing
before any change is made to the
• Tasks are not easily repeatable configuration including system, style,
• Notepad is the most common text editor reachability, etc.
Uses of Network Automation
Types of Network Automation
• Device Provisioning
• Data Collection & Telemetry
• Compliance Checks
• Reporting
• Troubleshooting
Network Automation Scenarios
Data Collection
• For a Cisco ISE deployment, an IT
manager needs to perform an audit of
network switches to gather the
hostname, IP address, platform, and
serial numbers from all network devices
in the organization.
• Correlate user switchport given their IP
Phone Extension
Network Automation Scenarios (Cont.)
Configuration Management Scenarios
• Due to new vulnerability, new ACLs needed to be added to Cisco ASA FWs at each
branch site.
• ISE Deployment requires commands on each and every switch.
• Enterprise needs to add BGP peers frequently for business partners.
• Documented processes lend themselves to automation.
Management Plane
Why Is Network Automation Different Now?
• PERL, Expect, and SSH connectivity has existed for years
• It was possible – tedious and error prone, but possible
• Manual parsing – lots of regular expressions
• Going forward
– Programmatic APIs
– No parsing
– Automatic failure on rollback
– Configuration changes as a transaction
Open Source Tools and Enterprise Platforms
Network Programmability Technology
• Linux
• Device and Controller APIs
• Version Control
• Software Development
• Automated Testing
• Continuous Integration
Network Automation Workflow
Configuration Management Workflow [Sample]
Cisco Platforms and APIs

Platform(s) Programmatic API(s)

IOS XE NETCONF, RESTCONF

IOS XR NETCONF, RESTCONF, gRPC

Nexus NX-API CLI, NX-API REST, NETCONF

Adaptive Security Appliances (ASA) REST

Application Centric Infrastructure (ACI) REST

APIC-EM REST
Linux Primer for Network Engineers
Network Programmability Fundamentals
Why Learn Linux?
Linux is everywhere—Used in various devices:
• Mobile devices
• Desktop Computers
• Production Servers
• Hypervisors
• Network switches
Why Learn Linux? (Cont.)
Though Linux is pervasive in technology, a network
programmability engineer should learn Linux
because:
• Network devices now expose the underlying Linux shell
• Network devices now enable engineers to run
containers on the actual network device
• Most software development environments are Linux-
based
• New open source projects such as Open vSwitch,
Docker, and OpenStack all have a Linux foundation
Navigating the Linux File System
Super User Privileges
• “super user” do
• Run a program as another user (ex: root privileges by default)
• Can configure who can run sudo commands in the “sudoers” file
• Debian/Ubuntu distros do not enable the root user

cisco@cisco: ~$
cisco@cisco: ~$ sudo su -
[sudo] password for cisco:
root@cisco: ~#

root@cisco: ~#
root@cisco: ~# exit
logout
cisco@cisco: $
Paths and Directories

Basic Commands
Command Description

pwd Print working directory

ls List contents of working directory

man <command> View manual pages (how-to) to learn how to use a given command and it’s flags
Paths and Directories (Cont.)
• Relative Path
– Address relative to the current, or working, directory
• Absolute Path
– Address relative to the root directory

cisco@cisco: ~/scripts$ pwd


/home/cisco/scripts
cisco@cisco: ~/scripts$ cd cisco
cisco@cisco: ~/scripts/cisco$
cisco@cisco: ~/scripts/cisco$ cd /var/log
cisco@cisco: /var/log$
cisco@cisco: /var/log$ pwd
/var/log
Paths and Directories (Cont.)

Change Directories
cd .. Change current directory to parent directory

cd Back to the home directory

cd ../.. Back two directories (there is no limit on this)

cd - Moves back to previous working directory


Linux Distributions and Package Managers
Package Management
• Packages are a convenient method to deliver software
• Package tool maintains a database of installed applications
• Two main CLI tools required to install, update and remove software
Package Management (Cont.)
Red Hat Family
rpm Install local rpm package

yum Download and install a package from repositories

.rpm File extension

cisco@cisco: ~$ sudo yum install traceroute

cisco@cisco: ~$ sudo rpm –i <package-name>.rpm


Package Management (Cont.)
Debian Family
dpkg Command to install a local .deb package

apt & apt-get Commands to download and install packages

.deb File extension

cisco@cisco: ~$ sudo apt-get install traceroute

cisco@cisco: ~$ sudo apt install traceroute

cisco@cisco: ~$ sudo dpkg –i <package-name>.deb


Working with Files and Directories
touch
• Updated time stamps of files and creates an “empty” file
cisco@cisco: ~$
cisco@cisco: ~$ touch catalyst_config.txt
cisco@cisco: ~$
cisco@cisco: ~$ ls
catalyst_config.txt cisco Desktop Documents Downloads Templates
cisco@cisco: ~$
cisco@cisco: ~$ ls -l catalyst_config.txt
-rw-rw-r-- 1 cisco cisco 0 Jun 24 11:50 catalyst_config.txt
Working with Files and Directories (Cont.)

Make Directory Commands


Command Description

mkdir Make a new directory

mkdir -p Make all required sub-directories in the path


Working with Files and Directories (Cont.)

Remove Commands
Command Description

rm Removes a file

rm -r Removes an entire directory and its contents

rmdir Removes an entire empty directory

rm -rf Removes a directory and contents including write-protected files


Working with Files and Directories (Cont.)
Copy and Move Commands
Command Description

cp Copy a file

mv Move/rename a file

cisco@cisco: ~/Nexus9000$
cisco@cisco: ~/Nexus9000$ cp file1 file2
cisco@cisco: ~/Nexus9000$
cisco@cisco: ~/Nexus9000$ mv file2 file3
cisco@cisco: ~/Nexus9000$
cisco@cisco: ~/Nexus9000$ ls
file1 file3
Working with Files and Directories (Cont.)
Viewing Files Commands
Command Description

more similar to using Cisco CL—space bar takes you down a full screen length (% in bottom
left).

less “less is more” because it allows the user to scroll up and down using arrow keys vs. just
the ability to space down.
cat Streams the file top to bottom without pausing.

head By default shows first 10 lines of a file.

tail By default shows last 10 lines of a file.

diff View diff between two files (hint: use –c option).


File Permissions
Linux operating systems are multi-user

Permissions are based on two factors:


• Permissions assigned to a specific user and group
• Permissions assigned to a specific action (read, write, execute)
File Permissions (Cont.)

cisco@cisco:~$ ls -l [Link]
-rw-rw-r-- 1 cisco cisco 117 Aug 6 2015 [Link]
cisco@cisco:~$
File Permissions (Cont.)
cisco@cisco:~$ ls -l vlans_script.py
-rw-rw-r-- 1 cisco cisco 0 Sep 12 15:14 vlans_script.py
cisco@cisco:~$
cisco@cisco:~$ chmod u+x vlans_script.py
cisco@cisco:~$
cisco@cisco:~$ ls -l vlans_script.py
-rwxrw-r-- 1 cisco cisco 0 Sep 12 15:14 vlans_script.py
cisco@cisco:~$
cisco@cisco:~$ chmod go+x+w vlans_script.py
cisco@cisco:~$
cisco@cisco:~$ ls -l vlans_script.py
-rwxrwxrwx 1 cisco cisco 0 Sep 12 15:14 vlans_script.py
cisco@cisco:~$
Linux Processes
Viewing Running Processes
• top
– Displays real time processor utilization
• htop
– Displays real time processor utilization in an easier to read format
• ps
– Display active processes
• ps aux
– Displays an exhaustive list of all processes by all users
Linux Processes (Cont.)
Viewing Running Processes
• ps
• ps aux | grep firefox

cisco@cisco: ~$ ps aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.3 24196 3256 ? Ss 20:15 0:01 /sbin/init splash
root 2 0.0 0.0 0 0 ? S 20:15 0:00 [kthreadd]
root 3 0.0 0.0 0 0 ? S 20:15 0:00 [ksoftirqd/0]
root 5 0.0 0.0 0 0 ? S< 20:15 0:00 [kworker/0:0H]
(output omitted)

cisco@cisco: ~$ ps aux | grep firefox


cisco 2442 29.0 19.5 574872 200716 ? Sl 21:12 0:01 /usr/lib/firefox/firefox
cisco 2497 0.0 0.0 5108 800 pts/6 S+ 21:12 0:00 grep --color=auto firefox
Linux Processes (Cont.)
kill
• Ends a running process
• Used along with the process ID (PID) to kill an individual process

cisco@cisco: ~$
cisco@cisco: ~$ ps aux | grep firefox
cisco 2442 29.0 19.5 574872 200716 ? Sl 21:12 0:01 /usr/lib/firefox/firefox
cisco 2497 0.0 0.0 5108 800 pts/6 S+ 21:12 0:00 grep --color=auto firefox
cisco@cisco: ~$ kill 2442
cisco@cisco: ~$
Discovery 1: Using the Linux
Command Line
Topology
Linux Networking
Network Programmability Fundamentals
Basic Linux Networking Commands

Command Description

ping Test connectivity between two nodes. In Linux, ping will run continuously unless
manually stopped. Supports options such as on Cisco CLI (hint: man pages).
traceroute Displays the layer 3 hops taken to reach a destination

ifconfig Displays interface information of all interfaces

ifconfigeth1 Displays interface information of a specific interface


Basic Linux Networking Commands (Cont.)
ip link Lists all the interfaces on the local system.

ip addr list
cisco@cisco: ~$ ip addr list
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet [Link]/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth2: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP
group default qlen 1000
link/ether 08:00:27:ce:e4:72 brd ff:ff:ff:ff:ff:ff
inet [Link]/24 brd [Link] scope global eth2
valid_lft forever preferred_lft forever
inet6 fe80::a00:27ff:fece:e472/64 scope link
valid_lft forever preferred_lft forever
Basic Linux Networking Commands (Cont.)
ifconfig vs. ip
• The command /bin/ip has been around for a long time, but people are still using the
older command /sbin/ifconfig.
• The ip command is more powerful and will eventually replace it.
Basic Linux Networking Commands (Cont.)
ip addr Assign or delete an IP address to a specific interface. The new network settings are
not persistent through a system restart.

cisco@cisco: ~$ sudo ip addr { add | del } a.b.c.d/yz dev <interface>

cisco@cisco: ~$
cisco@cisco: ~$ sudo ip addr add [Link]/24 dev eth1
cisco@cisco: ~$
Basic Linux Networking Commands (Cont.)
ip route Add a route to the local system.

cisco@cisco: ~$
cisco@cisco: ~$ sudo ip route add [Link]/24 via [Link] dev eth1
cisco@cisco: ~$
Basic Linux Networking Commands (Cont.)
ifup Used to enable or disable a specific interface.

ifdown

cisco@cisco: ~$
cisco@cisco: ~$ sudo ifdown eth1
cisco@cisco: ~$
cisco@cisco: ~$ sudo ifup eth1
cisco@cisco: ~$
Basic Linux Networking Commands (Cont.)
Netstat Commands
Command Description

netstat Displays local computer’s connection information, routing table information

netstat-r Displays local routing table (same as the route command)

netstat-i Displays interface statistics

cisco@cisco: ~$ netstat -i
Kernel Interface table
Iface MTU Met RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0 1500 0 28677 0 0 0 16559 0 0 0
BMRU
lo 65536 0 2239 0 0 0 2239 0 0 0 LRU
Basic Linux Networking Commands (Cont.)
dig Used to display DNS information such as A Records, MX Records, and CNAMES

cisco@cisco: ~$
cisco@cisco: ~$ dig [Link]

; <<>> DiG 9.9.5-3ubuntu0.7-Ubuntu <<>> [Link]


;; global options: +cmd
;; Got answer:
< output truncated >
; EDNS: version: 0, flags:; udp: 4000
;; QUESTION SECTION:
;[Link]. IN A

;; ANSWER SECTION:
[Link]. 73480 IN A [Link]
Basic Linux Networking Commands (Cont.)
host Used to resolve a hostname to an IP address or vice versa and learn DNS information
such as MX Records, Name Servers, CNAME, etc.

cisco@cisco: ~$
cisco@cisco: ~$ host [Link]
[Link] has address [Link]
[Link] has IPv6 address 2001:420:1101:1::a
[Link] mail is handled by 20 [Link].
[Link] mail is handled by 10 [Link].
[Link] mail is handled by 30 [Link].
cisco@cisco: ~$
Basic Linux Networking Commands (Cont.)
ssh Used to securely log in to remote systems. The username can be included in the
command.

cisco@cisco: ~$ ssh [Link] (uses system username - cisco)

cisco@cisco: ~$ ssh admin@[Link] -p 2222

cisco@cisco: ~$ ssh –l john [Link]


Viewing the Routing and ARP Tables
ip route list Primary method for viewing and modifying the routing table.

cisco@cisco: ~$
cisco@cisco: ~$ ip route list
default via [Link] dev enp0s3 proto static metric 100
default via [Link] dev enp0s8 proto static metric 101
default via [Link] dev enp0s9 proto static metric 102
[Link]/24 dev enp0s3 proto kernel scope link src [Link] metric 100
[Link]/24 dev enp0s8 proto kernel scope link src [Link] metric 100
[Link]/24 dev enp0s9 proto kernel scope link src [Link] metric 100
[Link]/16 dev enp0s3 scope link metric 1000
[Link]/24 dev enp0s3 proto kernel scope link src [Link]
cisco@cisco: ~$
Viewing the Routing and ARP Tables (Cont.)
route Another command to view and modify the routing table.

cisco@cisco: ~$
cisco@cisco: ~$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default [Link] [Link] UG 100 0 0 enp0s3
default [Link] [Link] UG 101 0 0 enp0s8
default [Link] [Link] UG 102 0 0 enp0s9
[Link] * [Link] U 100 0 0 enp0s3
[Link] * [Link] U 100 0 0 enp0s8
[Link] * [Link] U 100 0 0 enp0s9
link-local * [Link] U 1000 0 0 enp0s3
[Link] * [Link] U 0 0 0 enp0s3
Viewing the Routing and ARP Tables (Cont.)
arp View local system ARP table. Set a static ARP entry.

cisco@cisco: ~$ arp
Address HWtype HWaddress Flags Mask Iface
[Link] ether 52:54:00:12:35:02 C enp0s3
cisco@cisco: ~$

cisco@cisco: ~$ arp -s LOCAL_MACHINE 50:51:52:53:54:55


cisco@cisco: ~$
Persistent Network Configuration
Interface Configuration File
• Persistent interface route information is stored in: /etc/network/interfaces

auto eth0
iface eth0 inet static
address [Link]
netmask [Link]
up ip route add [Link]/24 via [Link] dev eth2
up ip route add [Link]/24 via [Link] dev eth3

auto eth1
iface eth1 inet dhcp
Persistent Network Configuration (Cont.)
Updating DNS
• DNS information is stored in the [Link] file
• The absolute path is /etc/[Link]
• Dynamically constructed from files located in: /etc/resolvconf/[Link].d/
• Files in this directory include head, tail, base – update these and regenerate
/etc/[Link] with sudo resolvconf -u
# Dynamic [Link](5) file for glibc resolver(3) generated by resolvconf(8)
# DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
nameserver [Link]
nameserver [Link]
~
~
~
"/etc/[Link]"
Persistent Network Configuration (Cont.)
Restarting the Networking Service
• Networking service must be restarted after making changes to the network
configuration
– Changing an IP address or subnet mask
– Reconfiguring a gateway
– Adding additional NICs

cisco@cisco: ~$
cisco@cisco: ~$ sudo service networking restart
cisco@cisco: ~$
Discovery 2: Linux Networking
Topology
Python Foundations for Network
Engineers – Part 1
Network Programmability Fundamentals
Understanding Python
Why Learn Python?
• Interpreted Scripting Language
• Low barrier to entry compared to other
languages
• Can be used to write various types of Python
Applications
• Python Execution Engine exists on most Linux
distributions including network operating
systems, such as NX-OS
Understanding Python (Cont.)
Python 2.x Python 3.x
• No longer under active development, • Under active development
but supported by the Python community • Designed to be easier to learn
• Better library support • Fixed major issues are 2.x
• Default on Linux and Mac • Not backwards compatible
• Supported by Cisco NX-OS
Executing Python Code
Using the Dynamic Interpreter (shell)

cisco@cisco: ~$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>

To exit the shell, use exit() or CTRL+D


Executing Python Code (Cont.)
Writing Python Scripts

#!/usr/bin/env python

if __name__ == "__main__":
course = 'Designing and Implementing Cisco Network Programmability'
print course

cisco@cisco: ~$ python [Link]


Designing and Implementing Cisco Network Programmability
cisco@cisco: ~$
Python Helper Utilities and Function
• help()—Returns the python built-in documentation about the object.
• dir()—Returns the attributes (and methods) of the object or module
• type()—Returns the type of the object

>>> type('[Link]') <type 'str'> >>>


>>> dir(str)
['replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper',
'zfill']
### output truncated for brevity ###
>>>
>>> help([Link])
Writing Idiomatic Python
• Single-Line comments
• Multi-line comments
• Whitespace
• Indentation
– Spaces vs. Tabs
• Python Style Guide (PEP8)
Common Python Data Types
• Strings
• Numbers
• Lists
• Dictionaries
• Booleans
• Files
Variable Assignment
• Assign a value to a variable using the equals sign (“=“)
• ipaddr was assigned the value of “[Link]”

>>>
>>> ipaddr = '[Link]'
>>>
Data Types: Strings
• Sequence of characters that >>> ipaddr = '[Link]'
>>>
are surrounded by quotes >>> hostname = 'nxos1'
• Immutable – individual >>>
characters cannot be natively >>> hostname = "nxos2"
>>>
modified >>> hostname[4] = '3'
• Empty string Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item
assignment
>>>
>>>
>>> os_version = ''
>>>
Printing Strings
• Using the print statement to print strings
– Prints the rendered string
• Typing in the variable name on the Interpreter
– Prints the value as a string literal

>>> interface_config = 'interface Eth1/1\n no switchport'


>>>
>>> interface_config
'interface Eth1/1\n no switchport'
>>>
>>> print interface_config
interface Eth1/1
no switchport
>>>
Concatenating Strings
Concatenate or add one or more strings together

>>> ipaddr = '[Link]'


>>> mask = '[Link]'
>>>
>>> ipmask = ipaddr + ' ' + mask
>>>
>>> ipmask
'[Link] [Link]'
>>>
String Built in Methods
• Working with common built-in methods >>> hostname = 'nxos1'
>>> [Link]()
• Use dir() on any object to see its 'NXOS1'
available built-in methods >>>
>>> macaddr = '00:11:22:33:44:55'
– <string>.upper() / .lower() >>> [Link](':', '.')
– <string>.replace() '[Link].44.55'
>>>
– <string>.startswith()
>>> ipaddr = '[Link]'
– <string>.format() >>> [Link]('10')
– <string>.split() True
>>>
>>> ipaddr = '10.{}.1.1'
>>> [Link]('200')
'[Link]'
>>>
>>> ipaddr = '[Link]'
>>> [Link]('.')
['10', '4', '8', '1']
Data Type: Numbers
• You can perform mathematical operations directly in code
• Integers and Floating Point numbers
• Operators such as +, -, *, /, //, % are used

>>> 5 * 4 >>> 10 / 3
20 3
>>> 10 - 4 >>> 10.0 / 3
6 3.3333333333333335
>>> >>>
>>> 239234 + 4 >>> 10.0 // 3
239238 3.0
>>> >>>
Data Type: Booleans
• Values are True or False AND Result
• Operators are and, or, and not True and False False
• not takes the inverse True and True True

False and False False

OR Result

>>> True and False True or False True


False True or True True
>>>
>>> True or False False or False False
True
>>> NOT Result
>>> not (True or False)
not True False
False
>>> not False True
Conditionals
• Expressions evaluate to True or False >>> 9372 > 9396
False
• Comparison Operators >>>
– ==, !=, >, <, >=, <= >>> 'nexus' != 'catalyst'
True
• Logical Operators >>>
>>> 'nexus' in 'nexus 9396'
– and, or, not
True
• Membership Operators >>>
>>> '9372' not in 'nexus 9396'
– in, not in True
• Identity Operators >>>

– is, is not
Conditionals (Cont.)
>>> switch = 'catalyst 3850'
Conditional Statements >>>
• if, elif, else >>> if 'catalyst' in switch:
• End with a colon ... switch_type = 'catalyst'
... elif 'nexus' in switch:
• Consistent indentation required ... switch_type = 'nexus'
... else:
... switch_type = 'unknown'
...
>>>
>>> print switch_type
catalyst
>>>
Discovery 3: Python Foundations -
Part 1
Topology
Python Foundations for Network
Engineers – Part 2
Network Programmability Fundamentals
Lists
• Contains one or more objects >>> devices = ['asa', 'nexus', 'nexus',
'catalyst', 'asr']
in an ordered list >>>
• Indexed starting at zero >>> devices[2] = 'aci'
>>>
• Mutable – individual elements >>> print devices ['asa', 'nexus', 'aci',
can be modified 'catalyst', 'asr']
>>>
• Supports reverse index values >>> print devices[-1]
• Empty List – [] asr
>>> unknown_devices = []
>>>
Lists (Cont.)
>>> devices = ['asa', 'nexus', 'asa']
Working with common built-in >>>
methods >>> [Link]('aci')
• <list>.append() >>>
>>> [Link](0, 'asr')
• <list>.insert() >>>
• <list>.pop() >>> devices
['asr', 'asa', 'nexus', 'asa', 'aci']
>>>
>>> [Link]()
'aci'
>>>
Lists (Cont.)
>>> [Link]('asa')
Working with common built-in 2
methods (continued) >>>
• <list>.count() >>> devices
['asr', 'asa', 'nexus', 'asa']
• <list>.extend() >>>
• <list>.sort() >>> [Link]()
>>>
Dictionaries
• Contains one or more items >>> facts = {'hostname': 'nxos1', 'os': '7.0.3'}
>>>
and is an unordered list >>> print facts['hostname']
• Item is a key-value pair nxos1
>>>
• Indexed by name/key >>> print facts['os']
• Mutable – individual elements 7.0.3
>>>
can be modified >>> facts['os'] = '7.0.2'
• Uses curly braces {} >>>
>>> print facts
{'hostname': 'nxos1', 'os': '7.0.2'}
>>>
>>> device_facts = {}
>>>
Dictionaries (Cont.)
>>> facts = {'hostname': 'nxos1', 'os': '7.0.3'}
Working with common >>>
built-in methods >>> [Link]({'vendor': 'cisco', 'platform':
• <dict>.update() '9396'})
>>>
• <dict>.pop() >>> facts
• <dict>.get() {'vendor': 'cisco', 'platform': '9396', 'hostname':
'nxos1', 'os': '7.0.3'}
>>>
>>> [Link]('platform')
'9396'
>>>
>>> print [Link]('vendor')
cisco
>>>
>>> print [Link]('os_version')
None
>>>
Dictionaries (Cont.)
>>> [Link]()
Working with common ['vendor', 'hostname', 'os']
built-in methods >>>
(continued) >>> [Link]()
['cisco', 'nxos1', '7.0.3']
• <dict>.keys() >>>
• <dict>.values() >>> [Link]()
[('vendor', 'cisco'), ('hostname', 'nxos1'), ('os',
• <dict>.items() '7.0.3')]
>>>
Loops
For Loops
• Has the ability to iterate over items of any data type
>>> devices = ['asr', 'asa', 'nexus', 'catalyst']
>>>
>>> for item in devices:
... print 'Device type is {}'.format(item)
...
Device type is asr
Device type is asa
Device type is nexus
Device type is catalyst
>>>
Loops (Cont.)
While Loop
• Iterate over object until a given condition
>>> interface_id = 1
>>>
>>> while interface_id <= 4:
... print 'Ethernet1/{}'.format(interface_id)
... interface_id += 1
...
Ethernet1/1
Ethernet1/2
Ethernet1/3
Ethernet1/4
>>>
Function
• Create re-usable objects in your code >>> devices = ['r1', 'r2', 'r3']
>>>
• Helps with making code modular >>> len(devices)
3
• Take note when you see the same lines
>>>
of code more than once in your script >>> hostname = 'SJCRTR01R1'
• Built-in functions >>>
>>> len(hostname)
– len(), type(), dir(), help() 10
>>>
Function (Cont.)
• Create a function by defining it and then calling it
• Optionally passing parameters and returning data

>>> def get_vlans(): >>> def vlan_exists(vlan_id):


... vlans_list = [1, 5, 10, 20] ... vlans_list = [1, 5, 10, 20]
... return vlans_list ... return vlan_id in vlans_list
... ...
>>> vlans = get_vlans() >>> vlan_exists(5)
>>> True
>>> print vlans >>> vlan_exists(11)
[1, 5, 10, 20] False
>>> >>>
Working with Files
• Basic read and write operation for files
• Optionally passing parameters and returning data
>>> config = open('[Link]', 'r')
>>>
>>> vlans = [Link]()
>>>
>>> vlans
'vlan 10\n name USERS\nvlan 20\n name VOICE\nvlan 30\n name WLAN\nvlan 40\n
name APP\nvlan 50\n name WEB\nvlan 60\n name DB'
>>> >>> print vlans
vlan 10
name USERS
vlan 20
name VOICE
### output truncated for brevity
Discovery 4: Python Foundations –
Part 2
Topology
Writing and Troubleshooting Python
Scripts
Network Programmability Fundamentals
Writing Scripts
• Include shebang (used by shell) #!/usr/bin/env python

• Define an entry point def vlan_exists(vlan_id):


• Often end with .py extension vlans_list = [1, 5, 10, 20]
return vlan_id in vlans_list
• Code is the same as you have seen on
the Python interactive interpreter if __name__ == "__main__":

vlans = [5, 8, 10, 15, 20]

for vlan in vlans:


print vlan, vlan_exists(vlan)
Executing Scripts
#!/usr/bin/env python cisco@cisco:~$ python vlan_check.py
5 True
def vlan_exists(vlan_id): 8 False
vlans_list = [1, 5, 10, 20] 10 True
return vlan_id in vlans_list 15 False
20 True
cisco@cisco:~$
if __name__ == "__main__":

vlans = [5, 8, 10, 15, 20]

for vlan in vlans:


print vlan, vlan_exists(vlan)
Analyzing Code
Pay attention to the following when getting started:
• Accessing data in lists (index) and dictionaries (key)
• Know your data types
• Variable scoping
• Code blocks and indentation with conditionals
Analyzing Code (Cont.)
Accessing data in lists (index) and dictionaries (key)

>>> neighbors = ['s1', 's2', 's3']


>>>
>>> facts = {'hostname': 'cisco', 'os': '7.0.2', 'neighbors': neighbors}
>>>
>>> facts['neighbors'][1]
's2'
>>>
Analyzing Code (Cont.)
Know your data types

>>> neighbors = ['s1', 's2', 's3']


>>>
>>> facts = {'hostname': 'cisco', 'os': '7.0.2', 'neighbors': neighbors}
>>>
>>> type(neighbors)
<type 'list'>
>>>
>>> type(facts)
<type 'dict'>
>>>
>>> type(facts['neighbors'])
<type 'list'>
>>>
Analyzing Code (Cont.)
Variable scoping #!/usr/bin/env python

ipaddr = '[Link]'
mask = '24'

def get_ip(ip):
print 'Function 1: ', ip
print 'Function 2: ', mask
print 'Function 3: ', ipaddr
print 'Function 4: ', mask

if __name__ == "__main__":
print 'Main 1: ', ipaddr
print 'Main 2: ', mask
ipaddr = '[Link]'
get_ip(ipaddr)
print 'Main 3: ', ip
Analyzing Code (Cont.)
Variable scoping (continued)

cisco@cisco:~$ python variable_scope.py


Main 1: [Link]
Main 2: 24
Function 1: [Link]
Function 2: 24
Function 3: [Link]
Function 4: 24
Main 3:
Traceback (most recent call last):
File "variable_scope.py", line 17, in <module>
print 'Main 3: ', ip
NameError: name 'ip' is not defined
cisco@cisco:~$
Analyzing Code (Cont.)
Code blocks and indentation with conditionals

>>> vendor = 'cisco'


>>> platform = 'nexus'
>>> model = '9396'
>>>
Analyzing Code (Cont.)
Code blocks and indentation with conditionals (continued)

>>> if vendor == 'cisco':


... if platform == 'catalyst':
... print 'platform is catalyst'
... elif platform == 'nexus':
... print 'platform is nexus'
... if model == '9396':
... print 'model is 9396'
...
platform is nexus
model is 9396
>>>
Error Handling
• Even if a Python statement is syntactically correct, it can cause an error when an
attempt is made to execute it.
• Errors detected during execution are called exceptions
• Errors (exceptions) are not handled by programs, but by the developer
implementing the program
• Python uses try/except statements to handle exceptions
Error Handling (Cont.)
Understand what errors could be raised based on the task being performed

>>> devices = ['r1', 'r2', 'r3']


>>>
>>> print devices[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>>
Error Handling (Cont.)
• Determine the code to execute if a given exception is caught
• Be as specific as possible when catching exceptions
>>> try:
... print devices[4]
... except (IndexError) as err_msg:
... print 'Insert custom code...'
... print 'Error from Python:', err_msg
...
Insert custom code...
Error from Python: list index out of range
>>>
Error Handling (Cont.)
• Determine the code to execute if a given exception is caught
• Be as specific as possible when catching exceptions
>>> try:
... print devices[4]
... except Exception as err_msg:
... print 'Insert custom code...'
... print 'Error from Python:', err_msg
...
Insert custom code...
Error from Python: list index out of range
>>>
Discovery 5: Writing and
Troubleshooting Python Scripts
Topology
Python Libraries
Network Programmability Fundamentals
Python Libraries
Functions (and other objects) are used to re-use code within a single
program.

Libraries, in the form of modules and packages, are used to re-use code
between programs.
Python Module
Python module is a standalone file that contains Python definitions and
statements.

Python module does not have to be a standalone program


Python Module (Cont.)
• Python Module—standalone file to be #!/usr/bin/env python
re-used by other programs
def vlan_exists(vlan_id):
• Entry point code is not executed when vlans_list = [1, 5, 10, 20]
imported return vlan_id in vlans_list
• Filename: vlan_check.py
if __name__ == "__main__":

vlans = [5, 8, 10, 15, 20]

for vlan in vlans:


print vlan, vlan_exists(vlan)
Python Module (Cont.)
• Use from/import statements to work with Python modules
• Enter Python shell from where the file is saved (or update the PYTHONPATH)

>>> from vlan_check import vlan_exists >>> import vlan_check


>>> >>>
>>> vlan_exists(5) >>> vlan_check.vlan_exists(20)
True True
>>> >>>
>>> vlan_exists(11) >>> vlan_check.vlan_exists(22)
False False
>>> >>>
Python Package
• Python Package is a collection of modules of which can be in different directories
• An __init__.py file is required in each directory
• Enter Python shell from where the base directory is (or update the PYTHONPATH)

>>> from [Link].vlan_check import vlan_exists


>>>
>>> vlan_exists(10)
True
>>>
Python Package (Cont.)
Sample Directory Structure

cisco@cisco:~$ tree npdesi/


npdesi/
├── features
│ ├── __init__.py
│ └── vlan_check.py
└── __init__.py

1 directory, 3 files
cisco@cisco:~$
>>> from [Link].vlan_check import vlan_exists
>>>
>>> vlan_exists(10)
True
>>>
Discovery 6: Custom Python
Libraries
Topology
APIs and Automation Protocols
Designing and Implementing Cisco Network Programmability (NPDESI)
v1.0
Introduction to Network APIs and
Protocols
APIs and Automation Protocols
Evolution of Device Management and Programmability
• Networks were static when protocols such as Simple Network Management
Protocol (SNMP) emerged.
• Managing networks via the Command Line Interface was (and is) the norm.
• Networks have grown to be overly complex.
• Regular Expressions and Expect scripting was the norm for those who did do any
form of automation.
Evolution of Device Management and Programmability
(Cont.)
!
Simple Network Management snmp-server community SJC-COM-1 RO SNMP_RO
Protocol snmp-server community CA-COM-1 RO_TOOLS
• First developed in late 1980s snmp-server community AM-COM-1 RW RW_TOOLS
snmp-server trap-source Loopback0
• Successfully used for snmp-server location AM-USA-CA-SJC
monitoring networks and for snmp-server contact +1 555-555-5555
very basic device modifications snmp-server host [Link] P@ssw0rd
snmp-server host [Link] P@ssw0rd
• Vendors frequently created snmp ifmib ifindex persist
their own MIBs and extensions !
• Not capable of meeting
demands of scale
Evolution of Device Management and Programmability
(Cont.)
Simple Network Management Protocol
• SNMP’s simplicity was a strength when networks were smaller
• v1 and v2 provide very basic and unencrypted security mechanisms
• Not built for real-time communication
• Lack of writable MIBs
• Difficult to replay/rollback configuration
• Lacks libraries for various programming languages
• In 2015, Google announced intent to disable SNMP for monitoring by 2017
Evolution of Device Management and Programmability
(Cont.)
Telnet, SSH, and the Command Line Interface
• Traditional and currently still the primary means of configuring network devices
• Requires human interaction
• Not modular, repeatable, or efficient
• All text based – no common data model among platforms
Evolution of Device Management and Programmability
(Cont.)
History of Network Device Management
Evolution of Device Management and Programmability
(Cont.)
Evolution of Device Management and Programmability
(Cont.)
Model Driven Network Programmability
Model-Driven Programmability Stack
Data Encoding Formats
JSON
• JavaScript Object Notation {
"ins_api": {
• Language independent "type": "cli_show",
"version": "1.2",
• Way of formatting and transmitting data
"sid": "eoc",
that is both human and machine "outputs": {
readable "output": {
"input": "show hostname",
• Sends data objects using name-value
"msg": "Success",
pairs "code": "200",
"body": {
"hostname": "[Link]"
}
}
}
}
}
JSON (Cont.)
• JSON uses name-value pairs, i.e. key- #!/usr/bin/env python
value pairs
import json
• JSON most closely maps to the
dictionary data type in Python if __name__ == "__main__":
• If you understand Python dictionaries, facts = {
'hostname': 'nxosv',
you understand JSON 'os': '7.3',
'location': 'San_Jose'
}
# print facts dictionary
print facts
# print facts as a JSON string
print [Link](facts, indent=4)
# print a specific value of key
print facts['os']
JSON (Cont.)
Script output from previous figure

$ python json_test.py
{'hostname': 'nxosv', 'os': '7.3', 'location': 'San_Jose'}
{
"hostname": "nxosv",
"os": "7.3",
"location": "San_Jose"
}
7.3
JSON (Cont.)
• Be aware of JSON strings that look like dictionaries
• You may need to use loads() and dumps()

facts = '{"hostname": "nxosv", "os": "7.3", "location": "San_Jose"}'


print facts
print type(facts)
# print facts['os']
# TypeError: string indices must be integers, not str
factsd = [Link](facts)
print [Link](factsd, indent=4)
JSON (Cont.)
APIs often return JSON strings

$ python json_test2.py
{"hostname": "nxosv", "os": "7.3", "location": "San_Jose"}
<type 'str'>
{
"hostname": "nxosv",
"os": "7.3",
"location": "San_Jose"
}
JSON (Cont.)
Getting familiar with JSON output while on a Nexus switch

nxosv# show hostname


[Link]
nxosv#

nxosv# show vlan brief

VLAN Name Status Ports


---- -------------------------------- --------- -------------------------------
1 default active Eth2/5, Eth2/6
100 web_vlan active

nxosv#
JSON (Cont.)
nxosv# show hostname | json
{
"hostname": "[Link]"
}
nxosv#
JSON (Cont.)
nxosv# show vlan brief | json
{
"TABLE_vlanbriefxbrief": {
"ROW_vlanbriefxbrief": [
{
"vlanshowbr-vlanid": 16777216,
"vlanshowbr-vlanid-utf": 1,
"vlanshowbr-vlanname": "default",
"vlanshowbr-vlanstate": "active",
},
{
"vlanshowbr-vlanid": 1677721600,
"vlanshowbr-vlanid-utf": 100,
"vlanshowbr-vlanname": "web_vlan",
}

* Output removed for brevity.


JSON (Cont.)
Same object in Python:

print response['TABLE_vlanbriefxbrief']['ROW_vlanbriefxbrief'][1]['vlanshowbr-
vlanname']

web_vlan
JSON (Cont.)
JSON schema definition – describes your JSON data

[
{
"id": 1,
"name": "DEFAULT_VLAN",
"state": "up",
},
{
"id": 10,
"name": “web_vlan",
"state": "down",
}
]
JSON (Cont.)
{
"$schema": "[Link]
"title": "VLAN Table",
"type": "array",
"items": {
"title": “VLAN",
"type": "object",
"properties": {
"id": {
"description": "The unique VLAN identifier",
"type": "number“,
"minimum": 1,
"maximum": 4096,
JSON (Cont.)
},
"name": {
"description": "VLAN NAME",
"type": "string"
},
"state": {
"description": "The unique VLAN admin state",
"type": "string",
"enum": ["up", "down"],
},
},
"required": ["id"]
}
}
Discovery 7: Working with JSON
Objects in Python
Topology
XML
• Extensible Markup Language <?xml version="1.0"?>
<ins_api>
• Language independent <type>cli_show</type>
<version>1.2</version>
• Way of formatting and transmitting data
<sid>eoc</sid>
that is both human and machine <outputs>
readable <output>
<body>
• Not as human readable as JSON
<hostname>[Link]</hostname>
</body>
<input>show hostname</input>
<msg>Success</msg>
<code>200</code>
</output>
</outputs>
</ins_api>
XML (Cont.)
<?xml version="1.0"?>
XML vs. HTML <ins_api>
• XML was designed to describe data <type>cli_show</type>
• HTML was designed to display data <version>1.2</version>
<sid>eoc</sid>
• XML tags are created by the author <outputs>
<output>
• HTML tags are predefined in the HTML
<body>
standard
• They are complementary <hostname>[Link]</hostname>
</body>
<input>show hostname</input>
<msg>Success</msg>
<code>200</code>
</output>
</outputs>
</ins_api>
XML (Cont.)
XML Namespaces
• Provide a means to mitigate element name conflicts
• You can also have a default namespace using xmlns=url eliminating need to have
attribute in each tag
XML (Cont.)
<interface>
<name>Ethernet1</name>
<description>Connects to EDGE</description>
<admin_state>up</admin_state>
</interface>

<interface>
<name>Ethernet1</name>
<oper>down</oper>
</interface>

<cfg:interface xmlns:cfg="[Link]
<cfg:name>Ethernet1</cfg:name>
<cfg:description>Connects to EDGE</cfg:description>
<cfg:admin_state>up</cfg:admin_state>
</cfg:interface>
XML (Cont.)
• Non-native Python object
• lxml—one module that simplifies working with XML
#!/usr/bin/env python

from lxml import etree

if __name__ == "__main__":

xml_as_string = '''
<ins_api>
<type>cli_show</type>
<version>1.2</version>
XML (Cont.)
<sid>eoc</sid>
<outputs>
<output>
<body>
<hostname>[Link]</hostname>
</body>
<input>show hostname</input>
<msg>Success</msg>
<code>200</code>
</output>
</outputs>
</ins_api>
'''
xml_obj = [Link](xml_as_string)
print xml_obj
XML (Cont.)
• Type is an Element object
• Takes name as first (root) object

$ python xml_scripts.py
<Element ins_api at 0x7f08d9f46170>
XML (Cont.)
• find() method finds the first matching sub-element, by tag name or path.
• Note: [Link]() not shown

xml_obj = [Link](xml_as_string)
print xml_obj
data = xml_obj.find('.//hostname')
print [Link]

$ python xml_scripts.py
<Element ins_api at 0x7f6d2e271170>
[Link]
XML (Cont.)
Getting familiar with XML output while on a Nexus switch

nxosv# show vlan | xml?


xml Output in xml format (according to .xsd definitions)
<output omitted for brevity>
XML (Cont.)
• XML schema definition (XSD)
• Describes XML documents
<vlan>
<name>web_vlan</name>
<vlan_id>100</vlan_id>
<state>shutdown</state>
</vlan>
XML (Cont.)
• XML schema definition (XSD)
• Describes XML documents
<xs:sequence>
<xs:element name=“vlan_id" minOccurs="1" type="nxos:base_unsignedInt_key">
<xs:annotation>
<xs:documentation>VLAN brief VLAN ID</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="state" minOccurs="1">
<xs:complexType>
<xs:annotation>
<xs:documentation>VLAN state</xs:documentation>
XML (Cont.)
• XML schema definition (XSD)
• Describes XML documents
</xs:annotation>
<xs:simpleContent>
<xs:restriction base="nxos:base_string">
<xs:enumeration value="shutdown">
<xs:annotation>
<xs:documentation>VLAN admin state</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="noshutdown">
# shortened for brevity
Discovery 8: Using XML in Python
Topology
Data Models
Data Models (Cont.)
What are data models?
• Data models describe a constrained set of data in the form of a schema language
• Use well-defined parameters to standardize the representation of data from a
network device so the output among various platforms is the same
• Not used to actually send information to devices and instead rely on protocols such
as NETCONF and RESTCONF.
• Device configuration can be validated against a data model in order to check if the
changes are a valid for the device before committing the changes
Data Models (Cont.)

*With REST, there may not have even been a XSD/JSD based model. **NETCONF supports XML only
YANG
• Modeling language defined in RFC 6020
• Initially built for NETCONF
• Now also used by RESTCONF
• Models configuration and operational state data
• Provides syntax and semantics
• Utilizes reusable data structures
YANG (Cont.)
Open & Native YANG Models
Model-Driven Programmability
Data Models
• Other platforms have
their own data models:
– Nexus 9000/3000
with NX-API REST
– Application Centric
Infrastructure
Model-Driven Programmability (Cont.)
• Model-based, structured, computer friendly
• Choice of transport, protocol, and encoding
• Model-driven APIs for abstraction and simplification
• Wide standard support while leveraging open source
• Deploy services faster and more simply
• Simplify application development
• Models manage abstractions of the underlying network device data structures
(configurations, state data, and so on).
Model-Driven Programmability (Cont.)
The model is king and the source of truth

module: openconfig-bgp
+--rw bgp!
+--rw global
| +--rw config
| | +--rw as
| | +--rw router-id?
| +--ro state
| | +--ro as
| | +--ro router-id?
| | +--ro total-paths?
| | +--ro total-prefixes?
...
Model-Driven Programmability Stack
REST
• If you understand how to work with a web browser, you understand REST.
• Same HTTP Request Methods and Response Codes are used.
REST (Cont.)
REST (Cont.)
Create, Retrieve, Update, and Delete (CRUD)
REST (Cont.)
HTTP Verbs
REST (Cont.)
{
Examples "l1PhysIf" : {
• GET [Link] "attributes" : {
– Retrieve Network Objects from an ASA "id" : "eth2/5",
"mtu" : "default"
• POST [Link] "speed" : "auto"
– Configure Interface Eth2/5 "adminSt": "down"
}
}
}
REST (Cont.)
Common HTTP Response Codes
Success (2xx) Description

200 Request Succeeded

201 The request has been fulfilled; new resource created

202

204 The server fulfilled request but does not return a body

Server Error (5xx) Description

500 Internal Server Error

501 Not implemented


REST (Cont.)
Common HTTP Response Codes
Client Error (4xx) Description

400 Bad Request. Malformed Syntax

401 Unauthorized

403 Server understood request, but refuses to fulfill it

404 Resource not found given URI


REST (Cont.)
TOOLS
• cURL
– Linux command line tool
• Postman
– Chrome application
• requests
– Python Module
REST (Cont.)
#!/usr/bin/env python

import requests
import json
from [Link] import HTTPBasicAuth

if __name__ == "__main__":

auth = HTTPBasicAuth('cisco', 'cisco')


headers = { 'Accept': 'application/json'}
url = '[Link]
response = [Link](url, verify=False, headers=headers, auth=auth)
print response.status_code
print [Link]
NETCONF
NETCONF is an IETF network management protocol designed specifically for
configuration management
• Makes a distinction between configuration and state data
• Utilizes multiple configuration data stores (candidate, running, startup)
• Configuration change transactions
• Provides client-side configuration validation
• Uses filtering mechanisms for selective data retrieval
• Uses a client-server model and SSH as transport protocol
NETCONF (Cont.)
Protocol Stack

Layer Example

Protocols SSHv2, SOAP, TLS

Messages <rpc>,<rpc-reply>

Operations* <get-config>, <get>, <copy-config>, <commit>, <validate>, <lock>, <unlock>, <edit-


config>, <delete-config>
Content XML Documents (XSD, YANG, etc.)

* Varies per hardware platform and OS


NETCONF (Cont.)
Data Stores
• Target of Operations
• May hold an entire copy of the configuration
• Not all data stores are supported by all devices
• Running config is the only required data store
• Not all device’s are writable
• May have to copy from a writable one
NETCONF (Cont.)
NETCONF over SSH
NETCONF (Cont.)
NETCONF (Cont.)
NETCONF (Cont.)
NETCONF (Cont.)
NETCONF (Cont.)
Inside the Protocol Stack

Layer

Content

Operations

Messages

Transport Protocol
NETCONF (Cont.)
XML Encoding
• Messages are RPCs
• Operation is copy-config

<?xml version="1.0"?>
<rpc message-id="1" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<copy-config>
<source>
<url>[Link]
</source>
<target>
<candidate/>
</target>
</copy-config>
</rpc>
]]>]]>
NETCONF (Cont.)
• Operation is get
• Content is everything else inside the operation

<?xml version="1.0"?>
<rpc message-id="101" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<get>
<filter type="subtree">
<native xmlns="[Link]
<interface>
<GigabitEthernet>
<name>1</name>
</GigabitEthernet>
</interface>
</native>
</filter>
... output truncated....
NETCONF (Cont.)
Utilities & Tools
• On box NETCONF sub system
$ ssh -p 830 cisco@csr1kv -s netconf
NETCONF (Cont.)
ncclient—Python NETCONF client

from ncclient import manager


with [Link](host='csr1kv', port=830, username='cisco', password='cisco',
hostkey_verify=False, device_params={'name': 'csr'},
allow_agent=False, look_for_keys=False) as device:

get_filter = """
<native xmlns="[Link]
<interface>
</interface>
</native>
"""
nc_get_reply = [Link](('subtree', get_filter))
print [Link](nc_get_reply.data_ele, pretty_print=True)
Discovery 9: NETCONF Capabilities
Exchange
Topology
RESTCONF
• Functional sub-set of NETCONF
• Exposes YANG models via a REST API (URL)
• Uses HTTP(S) as transport
• Uses XML or JSON for encoding
• Developed to use HTTP tools and programming
libraries
• Uses common HTTP verbs in REST APIs
RESTCONF (Cont.)
Protocol Operations

Operation Description

GET Retrieve data from a resource (config/operational)

POST Create a configuration data resource

PUT Create or replace a configuration data resource

PATCH Merge configuration data with target resource

DELETE Delete a configuration data resource


RESTCONF (Cont.)
RESTCONF and NETCONF

Operation Description

GET <get-config>, <get>

POST <edit-config> (operation="create")

PUT <edit-config> (operation="create/replace")

PATCH <edit-config> (operation="merge")

DELETE <edit-config> (operation="delete")


RESTCONF (Cont.)
Examples

• GET [Link]
– Retrieve full running configuration as an object
• GET [Link]
– Retrieve interface specific attributes
• GET [Link]
– Retrieve interface specific attributes for GigabitEthernet1
RESTCONF (Cont.)
RESTCONF Utilities & Tools

Same tools that are used for native REST interfaces are used for
RESTCONF
• Python requests module
• Postman
• Firefox RESTClient

There are no API docs so YANG tools will be used to generate URL and request body
gRPC
• Google RPC provides a general (open
source) RPC framework
• Interface definition in Cisco IOS XR
specifies device operations
• Provides simple client development
• High performance
• Functional subset of NETCONF
• Runs over HTTPS
gRPC (Cont.)
Protocol Operations

Operation Description

GetConfig Retrieve configuration data

MergeConfig Merge configuration data

DeleteConfig Delete configuration data

ReplaceConfig Replace configuration data

GetOper Retrieve operational data

CliConfig Merge configuration data in CLI format

ShowCmdTextOutput Retrieves CLI show-command output data


Cisco ASA REST API
APIs and Automation Protocols
Cisco ASA REST API Overview
• Cisco ASA API is a REST-based API
• REST Agent or Client, is an additional package and separate install
• Data is encoded in JSON
• Standard HTTP error and status codes are used
REST API Agent Pre-requisites
• Running ASA running 9.3(2) or 9.4(1) and above
• Enable https
– command: “http server enable”
• Download REST API agent using CCO credentials
– upload to device using standard methods (tftp, ftp, http)
• Install agent on ASA
– command: “rest-api image <image-name>”
• Enable agent service
– command: “rest-api agent”

The URI ‘/api' is now redirected to rest agent instead of the normal http
daemon
User Credentials
• Privilege Level 3
– Only /api/monitoring GET
requests
• Privilege Level 5
– All GET requests
• Privilege Level 15
– PUT/POST/DELETE
operations
Cisco ASA REST API Documentation and Console
• Located at [Link]
• You can navigate via left pane to view
all sections
• The browser defines what methods are
usable per URI
• Examples are provided for each URI
• Native API Console, similar to Postman
Cisco ASA REST API Documentation and Console (Cont.)
Cisco ASA REST API Documentation Examples
Cisco ASA REST API Console
Request Methods
• GET—Retrieves data from the specified object.
• PUT—Adds the supplied information
• POST—Creates the object with the supplied information.
• DELETE—Deletes the specified object.
• PATCH—Applies partial modifications to the specified object
Authentication
• Basic Authentication
– Username and password
– cisco:cisco
– Converts to base64 encoded string
• X-Auth-Token
– Retrieve token using basic
authentication or API Console methods
Cisco ASA REST API Examples—Postman

show version
Cisco ASA REST API Examples—Postman (Cont.)
Create Network Object
Cisco ASA REST API Examples—Postman (Cont.)
Cisco ASA REST API Examples—Python
import requests
import json
from [Link] import HTTPBasicAuth
[Link].urllib3.disable_warnings()

url = '[Link]
auth = HTTPBasicAuth('cisco', 'cisco')

response = [Link]( url, verify=False, auth=auth)

if response.status_code == 200:
print 'Status Code: ' + str(response.status_code)
parse = [Link]([Link])
print [Link](parse, indent=4)
else:
print 'ERROR Code: ' + str(response.status_code)
Cisco ASA REST API Examples—Python (Cont.)
cisco@cisco:~$ python show_version.py
Status Code: 200
{
"kind": "object#Version",
"currentTimeinSeconds": 1468510065,
"asaVersion": "9.5(2)207",
"totalFlashinMB": 8192,
"deviceType": "ASAv",
"upTimeinSeconds": 802800,
"firewallMode": "Router",
"selfLink": "/api/monitoring/device/version"
}
cisco@cisco:~$
Example Push Config
<import omitted >
url = '[Link]
auth = HTTPBasicAuth('cisco', 'cisco')

payload = {
"host": {
"kind": "IPv4Address",
"value": "[Link]"
},
"kind": "object#NetworkObj",
"name": "web_server08",
"objectId": "web_server08"
}
Example Push Config (Cont.)
headers = { 'content-type': "application/json" }
response = [Link]( url, data=[Link](payload), headers=headers,
verify=False, auth=auth)
if response.status_code == 201:
print 'Status Code: ' + str(response.status_code)
print [Link]
else:
print 'ERROR Code: ' + str(response.status_code)
print [Link]
cisco@cisco:~$ python push_object.py
Status Code: 201
{'Content-length': '0', 'Accept-ranges': 'bytes', 'Vary': 'Accept-Charset, Accept-
Encoding, Accept-Language, Accept', 'Server': 'CiscoASARestApiServer', 'Location':
'[Link] 'Date': 'Thu, 14
Jul 2016 18:08:41 GMT'}
cisco@cisco:~$
Special APIs
CLI Command Executor
• Generic CLI Command
Executor API
– Returns raw text
• Bulk CLI
– Returns list of JSON objects
REST API Debugging
• ASA provides a command to debug the API
• debug rest-api agent
• Syslog messages also generated for given ASA REST API errors

Error Message %ASA-3-342004: Failed to automatically restart the REST API Agent
after 5 unsuccessful attempts. Use the 'no rest-api agent' and 'rest-api agent'
commands to manually restart the [Link]

The REST API Agent has failed to start after many attempts
NX-OS Programmability
APIs and Automation Protocols
Nexus Programmability Overview
Nexus Programmability Features
NX-API CLI—Part 1
What is NX-API CLI?
• REST-like API that enables programmatic
access to Nexus devices
• Improves accessibility of the CLI by making
them available off box
• Supports show commands, configurations, and
Linux Bash
NX-API CLI—Part 1 (Cont.)
NX-API Transport
• Runs on HTTP/S
• CLI commands are encoded into the HTTP/S
POST body
• The request/response format is encoded with
JSON-RPC, JSON, or XML
• NGINX HTTP backend webserver to listen for
HTTP requests
NX-API CLI—Part 1 (Cont.)
nxosv# conf t
Enabling NX-API nxosv(config)# feature nxapi
• Enable the feature via the CLI
• Identify the port being used
• Enable the sandbox nxosv(config)# nxapi https port 8443

nxosv(config)# nxapi sandbox


nxosv(config)#
NX-API CLI—Part 1 (Cont.)
NX-API Sandbox
• NX-API is available on the switch itself
and accessed via web browser
• There are helpful buttons available with
commonly used built-in scripts
• Supported on all Nexus platforms
NX-API CLI—Part 1 (Cont.)
NX-API CLI—Part 1 (Cont.)
NX-API CLI—Part 1 (Cont.)
NX-API CLI—Part 1 (Cont.)
Discovery 10: NX-API Developer
Sandbox
Topology
NX-API CLI—Part 2
Python Example

#!/usr/bin/env python

import requests
import json
from [Link] import HTTPBasicAuth

if __name__ == "__main__":

auth = HTTPBasicAuth('cisco', 'cisco')


headers = {
'Content-Type': 'application/json'
}
NX-API CLI—Part 2 (Cont.)
payload = {
"ins_api": {
"version": "1.0",
"type": "cli_show",
"chunk": "0",
"sid": "1",
"input": "show version",
"output_format": "json"
}
}
NX-API CLI—Part 2 (Cont.)
url = '[Link]

response = [Link](url, data=[Link](payload),


headers=headers, auth=auth)

print 'Status Code: ' + str(response.status_code)


rx_object = [Link]([Link])
print [Link](rx_object, indent=4)
NETCONF
NETCONF* on the Nexus platform is based off XML Schema Definitions data
models and maps to CLI commands.
Layer Example

Transport Protocol SSHv2

RPC <rpc>,<rpc-reply>

Operations <get-config>, <copy-config>, <commit>, <validate>, <lock>, <unlock>, <edit-


config>**, <exec-command>***
Content XML Representation using XML Schema Definition (XSD) of show command or
feature to be configured.

* Only supported on Nexus 7K/5K ** Supports actions including rollback on error, stop on error,
continue on error, default operations, and candidate config *** Cisco-only
NETCONF (Cont.)
Requirements
• The client machine must have SSHv2 installed
• The client machine must have an XML management tool that supports NETCONF
over SSH
• Ensure that the SSH is enabled on the Nexus switch
– feature ssh
• No licensing is required
• NETCONF uses port 22 on Nexus

$ ssh cisco@nxosv -s {netconf | xmlagent}


NETCONF (Cont.)
Utilities and Tools
• xmlagent—SSH service acting as the XML/NETCONF server on the Nexus
platform
• xmlin—interactive utility to obtain XML strings of a particular show command or
configuration object
• show command | xmlin—CLI option to obtain XML equivalent of a given show
command
• show command | xmlout - CLI option to obtain XML equivalent of a given show
command’s output
• ncclient—Open source Python NETCONF client
xmlagent
• Using the xmlagent to perform a capabilities exchange
• Also accessed on the CLI by using the xmlagent command
cisco@cisco:~$ ssh cisco@nxosv -s netconf
User Access Verification
Password:
<?xml version="1.0" encoding="ISO-8859-1"?>
<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<capabilities>
<capability>urn:ietf:params:xml:ns:netconf:base:1.0</capability>
<capability>urn:ietf:params:netconf:base:1.0</capability>
<capability>urn:ietf:params:netconf:capability:validate:1.0</capability>
<capability>urn:ietf:params:netconf:capability:writable-
running:1.0</capability>
.... output truncated for brevity....
xmlagent (Cont.)
You (NETCONF client) must respond with supported capabilities

cisco@cisco:~$ ssh cisco@nxosv -s netconf


User Access Verification
Password:
<?xml version="1.0" encoding="ISO-8859-1"?>
<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<--omitted – reference previous slide -->
</hello>
]]>]]><?xml version="1.0"?>
<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<capabilities>
<capability>urn:ietf:params:xml:ns:netconf:base:1.0</capability>
<capability>urn:ietf:params:netconf:capability:rollback-on-
error:1.0</capability>
... output truncated for brevity...
xmlagent (Cont.)
Sending XML documents using xmlagent
• Show hostname—Request
<?xml version="1.0" encoding="ISO-8859-1"?>
<nf:rpc xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns="[Link] message-id="1">
<nf:get>
<nf:filter type="subtree">
<show>
<hostname/>
</show>
</nf:filter>
</nf:get>
</nf:rpc>
]]>]]>
xmlagent (Cont.)
Sending XML documents using xmlagent (continued)
• Show hostname—Response
<?xml version="1.0" encoding="ISO-8859-1"?>
<nf:rpc-reply xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns="[Link] message-id="1">
<nf:data>
<show>
<hostname>
<__readonly__>
<hostname>nxosv</hostname>
</__readonly__>
</hostname>
</show>
</nf:data>
</nf:rpc-reply>
]]>]]>
xmlin
Generate XML documents using the xmlin interactive shell
• Show hostname
nxosv# xmlin
<--output omitted -->
nxosv(xmlin)# show hostname
<?xml version="1.0"?>
<nf:rpc xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns="[Link] message-id="1">
<nf:get>
<nf:filter type="subtree">
<show>
<hostname/>
</show>
</nf:filter>
</nf:get>
</nf:rpc>
]]>]]>
xmlin (Cont.)
nxosv(xmlin)# config t
Enter configuration commands, one per line. End with CNTL/Z.
nxosv(config)(xmlin)# vlan 20
% Success
% Success
nxosv(config-vlan)(xmlin)# name web_vlan
% Success
% Success
nxosv(config-vlan)(xmlin)# end
<?xml version="1.0"?>
<nf:rpc xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns="[Link]
xmlns:m="[Link]
xmlns:m1="[Link] message-id="1">
<nf:edit-config>
<nf:target>
<nf:running/>
</nf:target>
## output continues on next slide ##
xmlin (Cont.)
<nf:config>
<m:configure>
<m:terminal>
<vlan>
<__XML__PARAM__vlan-id-create-delete>
<__XML__value>20</__XML__value>
<m1:name>
<m1:__XML__PARAM__vlan-name>
<m1:__XML__value>web_vlan</m1:__XML__value>
</m1:__XML__PARAM__vlan-name>
</m1:name>
</__XML__PARAM__vlan-id-create-delete>
</vlan>
</m:terminal>
</m:configure>
</nf:config>
</nf:edit-config>
</nf:rpc>
.... output truncated for brevity ...
xmlin (Cont.)
VLAN 200 is NOT configured when using rollback on error

<-- removed for brevity -->


<nf:edit-config>
<nf:target>
<nf:running/>
</nf:target>
<nf:error-option>rollback-on-error</nf:error-option>
<nf:config>
<m:configure>
<m:terminal>
<vlan>
### output continues on the next slide ###
xmlin (Cont.)
VLAN 200 is NOT configured when using rollback on error
• Spaces are not supported in VLAN names
### continues from previous slide ###
<vlan>
<__XML__PARAM__vlan-id-create-delete>
<__XML__value>200</__XML__value>
<m1:name>
<m1:__XML__PARAM__vlan-name>
<m1:__XML__value>web vlan</m1:__XML__value>
</m1:__XML__PARAM__vlan-name>
</m1:name>
</__XML__PARAM__vlan-id-create-delete>
</vlan>
<-- removed for brevity -->
xmlin Pipe Option
Generate XML documents for specific show commands

nxosv# show hostname | xmlin


<?xml version="1.0"?>
<nf:rpc xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns="[Link] message-id="1">
<nf:get>
<nf:filter type="subtree">
<show>
<hostname/>
</show>
</nf:filter>
</nf:get>
</nf:rpc>
]]>]]>
% Success
xmlin Pipe Option (Cont.)
Generate XML documents for specific show commands (Cont.)

nxosv# show hostname | xmlout


<?xml version="1.0" encoding="ISO-8859-1"?>
<nf:rpc-reply xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns="[Link]
<nf:data>
<show>
<hostname>
<__readonly__>
<hostname>nxosv</hostname>
</__readonly__>
</hostname>
</show>
</nf:data>
</nf:rpc-reply>
]]>]]>
NETCONF Python Scripts
Uses ncclient

nxosv# show hostname | xmlin


<?xml version="1.0"?>
<nf:rpc xmlns:nf="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns="[Link] message-id="1">
<nf:get>
<nf:filter type="subtree">
<show>
<hostname/>
</show>
</nf:filter>
</nf:get>
</nf:rpc>
]]>]]>
% Success
NETCONF Python Scripts (Cont.)
Get hostname script

device = [Link](host=host, port=port, username=user, password=pwd,


hostkey_verify=False, device_params={'name': 'nexus'},
allow_agent=False, look_for_keys=False)
get_filter = """
<show>
<hostname>
</hostname>
</show>
"""
nc_get_reply = [Link](('subtree', get_filter))
print nc_get_reply.xml
ns_map = {'mod': '[Link]
xml_rsp = nc_get_reply.data_ele.find('.//mod:hostname', ns_map)
value = xml_rsp.text
print value
NETCONF Python Scripts (Cont.)
NETCONF Python Scripts (Cont.)
Filters can be XML strings or XML objects

device = [Link](host=host, port=port, username=user, password=pwd,


hostkey_verify=False, device_params={'name': 'nexus'},
allow_agent=False, look_for_keys=False)
get_filter = """
<show>
<hostname>
</hostname>
</show>
"""
nc_get_reply = [Link](('subtree', get_filter))
print nc_get_reply.xml
ns_map = {'mod': '[Link]
xml_rsp = nc_get_reply.data_ele.find(
'.//mod:hostname', ns_map)
value = xml_rsp.text
NETCONF Python Scripts (Cont.)
Filters can be XML strings or XML objects

E = ElementMaker()
nc_filter = [Link](
[Link]()
)
print [Link](nc_filter) # view XML obj as string

nc_get_reply = [Link](('subtree', nc_filter))

Required imports:

from lxml import etree


from [Link] import ElementMaker
NETCONF Python Scripts (Cont.)
Filters can be XML strings or XML objects

device = [Link](host=host, port=port, username=user, password=pwd,


hostkey_verify=False, device_params={'name': 'nexus'},
allow_agent=False, look_for_keys=False)
get_filter = """
<show>
<hostname>
</hostname>
</show>
"""
nc_get_reply = [Link](('subtree', get_filter))
NETCONF Python Scripts (Cont.)
View show version XML output (cleaned up)

nxosv# show version | xmlout


<-- XML header and RPC REPLY omitted -->
<nf:data>
<show>
<version>
<__readonly__>
<header_str>NX-OSv is a demo version of the Nexus Operating
System</header_str>
<loader_ver_str>N/A</loader_ver_str>
<kickstart_ver_str>7.3(1)D1(1) [build 7.3(1)D1(0.10)]</kickstart_ver_str>
<sys_ver_str>7.3(1)D1(1) [build 7.3(1)D1(0.10)]</sys_ver_str>
<kick_file_name>bootflash:///titanium-d1-
[Link]</kick_file_name>
... output terminated for brevity ...
NETCONF Python Scripts (Cont.)
Get show version script and extract one value

def remove_namespaces(xml):
for elem in [Link]():
split_tag = [Link]('}')
if len(split_tag) > 1:
[Link] = split_tag[1]
return xml

nc_get_reply = [Link](('subtree', get_filter))


nc_get_reply_no_ns = remove_namespaces(nc_get_reply.data_ele)
xml_rsp = nc_get_reply_no_ns.find('.//kickstart_ver_str')
value = xml_rsp.text
print value
NETCONF Python Scripts (Cont.)
• NETCONF Nexus-only exec-command sends raw CLI commands vs. XML strings.
• Leverages exec_command method as compared to get, edit_config, etc.

with [Link](host=host, port=port, username=user, password=pwd,


hostkey_verify=False, device_params={'name': 'nexus'},
allow_agent=False, look_for_keys=False) as device:

commands = ['config t', 'interface Ethernet2/6', 'description Configured by


Python ncclient']
nc_config_reply = device.exec_command(commands)
NX-API REST
• NX-API REST is an evolved version NX-API CLI
• Complete REST interface that brings Model Driven Programmability to standalone
Nexus family switches
• Configuration and state information of the switch is stored in a hierarchical tree
structure known as the management information tree (MIT)
NX-API REST (Cont.)
• Object instances are referred to as managed objects (MOs)
• Managed Objects (MOs) are also of a certain type of Class
• Every managed object in the system can be identified by a unique distinguished
name (DN)
• URLs and URIs map directly to distinguished names identifying objects on the tree
• Data can be encoded in XML or JSON
NX-API REST (Cont.)
REST methods supported

Method Action Behavior

POST Create / Update Idempotent

GET Read Nullipotent

DELETE Delete Idempotent

Payloads can be XML or JSON


• Specified by file extension in URI
• Content-Type and Accept Header is ignored
Request Headers
• Authorization – User credentials
• Content-Type and Accept headers are ignored by Nexus switches
– Content-Type ("application/xml”) – The client payload is in xml format
– Accept ("application/xml”) – The server payload is in xml format

Ignored because payload is specific as file extension in URL


NX-API REST (Cont.)
http(s):// host:port /api /{mo|class} /{dn|classname} .{xml|jso ?[options]
n}
http or NX host & API Specify type DN or Object Class Specify Specify filters,
https port usage of API call based on API call encoding modifiers, join with
type for ampersand (&)
response

Examples (GET):
• [Link]
• [Link]
NX-API REST (Cont.)
Device Login and Authentication—Method: POST
• JSON

URL: [Link]

Body:

{
"aaaUser":{
"attributes":{
"name": "cisco",
"pwd": "cisco"
}
}
}
NX-API REST (Cont.)
Device Login and Authentication—Method: POST
• XML

URL: [Link]

Body:

<aaaUser name="admin" pwd="C1sco12345"/>


Examples—Postman
• DN-based query
• Retrieve interface attributes
and configuration of Eth2/5
• JSON Response
Examples—Postman (Cont.)
• DN-based API Call
• Shut down down interface
Eth2/2
• Attributes configured in JSON
Request
Examples—Postman (Cont.)
• Class-based query
• Retrieve information on all
Ethernet (physical) interfaces
Visore
• Built-in managed object
browser
• Navigate the object tree and
inspect the state of the objects
• http(s)://<nexus>/[Link]
Visore (Cont.)
• Query based on Class
• Returns all objects of a given
class, object type
• Displays URI and API response
Visore (Cont.)
• Query based on Distinguished
Name (DN)
• Returns attributes of specified
object
• Displays URI and API response
Visore (Cont.)
Python on Box
Nexus switches have a Python execution engine exposed that allow you to
access the interpreter or run scripts directly on the switch.

nxosv# python
Copyright (c) 2001-2012 Python Software Foundation; All Rights Reserved

nxosv# >>>
nxosv# >>>
Python on Box (Cont.)
Built-in Python module called cisco

nxosv# >>> import cisco


nxosv# >>> help(cisco)
## omitted for brevity ##
FUNCTIONS
cli(...)
execute a cli command

clid(...)
execute a cli command, return name/value pairs

clip(...)
execute a cli command, dont return it, just display it

set_vrf(...)
specify the vrf name for socket operations
Python on Box (Cont.)
CLI Command APIs
Function Example Description Output

cli() cli('show Returns the raw output of CLI 'nxosv \n'


hostname') commands, including
control/special characters
clip() clip('show Prints the output of the CLI nxosv
hostname') command directly to stdout
and returns nothing to Python
clid() clid('show Returns a dictionary of data = [Link]('show
hostname') attribute-names/values for hostname') print type(data) <type
CLI commands that support 'str'> data= [Link](data) print
JSON data['hostname'] nxosv
Python on Box (Cont.)
Configuration modes persistent through function calls*

nxosv# >>> from cisco import cli


nxosv# >>>
nxosv# >>> cli('config t ; interface Eth2/8 ; shutdown ')
''
nxosv(config-if)# >>>
nxosv(config-if)# >>> cli('no shutdown ')
''
nxosv(config-if)# >>>
nxosv(config-if)# >>> print cli('where')
conf; interface Ethernet2/8 ntc@nxosv%default
Python on Box (Cont.)
Executing standalone scripts and optionally execute with EEM or Scheduler

nxosv# source check_transit_interfaces.py

Scheduler

feature scheduler
scheduler job name enforcer
source enforce_config.py
scheduler schedule name enforcer
job name enforcer
time start now repeat 00:00:10
Python on Box (Cont.)
Executing standalone scripts and optionally execute with EEM or Scheduler

nxosv# source check_transit_interfaces.py

EEM

event manager applet trigger_this


event cli match "show version"
action 1 cli command "source [Link]"
action 2 syslog priority critical msg “CLOCK COMMAND EXECUTED:
action 3 event-default
Discovery 11: Using Python on the
Nexus Switch
Topology
Cisco IOS XE APIs
APIs and Automation Protocols
Cisco IOS XE APIs Overview
• Model Driven APIs
• Exposes NETCONF & RESTCONF Insterfaces
• NETCONF/YANG
• RESTCONF/YANG
• Data is exchanged in XML and JSON and is fully defined (in advance) using YANG
models
Cisco IOS XE APIs Overview (Cont.)
Accept NETCONF and RESTCONF requests and communicates directly to
configuration datastore(s).
IOS XE RESTCONF API
• REST-based API
• HTTP(S) Transport
• Uses YANG data models
• JSON/XML Encoding
• Content-Type & Accept Headers:
– application/[Link]+json
– application/[Link]+xml
• Currently must exit configuration mode after making a change for it to be readable
via RESTCONF
IOS XE RESTCONF API (Cont.)
Enabling RESTCONF
• Enable RESTCONF
• User with Privilege 15
• Enable http(s) Access

restconf
!
username <username> privilege 15 password <password>
!
ip http server
ip http secure-server
!
Request Methods
• GET—Retrieves data from the specified object
• PUT—Replaces full configuration object of tree specified
• POST—Creates the object with the supplied information
• DELETE—Deletes the specified object
• PATCH—Applies partial modifications to the specified object

PATCH is the recommended method as you get started with the API
RESTCONF Examples
Retrieve Entire Running Configuration Modeled as JSON

GET [Link]

GET [Link]

Great starting point to explore data structure

Use Query “?deep” to add additional leaf objects including IP Address


information (and much more)
RESTCONF Examples (Cont.)
RESTCONF Examples (Cont.)
Retrieve Interface Configurations

GET [Link]

GET [Link]

GET [Link]

GET [Link]

GET
[Link]
RESTCONF Examples (Cont.)
Retrieve Interface Configurations
RESTCONF Examples (Cont.)
Adding an Interface

POST [Link]

PATCH [Link]

PUT [Link]
RESTCONF Examples (Cont.)
Adding an Interface (Cont.)—Body

{
"ned:Loopback": {
"name": 100,
"ip": {
"address": {
"primary": {
"address": "[Link]",
"mask": "[Link]"
}
}
}
}
}
RESTCONF Examples (Cont.)
Updating an Interface

interface Loopback100 (existing configuration)


ip address [Link] [Link] secondary
ip address [Link] [Link]
RESTCONF Examples (Cont.)
interface Loopback100 (existing configuration)
ip address [Link] [Link] secondary
ip address [Link] [Link]

{
"ned:Loopback": {
"name": 100,
"ip": {
"address": {
"primary": {
"address": "[Link]",
"mask": "[Link]"
}
}
}
}
}
RESTCONF Examples (Cont.)
Updating an Interface (same Body as previously used)

POST [Link] Response: 409;


Error: Object Already Exists; No change in config

PATCH [Link] Response


204; No change in config

PUT [Link]
Response 204;
RESTCONF Examples (Cont.)
Result from using a PUT

interface Loopback100
ip address [Link] [Link]
RESTCONF Examples (Cont.)
Update Static Routes

csr1kv# show run | inc route (existing)


ip route [Link] [Link] [Link]

PATCH [Link]
RESTCONF Examples (Cont.)
{
"ned:route": {
"ip-route-interface-forwarding-list": [
{
"prefix": "[Link]",
"mask": "[Link]",
"fwd-list": [
{
"fwd": "[Link]"
}
]
### output continues on next slide ###
RESTCONF Examples (Cont.)
### continuation from previous slide ###
},
{
"prefix": "[Link]",
"mask": "[Link]",
"fwd-list": [
{
"fwd": "[Link]"
}
]
}
]
}
}
RESTCONF Examples (Cont.)
csr1kv# show run | inc route (final)
ip route [Link] [Link] [Link]
ip route [Link] [Link] [Link]
ip route [Link] [Link] [Link]
RESTCONF Examples (Cont.)
csr1kv#show run | inc route (new existing)
ip route [Link] [Link] [Link]
ip route [Link] [Link] [Link]
ip route [Link] [Link] [Link]

PUT [Link]
RESTCONF Examples (Cont.)
csr1kv# show run | inc route (final)
ip route [Link] [Link] [Link]

Be cautious with the use of PUTs


RESTCONF Examples (Cont.)
{
"ned:route": {
"ip-route-interface-forwarding-list": [
{
"prefix": "[Link]",
"mask": "[Link]",
"fwd-list": [
{
"fwd": "[Link]"
}
]
}
]
}
}
RESTCONF Examples (Cont.)
Remove a Route

DELETE [Link]
forwarding-list/[Link],[Link]

No Body Required.
RESTCONF Examples (Cont.)
Get Routes (Python)

#!/usr/bin/env python

import requests
import json
from [Link] import HTTPBasicAuth
[Link].urllib3.disable_warnings()

if __name__ == "__main__":

auth = HTTPBasicAuth('cisco', 'cisco')


headers = { 'Accept': 'application/[Link]+json'}
url = '[Link]
response = [Link](url, verify=False, headers=headers, auth=auth)
print [Link]([Link]([Link]), indent=4)
RESTCONF Examples (Cont.)
Get Routes (Python)—Output
{
"ned:route": {
"ip-route-interface-forwarding-list": [
{
"fwd-list": [
{
"fwd": "[Link]"
}
],

### output continues on next slide ###


RESTCONF Examples (Cont.)
### continuation from previous slide ###

"prefix": "[Link]",
"mask": "[Link]"
},
{
"fwd-list": [
{
"fwd": "[Link]"
}
],
"prefix": "[Link]",
"mask": "[Link]"
}
],
"static": {}
}
}
IOS XE NETCONF API
NETCONF* on the IOS XE platform is based off XML representation of YANG
models.
Layer Example

Transport SSHv2
Protocol
RPC <rpc>,<rpc-reply>

Operations <get-config>, <get>, <copy-config>, <commit>, <validate>, <lock>, <unlock>, <edit-


config>, <delete-config>
Content XML Representation of YANG Models

** Supports operations including rollback on error, stop on error, continue on error, default operations,
merge (default), replace, create, delete, remove. May vary per hardware platform.
IOS XE NETCONF API (Cont.)
Enabling NETCONF
• Enable NETCONF
• User with Privilege 15
• Optionally enable operational data

netconf-yang
!
username <username> privilege 15 password <password>
!
NETCONF
Requirements
• The client machine must have SSHv2 installed
• The client machine must have an XML management tool that supports NETCONF
over SSH
• Ensure that the SSH is enabled on the router
– Ports 830

$ ssh –p 830 cisco@csr1kv


NETCONF (Cont.)
Utilities & Tools

• NETCONF Server—allows you to test XML documents natively on the router


• ncclient—Open source Python NETCONF client
NETCONF Server
Perform a capabilities exchange

cisco@cisco:~$ ssh –p 830 cisco@csr1kv


User Access Verification
Password:
<?xml version="1.0" encoding="UTF-8"?>
<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<capabilities>
<capability>urn:ietf:params:netconf:base:1.0</capability>
<capability>urn:ietf:params:netconf:base:1.1</capability>
<capability>urn:ietf:params:netconf:capability:writable-
running:1.0</capability>
<capability>urn:ietf:params:netconf:capability:xpath:1.0</capability>
### output continues on next slide ###
NETCONF Server (Cont.)
<capability>urn:ietf:params:netconf:capability:validate:1.0</capability>
<capability>urn:ietf:params:netconf:capability:validate:1.1</capability>
<capability>urn:ietf:params:netconf:capability:rollback-on-
error:1.0</capability>
<capability>[Link]
<capability>[Link]
<200+ more omitted for brevity>
</capabilities>
<session-id>53296</session-id>
</hello>]]>]]>
NETCONF Server (Cont.)
You (NETCONF client) must respond with supported capabilities

cisco@cisco:~$ ssh cisco@nxosv -s netconf


User Access Verification
Password:
<?xml version="1.0" encoding="ISO-8859-1"?>
<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<--omitted – reference previous slide -->
</hello>
]]>]]><?xml version="1.0"?>
<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<capabilities>
<capability>urn:ietf:params:netconf:base:1.0</capability>
</capabilities>
</hello>]]>]]>
NETCONF Server (Cont.)
Sending XML documents direct to NETCONF server (request)
<?xml version="1.0"?>
<nc:rpc message-id="101" xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">
<nc:get>
<nc:filter type="subtree">
<native xmlns="[Link]
<interface>
<GigabitEthernet>
<name>1</name>
</GigabitEthernet>
</interface>
</native>
</nc:filter>
</nc:get>
</nc:rpc>
]]>]]>
NETCONF Server (Cont.)
Sending XML documents direct to NETCONF server (response)

<?xml version="1.0" encoding="UTF-8"?>


<rpc-reply message-id="101" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">
<data>
<native xmlns="[Link]
<interface>
<GigabitEthernet>
<name>1</name>
<negotiation>
<auto>true</auto>
</negotiation>
.... output truncated for brevity ...
NETCONF Python Scripts
#!/usr/bin/env python

from lxml import etree


from ncclient import manager

if __name__ == "__main__":

with [Link](host='csr1kv', port=830, username='cisco',


password='cisco',
hostkey_verify=False, device_params={'name': 'csr'},
allow_agent=False, look_for_keys=False) as device:

### output continues on next slide ###


NETCONF Python Scripts (Cont.)
### continuation from previous slide ###

get_filter = """
<native xmlns="[Link]
<interface>
<GigabitEthernet>
<name>1</name>
</GigabitEthernet>
</interface>
</native>
"""

nc_get_reply = [Link](('subtree', get_filter))


print [Link](nc_get_reply.data_ele, pretty_print=True)
NETCONF Python Scripts (Cont.)
<data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"
xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">
<native xmlns="[Link]
<interface>
<GigabitEthernet>
<name>1</name>
<negotiation>
<auto>true</auto>
</negotiation>

### output continues on next slide


NETCONF Python Scripts (Cont.)
### continuation from previous slide ###
<ip>
<address>
<primary>
<address>[Link]</address>
<mask>[Link]</mask>
</primary>
</address>
</ip>
</GigabitEthernet>
</interface>
</native>
</data>
NETCONF Python Scripts (Cont.)
nc_filter = """
<config>
<native xmlns="[Link]
<interface>
<Loopback>
<name>101</name>
<ip>
<address>
<primary>
<address>[Link]</address>
<mask>[Link]</mask>
</primary
</address>

### output continues on next slide ###


NETCONF Python Scripts (Cont.)
### continuation from previous slide ###

</address>
</ip>
</Loopback>
</interface>
</native>
</config>
"""

nc_reply = device.edit_config(target='running', config=nc_filter)


print nc_reply
print type(nc_reply)
NETCONF Python Scripts (Cont.)
<?xml version="1.0" encoding="UTF-8"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-
id="urn:uuid:3280b17b-ba2a-45b5-a13f-0e211077e7c0"
xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">
<ok/>
</rpc-reply>
<class '[Link]'>
Cisco IOS XR APIs
APIs and Automation Protocols
Cisco IOS XR APIs Overview
High-Level Overview
IOS XR NETCONF APIs
NETCONF* on the IOS XR platform is based off XML representation of YANG
models
Layer Example

Transport Protocol SSHv2

RPC <rpc>,<rpc-reply>

Operations <get-config>, <get>, <copy-config>, <commit>, <validate>, <lock>, <unlock>, <edit-


config>, <delete-config>, <kill-session>, <close-session>
Content XML Representation of YANG Models

** Supports operations including rollback on error, stop on error, continue on error, default operations,
merge (default), replace, create, delete, remove. May vary per hardware platform.
IOS XR NETCONF APIs (Cont.)
!
Enabling NETCONF ssh server netconf port 830
• Configure port to use for NETCONF netconf-yang agent
• Enable NETCONF over SSH ssh
username <username> privilege 15
• User with Privilege 15 password <password>
!
• Optionally enable local TTY for access to
netconf agent tty
NETCONF sub system
NETCONF
Requirements
• The client machine must have SSHv2 installed
• The client machine must have an XML management tool that supports NETCONF
over SSH
• Ensure that an SSH is enabled on the router

$ ssh –p 830 cisco@xrv –s netconf


NETCONF (Cont.)
Utilities & Tools

• NETCONF Server—allows you to test XML documents natively on the router


• ncclient—Open source Python NETCONF client
NETCONF Server
Perform a capabilities exchange

cisco@cisco:~$ ssh –p 830 cisco@xrv –s netconf


User Access Verification
cisco@xrv's password:
<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<capabilities>
<capability>urn:ietf:params:netconf:base:1.1</capability>
<capability>urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring</capability>
<capability>urn:ietf:params:netconf:capability:candidate:1.0</capability>
<capability>urn:ietf:params:netconf:capability:rollback-on-
error:1.0</capability>

### output continues on next slide ###


NETCONF Server (Cont.)
### continuation from previous slide ###

<capability>urn:ietf:params:netconf:capability:validate:1.1</capability>
<capability>urn:ietf:params:netconf:capability:confirmed-commit:1.1</capability>
<capability>[Link]
cdp-cfg&amp;revision=2015-01-07</capability>
<capability>[Link]
05</capability>
<200+ more omitted for brevity>
</capabilities>
<session-id>2453920142</session-id>
</hello>]]>]]>
NETCONF Python Scripts
#!/usr/bin/env python

from lxml import etree


from ncclient import manager

if __name__ == "__main__":

with [Link](host='xrv', port=830, username='cisco', password='cisco',


hostkey_verify=False, device_params={'name': 'iosxr'},
allow_agent=False, look_for_keys=False) as device:

### output continues on next slide ###


NETCONF Python Scripts (Cont.)
### continuation from previous slide ###

nc_filter = """
<interface-configurations xmlns="[Link]
XR-ifmgr-cfg">
<interface-configuration>
<interface-name>MgmtEth0/0/CPU0/0</interface-name>
</interface-configuration>
</interface-configurations>
"""

nc_get_reply = [Link](('subtree', nc_filter))


print nc_get_reply
NETCONF Python Scripts (Cont.)
# omitted for brevity

nc_filter = """
<config>
<interface-configurations xmlns="[Link]
ifmgr-cfg">
<interface-configuration>
<active>act</active>
<interface-name>Loopback100</interface-name>
<interface-virtual/>
</interface-configuration>
</interface-configurations>
</config>
"""
nc_reply = device.edit_config(target='candidate', config=nc_filter)
[Link]()
NETCONF Python Scripts (Cont.)
OpenConfig Data Model

nc_filter = """
<config>
<bgp xmlns="[Link]
<global>
<config>
<as>65512</as>
</config>
</global>
</bgp>
</config>
"""
nc_reply = device.edit_config(target='candidate', config=nc_filter)
[Link]()
Securing the Management Plane
APIs and Automation Protocols
Management Plane
Network Programmability Fundamentals
• The management plane consists of functions that achieve the management goals
of the network
• Includes management sessions that use SSH, SNMP NetFlow, and all APIs
including NETCONF, REST APIs, RESTCONF, gRPC, etc.
• When you consider the security of a network device, it is critical that the
management plane is protected
Management Plane (Cont.)

With more protocols and APIs being implemented on network devices, more
attention is required to ensure unused protocols and APIs are disabled
Access Control Lists
• Prevent unauthorized direct communication to network devices
• Permit connections among trusted hosts or networks that require communication
with network infrastructure devices according to established security policies
• Required communication typically consists of management- and control-plane
traffic such as external BGP, SSH, SNMP, and now specific APIs that may use
various ports and protocols
• After the required connections have been permitted, all other traffic to the
infrastructure is explicitly denied
• Applied in the ingress direction on all interfaces for which an IP address has been
configured
Access Control Lists (Cont.)
• ACLs should be applied on all ip access−list MGMT_IN
!−−− Permit required host connections to
interfaces with IP addresses limiting network management segment
management access permit tcp host <−mgmt−> any eq 22
• Use dedicated out of band management permit tcp host <−mgmt-> any eq 80
permit tcp host <−mgmt−> any eq 443
networks permit udp host <−mgmt−> any eq 161
interface mgmt0
ip access-group MGMT_IN in
Data Models
Designing and Implementing Cisco Network Programmability (NPDESI)
v1.0
YANG Data Modeling
Data Models
YANG Overview
• Data modeling language
defined in RFC 6020
• Analogous to XML schema and
SMI for SNMP
• Models configuration,
operational, and RPC data
• Provides semantics to better
define data
• Extensible and modular
– Constraints (i.e., “MUSTs”)
– Reusable structures
– Built-in and derived types
• Protocol independent
YANG Overview (Cont.)
YANG modules from standard
organizations such as the
IETF, open source, such as
Open Daylight, or vendor-
specific modules.
• [Link]
yang
• [Link]
ublic
YANG Module
YANG Module Contents
YANG Module Header
module acme-module {
namespace "[Link] URI
prefix acme;

import "ietf-yang-types" {
prefix yang;
}
include "acme-system";

organization "ACME Inc.";


contact joe@[Link];
description "Module describing the ACME products";
revision 2007-06-09 {
description "Initial revision.";
}
YANG Leaf Statement
• One value leaf host-name {
type string;
• No children mandatory true;
config true;
• One instance
description "Hostname for this system";
}
leaf cpu-temp {
type int32;
units degrees-celsius;
config false;
description "Current temperature in CPU";
}

NETCONF XML:
<host-name>[Link]</host-name>
YANG Leaf Statement (Cont.)
Data Constraints
• config
– Whether this leaf is a configurable value ("true"), or operational value ("false"). Inherited
from parent container if not specified. Default is "true."
• default
– Specifies default value for this leaf. Implies that leaf is optional.
• mandatory
– Whether the leaf is mandatory ("true"), or optional ("false").
• must
– Xpath constraint that will be enforced for this leaf.
• type
– The data type (range and so on) of this leaf.
YANG Leaf-List Statement
leaf-list domain-search {
Leaf-list Statement type string;
• One value ordered-by user;
• No children description “List of domain names to search";
}
• Multiple instances
NETCONF XML:
<domain-search>[Link]</domain-search>
<domain-search>[Link]</domain-search>
YANG Leaf-List Statement (Cont.)
leaf leaf-list

leaf enabled { leaf-list cipher {


type boolean; type string;
default true; }
}
Example XML instance
Example XML instance <cipher>blowfish-cbc</cipher>
<enabled>false</enabled> <cipher>3des-cbc</cipher>
YANG Leaf-List Statement (Cont.)
Container Statement—Groups-related leafs and containers
container system {
container services {
container ssh {
presence "Enables SSH";
description "SSH service configuration";
// more leafs, container, other things
}
}
}
NETCONF XML:
<system>
<services>
<ssh>
</ssh>
</services>
</system>
YANG List Statements
list user { NETCONF XML:
key "login-name"; <user>
leaf login-name { <login-name>crobbins</login-name>
type string; <full-name>Chuck Robbins</fullname>
} </user>
leaf full-name { <user>
type string; <login-name>jchambers</login-name>
} <full-name>John Chambers</fullname>
} </user>
YANG List Statements (Cont.)
Attributes for list and leaf-list
• max-elements
– Max number of elements in list. If max-elements are not specified, there is no upper limit,
i.e. “unbounded”
• min-elements
– Min number of elements in list. If min-elements are not specified, there is no lower limit,
for example, 0
• ordered-by
– List entries are sorted by “system” or “user”. System means that elements are sorted in a
natural order (numerically, alphabetically, and so on). User means the order the operator
entered them in is preserved. “ordered-by user” is meaningful when the order among the
elements has significance, for example, DNS server search order or firewall rules.
Putting Things Together
module acme-system {
namespace "[Link]
prefix "acme";

organization "ACME Inc.";


contact "joe@[Link]";
description
"The module for entities implementing the.."

revision 2016-08-09 {
description "Initial revision.";
}
Putting Things Together (Cont.)
container system {
leaf host-name {
type string;
description "Hostname for this system";
}

leaf-list domain-search {
type string;
description "List of domain names to search";
}

### output continued on the next slide ###


Putting Things Together (Cont.)
### output continuation from the previous slide ###

container login {
leaf message {
type string;
description "Message given at start of login session";
}

list user {
key "name";
leaf name {
type string;
}

### output continued on the next slide ###


Putting Things Together (Cont.)
### output continuation from the previous slide ###

leaf full-name {
type string;
}
leaf class {
type string;
}
}
}
}
}
YANG Types
Base Types Type Description
• Most YANG elements have a int8/16/32/64 Integer
data type
uint8/16/32/64 Unsigned integer
• Type may be a base type or
derived type: decimal64 Non-integer

– Derived types may be simple string Unicode string


typedefs or groupings
enumeration Set of alternatives
(structures)
– There are 20+ base types to boolean True or false
start bits Boolean array

binary Binary BLOB

leafref Reference "pointer"

...and more
YANG Types (Cont.)
Common YANG Types counter32/64 ipv4-address
• Commonly used YANG types gauge32/64 ipv6-address
defined in RFC 6021
object-identifier ip-prefix
• Use:import “ietf-yang-types”
{ prefix yang; } to reference date-and-time ipv4-prefix
these types as e.g. type timeticks ipv6-prefix
yang:counter64;
timestamp domain-name

phys-address uri

ip-version mac-address

flow-label bridgeid

port-number vlanid

ip-address ...and more


YANG Typedef Statement
Define a new type

typedef percent {
type uint16 {
range "0 .. 100";
}
description "Percentage";
}

leaf completed {
type percent;
}
YANG Typedef Statement (Cont.)
Typedef & Union Statements
• Define a new type that is either an IPv4 or IPv6 address

typedef ip-address {
type union {
type ipv4-address;
type ipv6-address;
}
}
YANG Choice Statement
Each alternative may consist of multiple definitions, either as a named or
anonymous group
choice route-distinguisher {
case ip-address-based {
leaf ip-address {
type ipv4-address;
}
leaf ip-address-number {
type uint16;
}
}

### output continued on the next slide ###


YANG Choice Statement (Cont.)
### output continuation from the previous slide ###

case asn32-based {
leaf asn32 {
type uint32;
}
leaf two-byte-number {
type uint16;
}
}
}

<asn32>12356789</asn32>
<two-byte-number>2468</two-byte-number>
YANG Grouping Statement
grouping target {
leaf address {
type inet:ip-address;
description "Target IP";
}
leaf port {
type inet:port-number;
description "Target port number";
}
}
container peer {
container destination {
uses target;
}
}
YANG Grouping Statement (Cont.)
YANG Grouping Statement (Cont.)
grouping endpoint {
leaf address {
type ip-address;
}
leaf port {
type port-number;
}
}

### output continues on the next slide ###


YANG Grouping Statement (Cont.)
### output continuation from the previous slide ###

container connection {
container source {
uses endpoint {
refine port {
default 80;
}
}
}
container destination {
uses endpoint {
refine port {
default 80;
}
}
}
}
YANG Grouping Statement (Cont.)
<connection>
<source>
<address>[Link]</address>
<port>8080</port>
</source>
<destination>
<address>[Link]</address>
<port>8080</port>
</destination>
</connection>
YANG Miscellaneous Statements
• Leafref list user {
key uid;
– Make an element reference in one of the rows in a unique name;
list, set the element type to leafref. …
• Unique
– Fields can be declared unique (example to the
right).
• Must
– Restricts valid values by XPath expression.
• When
– Used to check for particular conditions.
YANG RPC Statement
Administrative actions with input and output parameters ...and side effects.
YANG RPC Statement (Cont.)
rpc activate-software-image {
input {
leaf image {
type binary;
}
}
output {
leaf status {
type string;
}
}
}
YANG Imports and Includes
YANG Modules and Submodules
module acme-module {
namespace “…”;
prefix acme;

import ”ietf-yang-types" {
prefix yang;
}
include "acme-system";

organization "ACME Inc.";


contact joe@[Link];
description ”Module describing the
ACME products”;
revision 2007-06-09 {
description "Initial revision.";
}
### output continues on the next slide ###
YANG Modules and Submodules (Cont.)
### output continuation from the previous slide ###

submodule acme-system {
belongs-to acme-module {
prefix acme;
}

import ”ietf-yang-types" {
prefix yang;
}

container system {

}
}
YANG Model Examples
container community-sets {
description “Container for community sets";
list community-set {
key community-set-name;
description "Definitions for community sets";
leaf community-set-name {
type string;
description "name of the community set";
}
leaf-list community-member {
type string {
pattern '([0-9]+:[0-9]+)';
}
description "members of the community set";
}
}
}
XML
<community-sets>
<community-set>
<community-set-name>CSET1</community-set-name>
<community-member>65172:1</community-member>
<community-member>65172:2</community-member>
<community-member>65172:3</community-member>
</community-set>
<community-set>
<community-set-name>CSET10</community-set-name>
<community-member>65172:10</community-member>
<community-member>65172:20</community-member>
<community-member>65172:30</community-member>
</community-set>
</community-sets>
JSON
{ "community-sets": {
"community-set": [
{ "community-set-name": "CSET1",
"community-member": [
"65172:1",
"65172:2",
"65172:3" ]
},
{ "community-set-name": "CSET10",
"community-member": [
"65172:10",
"65172:20",
"65172:30" ]
}
]
}
}
CLI
community-set CSET1
65172:1,
65172:2,
65172:3
end-set
!
community-set CSET10
65172:10,
65172:20,
65172:30
end-set
!
YANG Tools
Data Models
YANG Tools
• YANG Validator
• pyang
• ydk
• YANG Explorer
YANG Validator
YANG Validator (Cont.)
Discovery 12: Validating YANG
Models Using Yang Validator
Topology
pyang
$ pyang -f tree -p /path/to/models <yang-file>
$ pyang -f tree -p yang/standard/ietf/RFC yang/standard/ietf/RFC/ietf-
[Link]
module: ietf-interfaces
+--rw interfaces
| +--rw interface* [name]
| +--rw name string
| +--rw description? string
| +--rw type identityref
| +--rw enabled? boolean
| +--rw link-up-down-trap-enable? enumeration {if-mib}?
+--ro interfaces-state
+--ro interface* [name]
+--ro name string
+--ro type identityref
+--ro admin-status enumeration {if-mib}?
+--ro oper-status enumeration
pyang (Cont.)
$ pyang -f sample-xml-skeleton -p /path/to/models <yang-file>
cisco@cisco:~$ pyang -p tools/ tools/oc-models/release/models/vlan/openconfig-
[Link] -f sample-xml-skeleton
<?xml version='1.0' encoding='UTF-8'?>
<data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"><vlans
xmlns="[Link] /><config><vlan-id /><name
/></config><state><vlan-id /><name /></state><members><member><interface-
ref><state><interface /><subinterface /></state></interface-
ref></member></members></vlan></vlans></data>
cisco@cisco:~$
pyang (Cont.)
<data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<vlans xmlns="[Link]
<vlan>
<vlan-id />
<config>
<vlan-id />
<name />
</config>
<state>
<vlan-id />
<name />
</state>

### output continues on the next slide ###


pyang (Cont.)
### output continuation from the previous slide ###

<members>
<member>
<interface-ref>
<state>
<interface />
<subinterface />
</state>
</interface-ref>
</member>
</members>
</vlan>
</vlans>
</data>
pyang (Cont.)
• JavaScript Tree Output really useful
• Use pyang –f jstree –p <path-to-models> <[Link]> >/tmp/[Link]
pyang (Cont.)
$ pyang -p /path/to/models <yang-file> --lint

cisco@cisco:~$ pyang -p tools/ tools/oc-models/release/models/lldp/openconfig-


[Link] --lint
cisco@cisco:~$
Discovery 13: Viewing and Validating
YANG Models with pyang
Topology
SDN Controllers
Designing and Implementing Cisco Network Programmability (NPDESI)
v1.0
Cisco APIC-EM
SDN Controllers
APIC-EM Overview
APIC-EM Overview (Cont.)
An SDN controller providing:
• Advanced Programmability Capabilities
• Policy-based Network Automation Capabilities
• Intent-based Policy Capabilities
APIC-EM Overview (Cont.)
Main Features & Benefits:

• Virtual and Physical platform


• Network Information Database
• Network Topology Visualization
• Plug and Play Application
• Cisco Intelligent WAN application
• Public Key Infrastructure Service
• Path Trace Application
• High Availability
• Backup and Restore
APIC-EM Overview (Cont.)
Simplified Configuration
APIC-EM Overview (Cont.)
Northbound and Southbound APIs
APIC-EM Web User Interface Dashboard
APIC-EM Platform Architecture
Supported Devices
APIC-EM Common Tasks
Common tasks you will perform when using APIC-EM are:

• Network Discovery
• Viewing Host and Device Inventories
• Visualizing the Network Topology
• Configuring Backup and Restore
• Managing Users
Starting Network Device Discovery
How APIC-EM Network Discovery Works
Discovery 17: Network Discovery
Configuration
Topology
Performing APIC-EM Tasks
Viewing Device Inventory
Performing APIC-EM Tasks (Cont.)
Deleting a Device
Performing APIC-EM Tasks (Cont.)
Viewing Host Inventory
Performing APIC-EM Tasks (Cont.)
Network Topology Visualization
Performing APIC-EM Tasks (Cont.)
Backing up and Restoring the Database
Performing APIC-EM Tasks (Cont.)
Users and RBAC Roles and Privileges
Discovery 18: APIC-EM Network
Discovery and RBAC
Topology
APIC-EM Applications
APIC-EM Applications (Cont.)
Network Plug-and-Play
APIC-EM Applications (Cont.)
Network Plug-and-Play Components
APIC-EM Applications (Cont.)
Cisco SD-WAN
APIC-EM Applications (Cont.)
Intelligent Wide Area Networks (IWAN)
APIC-EM Applications (Cont.)
IWAN Dashboard
APIC-EM Applications (Cont.)
Path Trace Application
APIC-EM Applications (Cont.)
The EasyQoS Solution
APIC-EM APIs
Using Postman with APIC-EM
Using Postman with APIC-EM (Cont.)
Using Postman with APIC-EM (Cont.)
Using Postman with APIC-EM (Cont.)
Using Python with APIC-EM
Using Postman with APIC-EM (Cont.)
The “uniq” APIC-EM Python Library
Discovery 19: Consuming the APIC-
EM API
Topology
Cisco Application Centric
Infrastructure
SDN Controllers
ACI Overview
Two modes of operation to support different operational models
ACI Overview (Cont.)
9500 Series 9300 Series
• 9504 • 9332PQ
• 9508 • 9372PX / 9372TX
• 9516 • 9396PX / 9396TX
• 93128TX
• 9336PQ (ACI Spine Switch)
ACI Overview (Cont.)
ACI Fabric
ACI Overview (Cont.)
Overloaded Network Constructs
ACI Overview (Cont.)
Application Language Barriers
• Developer and infrastructure teams must translate between disparate languages.
ACI Overview (Cont.)
What is an Application to the Network?
• A collection of all the Application's End Points
• The Application's L2 — L7 Network Policies
• The Relationship between these End Points and their Policies
ACI Overview (Cont.)
Logical Network Provisioning of Stateless Hardware
ACI Overview (Cont.)
ACI – Key Architectural Benefits
• Decoupling of end point identity, location, and
associated policy all of which are independent
from the underlying point of device attachment.
• Distributed Layer 3 gateway
• Any IP address anywhere
• Full normalization of the ingress encapsulation
mechanism used, 802.1Q VLAN, IETF VXLAN,
IETF NVGRE.
• Service insertion and redirection
• Removal of flooding requirements for IP control
plane (ARP/GARP)
ACI Overview (Cont.)
Common Policy and Operations Framework
ACI Overview (Cont.)
Fabric Initialization & Maintenance
ACI Overview (Cont.)
Introduction to APIC GUI
Discovery 20: ACI Fabric Discovery
Topology
Discovery 21: Creating Objects with
APIC GUI
Topology
ACI Object Model

VRFs and Subnets are independent between tenants


ACI Object Model (Cont.)
MIT
• Objects within APIC are structured in tree-based
hierarchy
• Objects are referred to as MO
• Packages identify the functional area
– fv – fabric virtualization
– vz – virtual zones
– fabric – physical fabric
• Every object has a parent
– Except top:root/uni
• Relationships
ACI Object Model (Cont.)
Management Information Model
ACI Object Model (Cont.)
ACI Object Model (Cont.)
ACI Object Model (Cont.)
ACI Object Model (Cont.)
Visore
• APIC Object Store Browser
• Directly read properties, associations, statistics, relationships
• Can search for all instances of a type (class) of object
– Where does this subnet exist? What BD is it tied to?
• [Link] IP ADDRESS>/[Link]
– Log in with APIC credentials
ACI Object Model (Cont.)
Visore Interface
• Initial screen is all MO's of class fabricNode
• Navigate Up and Down the MIT
• Search on Class or DN
– Filter on property, name, equal/not-equal
ACI Object Model (Cont.)
Stats, Faults via Visore
• Left arrow: Parent of the Managed Object
• Right arrow: Children of the Managed Object
• Statistics for the Managed Object (if supported)
• Faults for the Managed Object
• HealthScore ("healthInst”) for the Managed
Object
ACI Object Model (Cont.)
Class-Based Query
• Query based on Class
• Returns all objects of class, e.g. all Tenants
(fvTenant)
• Examine URI
ACI Object Model (Cont.)
DN-Based Query
• Query based on DN
Discovery 22: Navigating the Object
Model
Topology
APIC REST API
• REST API Overview
• API Inspector
• Postman Client
• Native Python
APIC REST API (Cont.)
Overview
• APIC is based on a hierarchical object model. EVERYTHING is represented as an
object and every object can be manipulated via REST.
• REST operations: POST, GET, DELETE
• Support for JSON and XML
• Supports event driven notification (subscriptions)
APIC REST API (Cont.)
Log in to APIC

{
JSON "aaaUser":{
• URL: [Link] "attributes":{
• Body: "name":"admin",
"pwd":”cisco123"
}
}
}
APIC REST API (Cont.)
XML
• URL: [Link]
• Method: POST
• Body:

<aaaUser name="admin" pwd=”cisco123"/>


APIC REST API (Cont.)
API Inspector
• Sniffer for the Object Creation through
the REST API
– GET
– POST
• Navigating through panes fetches data
with GET requests
• Submitting configuration changes uses
POST requests
APIC REST API (Cont.)
API Inspector — Creating a Tenant
APIC REST API (Cont.)
API Inspector — Subscription APIs

• Event-Driven Notifications
• Opens Web Socket to APIC
• Listens for Changes to a Given Object
APIC REST API (Cont.)
Discovery 23: Using API Inspector
Topology
Using Postman REST Client
Logging In
Using Postman REST Client (Cont.)
Get Object by Distinguished Name
Using Postman REST Client (Cont.)
Visore/Postman Property Comparison
Using Postman REST Client (Cont.)
Creating Objects
Using Postman REST Client (Cont.)
Obtaining the URI
Using Postman REST Client (Cont.)
Native Python

• Python requests module


• Examples will make native API calls
– No SDK being used
Using Postman REST Client (Cont.)
Native Python — Example 1 — Authentication

import requests
import json

def get_cookies(apic):
username = 'admin'
password = 'cisco123'
url = apic + '/api/[Link]'
auth = dict(aaaUser=dict(attributes=dict(name=username, pwd=password)))
authenticate = [Link](url, data=[Link](auth), verify=False)
return [Link]

### output continues on next slide ###


Using Postman REST Client (Cont.)
Native Python — Example 1 — Authentication

### output continuation from the previous slide ###

if __name__ == "__main__":
protocol = 'http'
host = 'apic'
apic = '{0}://{1}'.format(protocol, host)
cookies = get_cookies(apic)
Using Postman REST Client (Cont.)
Native Python — Example 2 – Get Subnets

def get_subnets(apic, cookies):


uri = '/api/class/[Link]'
url = apic + uri
req = [Link](url, cookies=cookies, verify=False)
response = [Link]
return response

rsp = get_subnets(apic,cookies)
# rsp is a unicode string

rsp_dict = [Link](rsp)
subnets = rsp_dict['imdata']
Using Postman REST Client (Cont.)
{"totalCount":"3","imdata":[{"fvSubnet":{"attributes":{"childAction":"","ctrl":"qu
erier","descr":"","dn":"uni/tn-infra/BD-default/subnet-[[Link]/27]",
"ip":"[Link]/27","lcOwn":"local","modTs":"2016-08-
21T11:47:48.321+00:00","monPolDn":"uni/tn-common/monepg-default",
"name":"","preferred":"no","scope":"private","status":"","uid":"0","virtual":"no"}
}},
{"fvSubnet":{"attributes":{"childAction":"","ctrl":"","descr":"","dn":"uni/tn-
DrPepper/BD-Web/subnet-[[Link]/24]","ip":"[Link]/24",
"lcOwn":"local","modTs":"2016-08-21T11:59:30.416+00:00","monPolDn":"uni/tn-
common/monepg-defaul
t","name":"[Link]:24","preferred":"no","scope":"private","status":"","uid":"153
74","virtual":"no"}}},{"fvSubnet":
{"attributes":{"childAction":"","ctrl":"","descr":"","dn":"uni/tn-DrPepper/BD-
DB/subnet-[[Link]/24]","ip":"10.20.
2.1/24","lcOwn":"local","modTs":"2016-08-
21T12:00:47.046+00:00","monPolDn":"uni/tn-common/monepg-default",
"name":"[Link]:24","preferred":"no","scope":"private","status":"","uid":"15374"
,"virtual":"no"}}}]}
Using Postman REST Client (Cont.)
Native Python — Example 2 – Accessing Return Elements
• Attributes are stored as the value of the imdata key
• Value is a list of dictionaries with each Subnet being a dictionary

>>> rsp = get_subnets(apic,cookies)


>>> rsp_dict = [Link](rsp)
>>> subnets = rsp_dict['imdata']

>>> for subnets in subnets:


... print subnets['fvSubnet']['attributes']['ip']
...
[Link]/27
[Link]/24
[Link]/24
>>>
Using Postman REST Client (Cont.)
Native Python —Query Filters

• Usually more efficient as less number of MOs need to be serialized and returned
• Filter the response returned using the supplied condition:
– Syntax: [Link]
– Returns only the MOs which satisfies the condition
Using Postman REST Client (Cont.)
Native Python — Example 3 – Using Query Target
• Use API Inspector and Visore to determine correct filter
• Example shows how to query for one or more classes when using DN

def get_object(apic, cookies):


uri = '/api/node/mo/uni/[Link]?query-target=subtree&target-subtree-
class=fvAEPg'
url = apic + uri
req = [Link](url, cookies=cookies, verify=False)
response = [Link]
return response
Cobra SDK
• Cobra is a native Python language binding for the APIC REST API
• Supports lookups, creations, modifications, and deletions
• Objects in Cobra are 1:1 representations of objects in the Management Information
Tree (MIT)
Cobra SDK (Cont.)
• Object Model Overview
• Installation
• Examples
• Reference Docs
• [Link]
Cobra SDK (Cont.)
Workflow
Cobra SDK (Cont.)
Cobra Installation
• Download directly from APIC
• Two separate packages
– acicobra
– acimodel
• http[s]://<apic>/cobra/_downloads
– easy_install –Z acicobra-1.*-[Link] acicobra
– easy_install –Z acimodel-1.*-[Link] acimodel
• Not yet on pypi (installable via pip)
Cobra SDK (Cont.)
acicobra
• This is technically the SDK and includes:
– cobra
– [Link]
– [Link]

from [Link] import MoDirectory


from [Link] import LoginSession
from [Link] import ConfigRequest
from [Link] import toXMLStr
Cobra SDK (Cont.)
acimodel
• These are python packages that model the MIT and includes:
– cobra
– [Link]

from [Link] import Tenant


from [Link] import Filter
Cobra SDK (Cont.)
Example 1 - Get Tenant – DN Lookup

def get_tenant(moDir, name):

mo = [Link]('uni/tn-{0}'.format(name))
return mo

if __name__ == "__main__":

username = 'admin'
password = 'Cisco123'
protocol = 'https'
host = 'apic'

### output continues on next slide ###


Cobra SDK (Cont.)
### output continuation from previous slide ###

apic = '{0}://{1}'.format(protocol, host)

session = LoginSession(apic, username, password)


moDir = MoDirectory(session)
[Link]()
Cobra SDK (Cont.)
Example 1 - Get Tenant – DN Lookup (continued)
>>> tenant = get_tenant(moDir, 'Finance')
>>>
>>> print tenant
<[Link] object at 0x7f387105ac50>
>>>
>>> [Link]
<[Link] object at 0x7f3866af5450>
>>>
>>> str([Link])
'uni/tn-Finance'
>>>
>>> [Link]
'Finance'
>>>
Cobra SDK (Cont.)
Example 2 - Get Tenants – Class Lookup
def get_tenants(moDir):

tenants = [Link]('fvTenant')
return tenants

>>> tenants = get_tenants(moDir)


>>>
>>> for tenant in tenants:
... print [Link]
...
Accounting
common
infra
mgmt
Finance
Cobra SDK (Cont.)
Example 3 – Configuring Application Profile

tenant = 'Finance'
ap = 'Finance-3Tier-App'

tenant_mo = [Link]('uni/tn-{0}'.format(tenant))

ap_mo = Ap(tenant_mo, name=ap, descr='new ANP for Finance')

config_req = ConfigRequest()
config_req.addMo(ap_mo)

[Link](config_req)
Arya
• GUI creates REST API calls
• API Inspector shows REST API calls
• ARYA ([Link]) creates code from REST
(objects)
• Auto-generate Python code
– Uses Cobra
Arya (Cont.)
Workflow
Arya (Cont.)
Optionally get the XML/JSON objects by using API Inspector

Example stored in file: [Link]

{"fvTenant":{"attributes":{"dn":"uni/tn-TENANT6","name":"TENANT6","descr":"sample-
test-for-cisco","rn":"tn-TENANT6","status":"created"},"children":[]}}
Arya (Cont.)
# PORTION OF WHAT IS GENERATED
# list of packages that should be imported for this code to work
import [Link]
import [Link]
import [Link]
import [Link]
import [Link]
from [Link] import toXMLStr

# log into an APIC and create a directory object


ls = [Link]('[Link] 'admin', 'password')
md = [Link](ls)
[Link]()
Arya (Cont.)
# the top level object on which operations will be made
topMo = [Link]('')

# build the request using cobra syntax


fvTenant = [Link](topMo, name=u'TENANT6', descr=u'sample-test-for-
cisco')

# commit the generated code to APIC


print toXMLStr(topMo)
c = [Link]()
[Link](topMo)
[Link](c)
Arya (Cont.)
Usage

$ [Link] -h
usage: Code generator for APIC cobra SDK [-h] [-f FILEIN] [-s] [-d SOURCEDIR]
[-t TARGETDIR] [-i IP] [-u USERNAME]
[-p PASSWORD] [-nc]

optional arguments:
-h, --help show this help message and exit
-f FILEIN, --filein FILEIN
Document containing post to be sent to REST API
-s, --stdin Parse input from stdin, for use as a filter, e.g., cat
[Link] | [Link] -s
-d SOURCEDIR, --sourcedir SOURCEDIR
Specify a source directory containing ACI object files
you want to convert to python.
### output continues on the next slide ###
Arya (Cont.)
### output continuation from the previous slide ###

-t TARGETDIR, --targetdir TARGETDIR


Where to write the .py files that come from the -d
directory. If none is specified, it will default to
SOURCEDIR
-i IP, --ip IP IP address of APIC to be pre-populated
-u USERNAME, --username USERNAME
Username for APIC account to be pre-populated in
generated code
-p PASSWORD, --password PASSWORD
Password for APIC account to be pre-populated in
generated code
-nc, --nocommit Generate code without final commit to changes
Arya (Cont.)
Example 1 - Create Tenant, Bridge Domain, Subnet

[Link]:

<polUni>
<fvTenant name="Tenant_7">
<fvBD name="T7_BD">
<fvSubnet subnet="[Link]/24">
</fvSubnet>
</fvBD>
</fvTenant>
</polUni>

$ [Link] -f [Link]
Arya (Cont.)
$ [Link] -f [Link] -i apic -u admin -p cisco123 -nc
Arya (Cont.)
Example 2 - Create App Pro, EPG, Associations

{
"fvAp": {
"attributes": {
"dn": "uni/tn-Finance/ap-Finance-3Tier-App",
"name": "Finance-3Tier-App",
"rn": "ap-Finance-3Tier-App",
"status": "created"
},
"children": [
{

### output continues on next slide ###


Arya (Cont.)
### output continuation from previous slide ###
"fvAEPg": {
"attributes": {
"descr": "descr-epg-web",
"dn": "uni/tn-Finance/ap-Finance-3Tier-App/epg-web_epg",
"name": "web_epg",
"prio": "level1",
"rn": "epg-web_epg",
"status": "created"
},

### output shortened for brevity ###


Discovery 24: Using ARYA
Topology
ACI Toolkit
• Simple toolkit built on top of APIC API
• Set of simple python objects
– Python Library
– Used to generate REST API calls
– Runs locally
• Not full functionality, most common
– Focused primarily on configuration
• Preserves the ACI basic concepts
– Tenants, EPGs, Contracts, etc.
• [Link]
• [Link]
ACI Toolkit (Cont.)

• Exposes limited number of ACI objects


• Introduction to ACI concepts and working with the APIC programmatically
• Applications cover many common use cases for building apps
ACI Toolkit (Cont.)
Installing Toolkit

• GitHub
• Pre-installed OVA
• Docker
ACI Toolkit (Cont.)
Toolkit Object Model

• Sub-set of complete ACI object model


• Focused on three distinct areas of the “core” object model:
– Application Topology (tenants and contracts)
– Interface Model
– Physical Topology
ACI Toolkit (Cont.)
Application Topology
ACI Toolkit (Cont.)
Application Topology (continued)
ACI Toolkit (Cont.)
Example 1 – Tenant Configuration

# Create the Tenant


tenant = Tenant('toolkit_tenant')

# Create the Application Profile


app = AppProfile('app_tk', tenant)

# Create the EPG


epg = EPG('epg_tk', app)

# Create a VRF and BridgeDomain


context = Context('vrf_tk', tenant)
bd = BridgeDomain('bd_tk', tenant)
bd.add_context(context)
ACI Toolkit (Cont.)
# Place the EPG in the BD
epg.add_bd(bd)

# Create Session object


session = Session(apic, username, password)

# Login to APIC
[Link]()

# Push configuration
resp = session.push_to_apic(tenant.get_url(), tenant.get_json())
ACI Toolkit (Cont.)
Example 2 – Get Interface Info

>>> interfaces = [Link](session)


>>> interfaces = [Link](session=session, pod_parent='1', node='101',
module='1', port='15')

>>> intf = interfaces[0]


>>> print [Link]
leaf
>>>
>>> print [Link]
15
>>> print [Link]
eth 1/101/1/15
>>>
### output continues on the next slide ###
ACI Toolkit (Cont.)
### output continuation from the previous slide ###

>>> print [Link]


9000
>>> print [Link]
up
>>> print [Link]
inherit
>>>
>>> print [Link]
None
>>> print intf.is_cdp_enabled()
False
ACI Toolkit (Cont.)
Example 3 – Subscriptions - Event Driven Notifications
ACI Toolkit (Cont.)
ACI Toolkit Applications
• CLI
• Diagrams
• Lint
• Cable Plan
• Event Feeds
• Fake APIC
ACI Toolkit Applications — CLI
CLI
• Interactive “traditional” CLI for working with an ACI fabric
• Supported commands can be found on GitHub
ACI Toolkit Applications — CLI (Cont.)
$ python [Link] -l admin -p c1sco123 -u [Link]

Cisco ACI Toolkit Command Shell


Copyright (c) 2015, Cisco Systems, Inc. All rights reserved.

fabric# show tenant


Tenant
------
infra
common
mgmt
Finance
Discovery 25: CLI Emulation
Topology
ACI Toolkit Applications — Diagrams Tool
• Auto-generate visual representation of tenant objects
• $ python [Link] -o [Link]
ACI Toolkit Applications — Diagrams Tool (Cont.)
Discovery 26: ACI Diagram Tool
Topology
ACI Toolkit Applications — Lint
• Static analysis tool for Cisco ACI fabrics
• Example Use Cases:
– Configuration Analysis – Determine whether any of the configuration could be possibly
problematic or suspicious. Based on a defined number of conditions (can be expanded)
– Compliance & Auditing – Determine if any violations occur from a policy and security
perspective. Compliments APICs use of tags for user-defined groups.
ACI Toolkit Applications — Lint (Cont.)
Discovery 27: ACI Toolkit — Lint
Topology
ACI Toolkit Applications — Cable Plan
• Export existing cabling scheme from existing ACI fabrics
• Compare two different cabling schemes
– Desired vs. Existing
ACI Toolkit Applications — Cable Plan (Cont.)
$ python [Link] -e existing_cabling
$ cat existing_cabling
<?xml version="1.0" encoding="UTF-8"?>
<?created by [Link]?>
<CISCO_NETWORK_TYPES version="None" xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link] nxos-cable-plan-
[Link]">
<DATA_CENTER networkLocation="None" idFormat="hostname">
<CHASSIS_INFO sourceChassis="Spine1" type="n9k">
<LINK_INFO sourcePort="eth5/2" destChassis="Leaf2"
destPort="eth1/49"/>
<LINK_INFO sourcePort="eth5/1" destChassis="Leaf1"
destPort="eth1/49"/>

### output continues on next slide ###


ACI Toolkit Applications — Cable Plan (Cont.)
### output continuation from previous slide ###

</CHASSIS_INFO>
<CHASSIS_INFO sourceChassis="Spine2" type="n9k">
<LINK_INFO sourcePort="eth5/2" destChassis="Leaf2"
destPort="eth1/50"/>
<LINK_INFO sourcePort="eth5/1" destChassis="Leaf1"
destPort="eth1/50"/>
</CHASSIS_INFO>
</DATA_CENTER>
</CISCO_NETWORK_TYPES>
ACI Toolkit Applications — Event Feeds
• ACI Events to Atom Feeds
• Subscribes to APIC Managed Objects and records any updates to the objects over
a web socket connection
• Monitor changes & Display updates in a reader of your choice!
– Monitoring tools readers, or individual, etc.
ACI Toolkit Applications — Event Feeds (Cont.)
• Start the eventfeeds application
• Available feeds are accessible via web
• Subscribe

$ python [Link] --ip [Link] --port 5001


ACI Toolkit Applications — Event Feeds (Cont.)
ACI Toolkit Applications — Event Feeds (Cont.)
ACI Toolkit Applications — Fake APIC
• The Fake APIC is designed for users to session = FakeSession(filenames)
query = '/api/mo/uni/tn-tenant1/BD-
view Managed Objects (and their [Link]?query-target=children'
properties) based on JSON fake_ret = fake_session.get(query)
configuration files. fake_data = fake_ret.json()['imdata']
data = fake_ret.json()['imdata']
• The Fake APIC works as an offline- # print the data from the Fake APIC
tool for users who may not have access print [Link](data, indent=4)
to the APIC, but still want to see certain
(or all) Managed Objects on the
network.
Discovery 28: Using the APIC REST
API
Topology
Network Operations
Designing and Implementing Cisco Network Programmability (NPDESI)
v1.0
Software Development
Methodologies
Network Operations
Software is Everywhere
• “Software is Eating the World” – Marc
Andreeseen
• Companies impacting everyone’s day to day
lives that did not exist 10 years ago
• “40% of businesses unfortunately will not exist in
a meaningful way in 10 years” - John Chambers
Software is Everywhere (Cont.)
Software is Everywhere (Cont.)
Development Methodologies
• Waterfall
• Agile
• Prototyping
• Rapid App Development
• Extreme Programming
Waterfall
• Around since the 1950s
• Sequential Design Approach
• Requirement and scope are fixed
• Well known and fixed requirements
• Short projects
• Product definition is stable
Waterfall (Cont.)
Waterfall (Cont.)
Pros Cons
• Good design • Difficult requirement gathering
• Good documentation • Inflexible design
• Good progress measurement • Long process
Lean
Management philosophy to eliminate
waste across all aspects of business.
• Derived from Toyota Production
Systems
• Change enablers:
– Purpose
– Process
– People
Agile (Cont.)
Implementation of Lean for
software development
• Short sprints
• Continuous incremental value
Agile (Cont.)
SCRUM
• Agile Project Management
Methodology
– Product Backlog
– Sprint Backlog
– Sprints
– Daily Scrum
Agile (Cont.)
Developing with Agile
Agile (Cont.)
Pros Cons
• Rapid, continuous delivery of useful • Lack of emphasis on documentation
software • Scope Creep
• People before process and tools • Higher chance for bugs
• Really flexible approach
• Even late changes in requirements are
welcomed
Introduction to DevOps
Network Operations
Dev and Ops – The Problem
Developers World
• Care About
– Writing Software
– Working Code
– APIs
– Libraries
– Sprints
• Success
– Software works – Laptop and Test
– Finished Sprint
Dev and Ops – The Problem (Cont.)
Operations World
• Care About
– Everything is stable
– Standards
– Templates
– Not getting bothered at 2:00 am
• Success
– Software is stable
– Backup and restore works
– Systems are operating within defined thresholds
Dev and Ops – The Problem (Cont.)
• Development wants to release newer
versions of applications and new
products as fast as possible
• The Operations department wants a
reliable and stable environment
Dev and Ops – The Problem (Cont.)
DevOps Demystified
What is DevOps? • Deliver software, products, and
• DevOps is a change in operational services faster
approach and mindset • Requires commitment at all levels
• Cultural Movement • Break down silos and improve
• Enhanced level of communication communications
• Automate all the things
DevOps Demystified (Cont.)
• DevOps is the utilization of Lean and Agile techniques to combine development and
operation together
• It based on CALMS:
– Culture
– Automation
– Lean
– Measurement
– Sharing
DevOps Demystified (Cont.)
Culture
• Good Habits:
– Trust
– Respect
– Supportive
– Collaborative
– No-blame / no victims
– Common Goals
• Management evolution
DevOps Demystified (Cont.)
Automation
• From a technology perspective, this is where many engineers want to start. Deploy
Automation.
– Puppet
– Chef
– Ansible
• In an environment that practices DevOps, automation will occur everywhere and
between teams
DevOps Demystified (Cont.)
Lean
• Identify wastes
• Continuous learning
• Focus on people
• Optimize the whole
DevOps Demystified (Cont.)
Measurement • Rewards and feelings of success
• Mean Time To Recovery (MTTR) • Release and deployment
• Number and frequency of • User Acceptance Testing
outages/performance issues • Measure Everything
• Number and cost of resources
• Attitude to continuous improvement
DevOps Demystified (Cont.)
Sharing
• Share code, ideas, and problems
• Leverage common repositories like GitHub
• ChatOps
DevOps Demystified (Cont.)
DevOps Benefits*
• Increased Agility
• Increased Reliability
• Impact to the business
DevOps Tools and Technologies
• Source code management
• Code review
• Automated Testing
• Collaboration and release/configuration
management
DevOps Tools and Technologies (Cont.)
DevOps Tools and Technologies (Cont.)
Version Control
Network Operations
Version Control Systems
Why Version Control?
• Collaboration
• Storing Versions
• Restoring Previous Versions
• Understanding What Happened
Version Control Systems (Cont.)
• Concurrent Versions System • Git
– Originally was a “first come, first serve – Originally built to support Linux Kernel
system” developing
• Apache Subversion • Mercurial
– Atomic operations – Originally made to compete with Git
– Slow comparative speed
Overview of Git
• Created by Linus Torvalds in 2005
• First version built in about 10 days
• Version Control
• Code collaboration
• Minimize mistakes
Overview of Git (Cont.)
When should you use it?
Have you ever:
• Maintain multiple versions of a product?
• See the difference between two (or more) versions of your code?
• Prove that a particular change broke or fixed a piece of code?
• Review the history of some code?
• Submit a change to someone else's code?
• Share your code, or let other people work on your code?
• See how much work is being done, and where, when and by whom?
• Experiment with a new feature without interfering with working code?
Overview of Git (Cont.)
Does it matter for Networking?
• Configuration Files
• Scripts
• Variable Files
• Playbooks
• Manifests
Git Architecture
• Working Directory
• Staging Area
• Local Repository
• Remote Repository
Git Commands
Git Command Description

git init Initialize a directory for a git project

git config <params> Configure git params such as username/email

git status Check status of your project

git add <file/dir> Start tracking files and add them to the staging area

git commit –m <message> Create a local snapshot


Git Commands (Cont.)
Git Command Description

git remote <params> Add (view) remote repositories

git push <params> Push local snapshot (commit) to remote repository

git pull <params> Patch and merge changes from remote repository (combines git fetch
and git merge)
git clone <params> Copy another (remote) project to your local machine
Git Workflow
$ git init
$ git config --global [Link] "John Smith"
$ git config --global [Link] john_smith@[Link]
$ git add [Link]
$ git commit –m "initial commit"

Two examples of remotes:

*$ git remote add local ~/local_remote/


$ git remote add origin [Link]

$ git remote –v # view configured remotes


$ git push local master

*Assumes ~/local_remote has been initialized as a bare repository


Git Workflow (Cont.)
Split the project into more manageable pieces – diverge from the mainline to
add specific features, fix bugs, etc.
Git Branches
Git Command Description

git branch Check branch your own and create branches

git checkout Move between branches

git merge Merge one branch into another


Git Branches (Cont.)
git branch workflow

cisco@cisco:~$ git branch


* master
cisco@cisco:~$ git checkout -b fix_aaa_bug
Switched to a new branch 'fix_aaa_bug'
cisco@cisco:~$
cisco@cisco:~$ git branch
* fix_aaa_bug
master
cisco@cisco:~$
cisco@cisco:~$ git checkout master
cisco@cisco:~$ git merge fix_aaa_bug
Using Git
Collaborating with GitHub
What is GitHub?
• Distributed Version Control System based on Git that is a web-based hosting
service
• Free Version for public files / code repositories
• Git + Code Review
• GitHub Enterprise
Collaborating with GitHub (Cont.)
Public Git Cloud Platforms
• GitHub
• Stash
• BitBucket
Collaborating with GitHub (Cont.)
• You get to use all the git commands already reviewed using a GitHub repository as
a remote
• GitHub Pull Request
– Offers the ability to propose changes to a repository that you do not maintain
– Fork & Pull Method
Collaborating with GitHub (Cont.)
Fork & Pull Model
• Copy an existing repository to your own GitHub account (Fork)
• You are the owner of this new repository
• Clone your new repository
• Make changes as necessary
• Push to your master
• Issue a Pull Request within GitHub UI
Discovery 29: GitHub Pull Request
Topology
GitHub Pull Request: Fork and Pull
• User Point of View
• The person who wants to submit a change to another person's repository.
GitHub Pull Request: Fork and Pull (Cont.)
Step 1: Navigate to the Repository & Fork
GitHub Pull Request: Fork and Pull (Cont.)
Step 2: Fork the Repository to your Account
GitHub Pull Request: Fork and Pull (Cont.)
Step 3: Make a change to YOUR new repository

git clone [Link]


cd automation_project
touch [Link] (make a change)
git add [Link]
git commit –m ‘added new config file’
git push origin master
GitHub Pull Request: Fork and Pull (Cont.)
Step 4: Create the Pull Request
GitHub Pull Request: Fork and Pull (Cont.)
Step 5: Click “New Pull Request”
GitHub Pull Request: Fork and Pull (Cont.)
Step 6: Review the Pull Request and Create
GitHub Pull Request: Fork and Pull (Cont.)
Step 7: Add Comments to the Pull Request
GitHub Pull Request: Fork an Pull (Cont.)
Pull Request Succeeds
Changing Views
Project Maintainer Point of View
• The person who will review and merge the pull request.
Changing Views (Cont.)
Step 1: Browse to Correct Repository
Changing Views (Cont.)
Step 2: Examine List of Pull Requests
Changing Views (Cont.)
Step 3: Review (comment/approve) the Pull Request
Changing Views (Cont.)
Final View of Merge
Discovery 30: Working with Git
Topology
Automated Testing
Network Operations
Network Test Infrastructure
Network Lab of Today
• Hardware Centric
– Needs power
– Needs space
– Needs cooling
– Need physical labor
– Needs maintenance
– Needs upgrades
• One word: Expensive
Network Test Infrastructure (Cont.)
Network Lab of Tomorrow
• Single click deployment
• Software Centric
• Simple replication of networks
• Offers ability to save and restore network topologies
• Quick speed to deploy
• Low-cost alternative
Network Test Infrastructure (Cont.)
Improving the way infrastructure is tested for network applications:
• Network Functions Virtualization — software-based solutions
• Cisco Virtual Internet Routing Lab (VIRL)
• DevNet Sandboxes
Network Function Virtualization
• Software-centric network solutions:
– Bare-metal
– Container
– Virtual machine
• Virtual Box, KVM, vSphere, AWS, Azure
• Run network functions in software, lower operational costs and improves time to
deploy and test
• Focus on testing vs. rack and stack
Network Function Virtualization (Cont.)
• IOS-XRv • ACI Emulator
• NX-Osv • APIC-EM
• ASAv • Ansible
• CSR 1000V

All machines that are used in this


course are virtual machines
VIRL
• Cisco virtual machines encapsulated as a single
application
• Powerful GUI for network design and simulation
control
• Configuration engine that can build complete
Cisco configuration at the push of a button
VIRL (Cont.)
• IOSv
• IOSvL2 switch
• IOS XRv
• NX-OSv
• CSR1000v
• IOS XRv 9000
• ASAv
• Routem LXC
• Ostinato LXC
• IOL
• Third Party
• Add your own…
VIRL (Cont.)
• Two available UIs
– VM Maestro
– Web UI
• Design and configure networks
• Manage and operate
simulations
• Connect to virtual devices
VIRL (Cont.)
• Topologies are stored as XML
• Readable
• Editable
• Shareable
VIRL (Cont.)
• OpenStack
– Access to APIs from Nova,
Neutron, and Shared Services
(Keystone, Glance)
• Service Topology Director
(STD)
– Simulation Engine
– Roster
– AutoNetkit
VIRL (Cont.)
Python Example – Launch a new VIRL simulation using the STD API and a
local topology file:
DevNet
• Developer Program
• Free 24 X 7 hosted labs
• Try new technologies and products
• Learn
• Test
• Get early access to new releases of Cisco product
versions
• Collaborate across locations by sharing lab sessions
across users
DevNet Sandbox
• Sandbox Environments
• Reserve a lab or use an
always-on environment
DevNet Learning Labs
DevNet GitHub
• Code samples
• Postman Collections
• Tools & Utilities
Discovery 31: DevNet Sandbox
Topology
Discovery 32: DevNet Learning Labs
Topology
Discovery 33: DevNet GitHub
Topology
Network Testing
• How are tests executed on the network today?
• Do you execute tests before and after network change?
• Are the most common tests done using ping, traceroute, and show commands?

Even these tests can be automated


Network Testing (Cont.)
Types of Tests:
• Pre and Post change tests
• Configuration Compliance tests
– OS
– AAA
– SNMP
– ACL
• Ephemeral Data tests
• Reachability tests
• Performance tests
Network Testing (Cont.)
Getting Started VLAN Configuration
• It’s not about technology 1. Configure/Add VLAN
• It’s about documenting manual 2. Configure/Add SVI
workflows 3. Check to see if interface is available
4. Add VLAN to upstream trunk
5. Assign VLAN to local interface
Which other steps are needed? 6. Validate reachability
Network Testing (Cont.)
- name: show version
Options for Testing nxos_command:
• Perform manually commands:
• Write custom scripts and tests - show version
username: cisco
• Tools such as Ansible password: cisco
host: "{{ inventory_hostname }}"
register: output
- assert:
that:
Sample Ansible task - "'7.3(1)D1(1)' in
output['response'][0]"
Network Testing (Cont.)
- name: Reachability Test
Reachability test nxos_ping:
• Loop through a list of IP addresses dest={{ item }}
• Ensure all are reachable from a given vrf=management
host={{ inventory_hostname }}
set of devices username=cisco
password=cisco
with_items:
- [Link]
- [Link]
- [Link]
Network Testing (Cont.)
Style Check — Ensure all ACLs are upper case

# output omitted for brevity url = '[Link] response =


[Link](url, data=[Link](payload), headers=headers, auth=auth) rx_object
= [Link]([Link])['ins_api']['outputs']['output']['body']
access_lists_to_fix = [] for acl in
rx_object['TABLE_ip_ipv6_mac']['ROW_ip_ipv6_mac']: if [Link]('acl_name'): if
[Link]('acl_name') != [Link]('acl_name').upper():
access_lists_to_fix.append([Link]('acl_name')) ### output continues on next
slide ###
Network Testing (Cont.)
### output continuation from the previous slide

if access_lists_to_fix:
print "{0} ACLs to be fixed:".format(len(access_lists_to_fix))
print [Link](access_lists_to_fix, indent=4)

81 ACLs to be fixed:
[
"copp-system-p-acl-bgp",
"copp-system-p-acl-bgp6",
"copp-system-p-acl-cts",
"copp-system-p-acl-dhcp",
"copp-system-p-acl-dhcp-relay-response",
"copp-system-p-acl-dhcp6",
Network Testing (Cont.)
Test Automation
• The role automation can have on an organization is much larger than configuration
management and deploying configurations faster.
• Keep in mind style, syntax, reachability, ephermal data, configuration, and
compliance checks.
Unit Tests
• Units tests are a practice of testing specific functions and features
• Verify code and an application is working as expected
• A test case is the smallest unit of testing
• Ensure that changes don’t break existing code base
• Python test framework: unittest
Unit Tests (Cont.)
• Test specific portions of an application and library
• Example: ensure subnets work appropriately in the Cisco ACI Toolkit Python library
• Tests are meant to be small and concrete
• Unittests can be run offline – focus is on code
Unit Tests (Cont.)
def test_add_2_valid_subnets(self):
"""
Test adding 2 subnets to the BD
"""
bd, sub1 = self.create_bd_with_subnet()

# Add a second subnet to the BD


sub2 = Subnet('sub2', bd)
sub2.set_addr('[Link]/24')
bd.add_subnet(sub2)

# Verify that there are now 2 subnets


subnets = bd.get_subnets()
[Link](len(subnets) == 2)
[Link](bd.has_subnet(sub2))
return bd, sub1, sub2
Unit Tests (Cont.)
• Mock devices
• Mock live devices to simulate API responses
• Test portions of code that are parsing, obtaining, and getting data from network
devices
• Common to use [Link]

• Unittests are also for integration testing — verifying that the code is performing as
expected communicating with other systems.
• From a network perspective, this verification is helpful for configuration validation
and ephemerical state validation.
Unit Tests (Cont.)
Test Hostname

# imports removed for brevity


class TestHostname([Link]):

@staticmethod
def get_output(commands):
auth = HTTPBasicAuth('cisco', 'cisco')
headers = {
'Content-Type': 'application/json'
}

### output continues on the next slide ###


Unit Tests (Cont.)
### output continuation from the previous slide ###

payload = {
"ins_api": {
"version": "1.0",
"type": "cli_show",
"chunk": "0",
"sid": "1",
"input": commands,
"output_format": "json"
}
}
url = '[Link]
response = [Link](
url, data=[Link](payload), headers=headers, auth=auth)
rx_object = [Link]([Link])
return rx_object
Unit Tests (Cont.)
def test_hostname(self):
expected_hostname = '[Link]'
commands = ['show hostname']
rx_object = self.get_output(commands)
output = rx_object['ins_api']['outputs']['output']['body']
hostname = output['hostname']

[Link](expected_hostname, hostname)

if __name__ == '__main__':
[Link]()
Unit Tests (Cont.)
Automated Testing Workflow using Unit tests

From a network programmability perspective, unittests can be used for your


checks and other tools.
Discovery 34: Integration Testing
Topology
Continuous Integration
Network Operations
Introduction to Continuous Integration
• Continuous Integration is a software development practice that requires
developers to integrate their code into a shared repository one or more times per
day.
• Each time code is contributed, an automated process is used for verifying and
testing the software.
Introduction to Continuous Integration (Cont.)
Development without CI
• Increased number of bugs
• Insufficient testing
• Lack of integration testing
• Slow release process
• Project Delays
Introduction to Continuous Integration (Cont.)
Development with CI
• Frequent commits
• Automated builds, tests, documentation, and reports
– Early and often
• Dedicated Build and Test Servers
• Fewer bugs
Introduction to Continuous Integration (Cont.)
Multiple Releases per Day Multiple Releases per Year
• More features • Fewer features
• Stability • Instability
• Improved customer response • Negative customer response
• Employee moral goes up • Employee moral goes down
• Disruptor • Disrupted
Introduction to Continuous Integration (Cont.)
CI Pipeline
Introduction to Continuous Integration (Cont.)
Source Code Repository
• Source code management systems are not only for source code, but also for:
– Tests
– Build Scripts
– Build Tools
– Configuration scripts
– Documentation
Introduction to Continuous Integration (Cont.)
Automated Build Process
• An automated build process should be able to build the application completely from
source
• Ensure developers leverage a consistent development environment
Introduction to Continuous Integration (Cont.)
Automated Test Suite
• Unit Tests
• Integration Tests
• Code Coverage
• Code Standards
Introduction to Continuous Integration (Cont.)
Build Servers
• Popular build systems
– Jenkins
– Travis CI
• Automated builds at defined times, after every commit, when a Pull Request is
opened
• Ensure that dependencies are maintained. Code compiles and tests pass.
Introduction to Continuous Integration (Cont.)
Benefits
• Improved code quality
• Continuous testing — early and often
• Reduce risks that are associated to cost, schedule, and budget
Travis CI
Hosted continuous integration service that is used to test projects that are
hosted on GitHub — [Link]
Travis CI (Cont.)
• Travis Configuration File ---

• .[Link] language: python


• Stored in root of your GitHub project python:
- "2.7"
install:
- git clone
[Link]
- cd acitoolkit
- python [Link] install
- pip install ansible==1.9.2
script:
- python [Link]
- python check_neighbors.py
Configuration Management and
Automation Tools
Network Operations
Configuration Management
• Automate the provisioning and deployment of applications and infrastructure
• No knowledge of programming required
• Leverages software development practices for deployments:
– Version Control
– Design Patterns
– Testing
• Common tools: Puppet, Ansible, Chef, and SaltStack
Configuration Management (Cont.)
Ansible Overview
• Acquired by Red Hat
• IT Automation Framework
• Agent-less
• Leverages YAML to create Ansible Playbooks
• Free version
• Ansible Tower
• Supports IOS, IOS-XR and NXOS
Ansible Overview (Cont.)
Install Ansible
• Latest Releases Via Apt (Ubuntu)

$ sudo apt-get install software-properties-common


$ sudo apt-add-repository ppa:ansible/ansible
$ sudo apt-get update
$ sudo apt-get install ansible

• Latest Releases Via Pip

$ sudo easy_install pip


$ sudo pip install ansible
Ansible Overview (Cont.)
How Ansible Works
• Control Host
• Connects to device
– SSH or APIs
• Execute Python code (modules)
– On the control host
• Returns JSON object per task
Ansible Overview (Cont.)
---
Ansible components
• Inventory
- name: manage IOSXE devices
• Playbooks hosts: iosxe
• Plays
tasks:
• Tasks - name: show version
ios_command:
• Modules commands:
• Variables - show version
username: "{{ username }}"
password: "{{ password }}"
host: "{{ inventory_hostname }}"
Ansible Overview (Cont.)
Inventory
[all:vars]
• Target devices
username=cisco
• IPs or FQDNs password=cisco
• Groups
[nxos]
• Support variables definition nxosv

[iosxr]
xrv

[iosxe]
csr1kv
Ansible Overview (Cont.)
Playbook
• A file that contains the
instruction set on tasks that will
be automated, orchestrated,
and the like.
• Uses [Link] as file name for
“main” playbook
• YAML format
Ansible Overview (Cont.)
Plays
• Playbook that is comprised of
plays
• Plays begin with a hyphen “-” at
leftmost position
• name:
– Arbitrary description of the play
that will display on the screen
when the play is executed
• hosts:
– Required and denotes which
hosts or machines the play will
be executed against
Ansible Overview (Cont.)
Tasks
• Individual tasks make up a Play
• Tasks are executed on the
hosts that are defined in the
play definition
• Within each task:
– name:
• Optional, arbitrary description
of the task that will display on
the screen when the task is
executed
– ios_command:
• Specific tasks that perform a
single function
Ansible Overview (Cont.)
Modules & Variables
• Modules automate specific
tasks
– Apply configurations
– Configure VLANs
Ansible Overview (Cont.)
Module Documentation – ios_command
• ios_command - Run arbitrary commands on ios devices
• Synopsis – Sends arbitrary commands to an ios node and returns the results read
from the device
parameter Required Comments

commands Yes List of commands to send to the remote ios device over the configured
provider.
interval No Configures the interval in seconds to wait between retries of the
command.
retries No Specifies the number of retries a command should by tried before it is
considered failed.
waitfor No List of conditions to evaluate against the output of the command.

Note: not all parameters are shown — [Link]


Ansible Overview (Cont.)
Module Documentation – ios_command (Cont.)

- name: show ip interface


ios_command:
commands:
- show ip interface brief
username: "{{ username }}"
password: "{{ password }}"
host: "{{ inventory_hostname }}“
Ansible Overview (Cont.)
Base Directory Structure
Ansible Base Modules
• Modules that are supported across several network operating systems
• IOS, NXOS, IOS-XR support:

• *_command
• *_config
Ansible Base Modules (Cont.)
- ios_command:
ios_command commands:
• Run commands on Cisco IOS - show version
• Params username: "{{ username }}"
password: "{{ password }}"
– commands host: "{{ inventory_hostname }}"
– wait_for
– retries
Playbook:
– interval test-ios_command.yml
Ansible Base Modules (Cont.)
$ ansible-playbook -i hosts test-ios_command.yml -v
PLAY [testing ios_command] *****************************************************

TASK [show version] ************************************************************


ok: [csr1kv] => {"changed": false, "stdout": ["Cisco IOS XE Software, Version
BLD_V163_THROTTLE_LATEST_20160624_090103_V16_3_0_241\nCisco IOS Software [Denali],
CSR1000V Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Experimental Version
16.3(20160624:092502) [v163_throttle-BLD-BLD_V163_THROTTLE_LATEST_20160624_090103
........
........
PLAY RECAP *********************************************************************
csr1kv : ok=1 changed=0 unreachable=0 failed=0
Ansible Base Modules (Cont.)
ios_config • Params (cont.)
• Manage Cisco IOS config sections – after
• Params – match
– commands – replace
– parents – update_config
– src – backup_config
– dest
– append
– before
Ansible Base Modules (Cont.)
- name: configure acl test
ios_config:
commands:
- 10 permit ip host [Link] any log
- 20 permit ip host [Link] any log
- 30 permit ip host [Link] any log
- 40 permit ip host [Link] any log
- 50 permit ip host [Link] any log
parents: ['ip access-list extended test']
before: ['no ip access-list extended test']
match: exact
replace: block
username: "{{ username }}"
password: "{{ password }}"
host: "{{ inventory_hostname }}"
Ansible Base Modules (Cont.)
$ ansible-playbook -i hosts test-ios_config.yml

PLAY [ios_config testing] ******************************************************

TASK [configure acl test] ******************************************************


changed: [csr1kv]

PLAY RECAP *********************************************************************


csr1kv : ok=1 changed=1 unreachable=0 failed=0
Ansible Base Modules (Cont.)
• Register - name: Ensure proper OS version is present on
device
– Stores task results into a hosts: nxos
variable connection: local
• Assert tasks:
– Boolean tests - name: show version
nxos_command:
commands:
- show version
username: "{{ username }}"
password: "{{ password }}"
host: "{{ inventory_hostname }}"
register: output

- assert:
that:
- "'7.3(1)D1(1)' in output['stdout'][0]"
Ansible Base Modules (Cont.)
• Register - name: Ensure proper OS version is present on
device
– Stores task results into a hosts: nxos
variable connection: local
• Debug tasks:
– Prints variables - name: show version
nxos_command:
commands:
- show version
username: "{{ username }}"
password: "{{ password }}"
host: "{{ inventory_hostname }}"
register: output

- debug: var=output
Ansible Base Modules (Cont.)
$ ansible-playbook -i hosts test-nxos_command.yml

PLAY [Print output] *******************

TASK [debug] *******************************************************************


ok: [nxosv] => {
"output": {
"changed": false,
"response": [
"\nCisco Nexus Operating System (NX-OS) Software\nTAC support:
[Link]
[Link]
CopyrOMITTEDOUTPUT
]
}
}
Discovery 35: Compliance Checks
with Ansible
Topology
NXOS Features Modules
• Configure a specific feature or perform a certain operation
– Routing protocols
– VXLAN/EVPN
– FHRP
– Link aggregation
– Interface configuration
– VPC
– VLANs, interfaces, and the like.
• Better abstractions
• Idempotent
• Supports Nexus Application Programming Interface (NX-API) and CLI
NXOS Features Modules (Cont.)
• nxos_bgp • nxos_hsrp
• nxos_bgp_af • nxos_interface
• nxos_bgp_neighbor • nxos_interface_ospf
• nxos_bgp_neighbor_af • nxos_ip_interface
• nxos_evpn_global • nxos_ospf
• nxos_evpn_vni • nxos_ospf_vrf
• nxos_facts • nxos_overlay_global
• nxos_feature • nxos_pim
NXOS Features Modules (Cont.)
• nxos_pim_rp_address • nxos_vpc_interface
• nxos_ping • nxos_vrf
• nxos_portchannel • nxos_vrf_af
• nxos_static_route • nxos_vrf_interface
• nxos_switchport • nxos_vrrp
• nxos_vlan • nxos_vxlan_vtep
• nxos_vpc • nxos_vxlan_vtep_vni
NXOS Features Modules (Cont.)
- name: configure ethernet2/1 interface
nxos_interface nxos_interface:
• Manages physical attributes of interface: ethernet2/1
interfaces admin_state: up
mode: layer3
• Parameters description: "Configured with
– interface Ansible"
state: present
– admin_state
username: "{{ username }}"
– description password: "{{ password }}"
– mode host: "{{ inventory_hostname }}"

– state
NXOS Features Modules (Cont.)
- name: configure ethernet2/1 ip
nxos_ip_interface address
• Manages Layer 3 attributes of nxos_ip_interface:
interfaces interface: ethernet2/1
addr: "[Link]"
mask: 30
state: present
username: "{{ username }}"
password: "{{ password }}"
host: "{{ inventory_hostname }}"
NXOS Features Modules (Cont.)
Example: Assigning Native VLAN on NXOS
• Ensure VLAN 113 exists
– nxos_vlan
• Ensure Ethernet2/1 is L2
– nxos_interface
• Configure Access Port
– nxos_switchport
NXOS Features Modules (Cont.)
- name: ENSURE VLAN EXISTS
nxos_vlan:
vlan_id=113 - name: ENSURE INTERFACE IS CONFIGURED FOR V113
name=native nxos_switchport:
vlan_state=active interface=eth2/1
host={{ mode=access
inventory_hostname }} access_vlan=113
username={{ username }} host={{ inventory_hostname }}
password={{ password }} username={{ username }}
password={{ password }}
- name: ENSURE INTERFACE IS
L2
nxos_interface:
interface=eth2/1
mode=layer2
host={{
inventory_hostname }}
username={{ username }}
password={{ password }}
NXOS Features Modules (Cont.)
Example: Assigning Native VLAN on NXOS
• Run the playbook
$ ansible-playbook -i hosts test_nxos.yml

PLAY [configure nxos device] ***************************************************

TASK [CREATE VLAN] *************************************************************


changed: [nxosv]

TASK [ENSURE INTERFACE IS L2] **************************************************


changed: [nxosv]

TASK [CONFIGURE TRUNK] *********************************************************


changed: [nxosv]
NXOS Features Modules (Cont.)
Example: Assigning Native VLAN on NXOS (continued)
• Idempotency check
$ ansible-playbook -i hosts test_nxos.yml

PLAY [configure nxos device] ***************************************************

TASK [CREATE VLAN] *************************************************************


ok: [nxosv]

TASK [ENSURE INTERFACE IS L2] **************************************************


ok: [nxosv]

TASK [CONFIGURE TRUNK] *********************************************************


ok: [nxosv]
Discovery 36: Tenant Provisioning
with Ansible
Topology

You might also like