0% found this document useful (0 votes)
19 views123 pages

Yang

Uploaded by

pppeter129
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)
19 views123 pages

Yang

Uploaded by

pppeter129
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
You are on page 1/ 123

Introduction to Model Driven

Programmability
Breaking down YANG, NETCONF, and
RESTCONF
Hank Preston, Principal Engineer, NetDevOps Guy, ccie 38336 R/S
@hfpreston

BRKDEV-1368
Cisco Webex Teams

Questions?
Use Cisco Webex Teams to chat
with the speaker after the session

How
1 Find this session in the Cisco Events Mobile App
2 Click “Join the Discussion”
3 Install Webex Teams or go directly to the team space
4 Enter messages/questions in the team space

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 3
Agenda

• The Road to Model Driven Programmability


• Introduction to YANG Data Models
• Introduction to NETCONF
• Introduction to RESTCONF
• Conclusion and Q/A

Note: All code samples referenced in this presentation are available at


https://github.com/CiscoDevNet/BRKDEV-1368

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 4
The Road to Model Driven
Programmability
The Network is No Longer Isolated

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 6
What about SNMP?

SNMP works • Typical config: SNMPv2 read-


only community strings
“reasonably well • Typical usage: interface statistics

for device queries and traps


• Empirical Observation: SNMP is
monitoring” not used for configuration
• Lack of Writeable MIBs
RFC 3535: Overview of the 2002 IAB
• Security Concerns
Network Management Workshop – 2003 • Difficult to Replay/Rollback
https://tools.ietf.org/html/rfc3535
• Special Applications

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 7
RFC 3535: What is Needed?
What do
we need?
• A programmatic interface for device
configuration
• Separation of Configuration and State
Data
• Ability to configure "services" NOT
"devices"
• Integrated error checking and recovery

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 8
Model Driven Programmability

• NETCONF – 2006 – RFC 4741


(RFC 6241 in 2011)
• YANG – 2010 – RFC 6020
• RESTCONF – 2017 – RFC 8040
• gRPC – 2015 – OpenSource project by
Google
• Not covered in today’s session

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 9
Transport (Protocol) vs Data (Model)

• NETCONF • YANG
• RESTCONF
• gRPC

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 10
What is YANG?
Three Meanings of “YANG”

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 12
YANG Modeling Language

module ietf-interfaces {
• Module that is a self-contained import ietf-yang-types {
top-level hierarchy of nodes prefix yang;
}
• Uses containers to group related container interfaces {
list interface {
nodes key "name";
leaf name {
• Lists to identify nodes that are type string;
}
stored in sequence leaf enabled {
type boolean;
• Each individual attribute of a node default "true";
is represented by a leaf }
}

• Every leaf must have an


associated type
Example edited for simplicity and brevity

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 13
What is a Data Model?

• Person
• Gender - male, female, other
• Height - Feet/Inches or Meters
A data model is simply a well • Weight - Pounds or Kilos
understood and agreed upon method to
describe "something". As an example, • Hair Color - Brown, Blond, Black,
consider this simple "data model" for a Red, other
person. • Eye Color - Brown, Blue, Green,
Hazel, other

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 14
What might a YANG Data Model describe?

Device Data Models Service Data Model


- Interface - L3 MPLS VPN
- VLAN - MP-BGP
- Device ACL - Network ACL
- Tunnel - EVPN
- OSPF - System Management
- etc - Network Faults
- etc

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 15
Working with YANG
Data Models
Where do Models Come From?

Industry Vendor
Standard Specific

• Standard definition • Vendor definition


(IETF, ITU, OpenConfig, etc.) (i.e. Cisco)

• Compliant with standard • Unique to Vendor Platforms


ietf-diffserv-policy.yang cisco-memory-stats.yang
ietf-diffserv-classifer.yang cisco-flow-monitor
ietf-diffserv-target.yang cisco-qos-action-qlimit-cfg

https://github.com/YangModels/yang

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 17
What is OpenConfig?

Models Designed by Operators for


Operators

“OpenConfig’s initial focus is on


compiling a consistent set of vendor-
neutral data models based on actual
operational needs from use cases and
requirements from multiple network
operators.”

OpenConfig FAQ:
www.openconfig.com

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 18
What is OpenConfig?

Models Designed by Operators for


Operators
• Focused on creating vendor-neutral
data models written in YANG
• Models combine both configuration
and operational data
• Model coverage still limited with an
active development community
• Support from multiple routing vendors
(e.g. Cisco, Juniper, Arista)
• Vendor exceptions carried a deviations

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 19
Where to get the Models?

• For YANG modules from standard


organizations such as the IETF, open
source such as Open Daylight or
vendor specific modules”
• https://github.com/YangModels/yang

• For OpenConfig models


• https://github.com/openconfig/public

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 20
YANG Data Models

The model can be displayed and represented in any number of


formats depending on needs at the time. Some options include:
• YANG Language
• Clear Text
• XML
• JSON
• HTML/JavaScript

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 21
Working with YANG Models

DevNet$ pyang –f tree ietf-interfaces.yang

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}?

Example output edited for simplicity and brevity

BRKDEV-1368/yang/ietf-interfaces.yang

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 22
Using pyang
module: ietf-interfaces Module Name
+--rw interfaces
| +--rw interface* [name] Key

container
| +--rw name string Leaf
| +--rw description? string

list
• Python YANG Library | +--rw type identityref
| +--rw enabled? Optional boolean
• Validate and display YANG files | +--rw link-up-down-trap-enable? enumeration {if-mib}?
+--ro interfaces-state
• Many formats for display +--ro interface* [name]
+--ro name string
• Text: tree +--ro type identityref
+--ro admin-status enumeration {if-mib}?
• HTML: jstree
+--ro oper-status enumeration

container
+--ro last-change? yang:date-and-time Data Type

list
+--ro if-index int32 {if-mib}?
+--ro phys-address? yang:phys-address
+--ro higher-layer-if* interface-state-ref
+--ro lower-layer-if* interface-state-ref
Read
+--ro speed? yang:gauge64
Only
+--ro statistics
+--ro discontinuity-time yang:date-and-time
+--ro in-octets? yang:counter64
[OUTPUT REMOVED]

Example edited for simplicity and brevity


BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 23
Augmentation and Deviations in YANG

Standard Model

Standard Model with


Augmentation
Standard Model with
Deviation
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 24
Network Device
Data in YANG
Actual Device Data Modeled in YANG

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 26
Use NETCONF to Retrieve ietf-interfaces data

from device_info import ios_xe1


• NETCONF details covered in another from ncclient import manager
import xml.dom.minidom
session
# NETCONF filter to use
• ncclient provides a Python client for netconf_filter = open("filter-ietf-interfaces.xml").read()
NETCONF
• Using built-in library to print reply if __name__ == '__main__':
• xml.dom.minidom with manager.connect(host=ios_xe1["address"],
port=ios_xe1["port"],
username=ios_xe1["username"],
password=ios_xe1["password"],
hostkey_verify=False) as m:

netconf_reply = m.get_config("running", netconf_filter)


interfaces = xml.dom.minidom.parseString(netconf_reply.xml)
interfaces = interfaces.getElementsByTagName("interfaces")
print(interfaces[0].toprettyxml())

BRKDEV-1368/yang/device_info.py
BRKDEV-1368/yang/example1.py
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 27
Use NETCONF to Retrieve ietf-interfaces data
DevNet$ python example1.py

<interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces"> Namespace = Capability = Model


<interface>
<name>GigabitEthernet1</name> Leaf
interface node

<description>DON'T TOUCH ME</description>


<type xmlns:ianaift="urn:ietf:params:xml:ns:yang:iana-if-type">ianaift:ethernetCsmacd</type>
interfaces container

<enabled>true</enabled>
<ipv4 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
<address>
<ip>10.10.10.48</ip>
<netmask>255.255.255.0</netmask>
</address>
</ipv4>
<ipv6 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip"/>
</interface>
<interface>
<name>GigabitEthernet2</name>
<type xmlns:ianaift="urn:ietf:params:xml:ns:yang:iana-if-type">ianaift:ethernetCsmacd</type>
<enabled>true</enabled>
<ipv4 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip"/>
<ipv6 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip"/>
</interface>
</interfaces>
BRKDEV-1368/yang/device_info.py
BRKDEV-1368/yang/example1.py
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 28
YANG Model Augmentation
<interface>
<name>GigabitEthernet2</name>
(venv) $pyang -f tree ietf-interfaces.yang
<description>**THIS IS INTERFACE 2**</description>
module: ietf-interfaces
<type>ianaift:ethernetCsmacd</type>
+--rw interfaces
<enabled>true</enabled>
| +--rw interface* [name]
<ipv4 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
| +--rw name string
<address>
| +--rw description? string
<ip>172.16.20.1</ip>
| +--rw type identityref
<netmask>255.255.255.0</netmask>
| +--rw enabled? boolean
</address>
| +--rw link-up-down-trap-enable? enumeration {if-mib}?
</ipv4>
</interface>

Where is the <ipv4> leaf in the model?


module: ietf-ip
augment /if:interfaces/if:interface:
+--rw ipv4!
| +--rw enabled? boolean
| +--rw forwarding?
| +--rw mtu?
boolean
uint16
The YANG model
| +--rw address* [ip] states what base
model it is
| | +--rw ip inet:ipv4-address-no-zone
| | +--rw (subnet)
| |
| |
+--:(prefix-length)
| +--rw prefix-length? uint8 augmenting.
| | +--:(netmask)
| | +--rw netmask? yang:dotted-quad {ipv4-non-contiguous-netmasks}?

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 30
YANG Model Deviations
module: ietf-ip <interfaces-state xmlns="ietf-interfaces">
augment /if:interfaces-state/if:interface: <interface>
+--ro ipv4! <name>GigabitEthernet1</name>
| +--ro forwarding? boolean <type>ianaift:ethernetCsmacd</type>
| +--ro mtu? uint16 <admin-status>up</admin-status>
| +--ro address* [ip] <oper-status>up</oper-status>
| | +--ro ip inet:ipv4-address-no-zone <last-change>2017-11-14T13:33:</last-change>
| | +--ro (subnet)? <if-index>0</if-index>
| | | +--:(prefix-length) <phys-address>00:50:56:bb:c9:2c</phys-address>
| | | | +--ro prefix-length? uint8 <speed>1024000</speed>
| | | +--:(netmask) <statistics>
| | | +--ro netmask? yang:dotted-quad <discontinuity-time>..</discontinuity-time>
| | +--ro origin? ip-address-origin <in-octets>41705747838</in-octets>
<in-unicast-pkts>129128494</in-unicast-pkts>
<in-broadcast-pkts>0</in-broadcast-pkts>
Where is the <ipv4> leaf in the device data? <in-multicast-pkts>0</in-multicast-pkts>
<in-discards>0</in-discards>
<in-errors>0</in-errors>
<in-unknown-protos>0</in-unknown-protos>
<out-octets>168135978</out-octets>
<out-unicast-pkts>414310</out-unicast-pkts>
<out-broadcast-pkts>0</out-broadcast-pkts>
<out-multicast-pkts>0</out-multicast-pkts>
<out-discards>0</out-discards>
<out-errors>0</out-errors>
</statistics>
</interface>
</interfaces-state>

Outputs modified for screen display

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 31
YANG Model Deviations
module: ietf-ip <interfaces-state xmlns="ietf-interfaces">
augment /if:interfaces-state/if:interface: <interface>
+--ro ipv4! <name>GigabitEthernet1</name>
| +--ro forwarding? boolean <type>ianaift:ethernetCsmacd</type>
| +--ro mtu? uint16 <admin-status>up</admin-status>
| +--ro address* [ip] <oper-status>up</oper-status>
| | +--ro ip inet:ipv4-address-no-zone <last-change>2017-11-14T13:33:</last-change>
| | +--ro (subnet)? <if-index>0</if-index>
| | | +--:(prefix-length) <phys-address>00:50:56:bb:c9:2c</phys-address>
| | | | +--ro prefix-length? uint8 <speed>1024000</speed>
| | | +--:(netmask) <statistics>
| | | +--ro netmask? yang:dotted-quad <discontinuity-time>..</discontinuity-time>
| | +--ro origin? ip-address-origin <in-octets>41705747838</in-octets>
<in-unicast-pkts>129128494</in-unicast-pkts>
<in-broadcast-pkts>0</in-broadcast-pkts>
Where is the <ipv4> leaf in the device data? <in-multicast-pkts>0</in-multicast-pkts>
module cisco-xe-ietf-ip-deviation { <in-discards>0</in-discards>
namespace <in-errors>0</in-errors>
"http://cisco.com/ns/cisco-xe-ietf-ip-deviation"; <in-unknown-protos>0</in-unknown-protos>
. <out-octets>168135978</out-octets>
. <out-unicast-pkts>414310</out-unicast-pkts>
deviation /if:interfaces-state/if:interface/ip:ipv4{ <out-broadcast-pkts>0</out-broadcast-pkts>
deviate not-supported; <out-multicast-pkts>0</out-multicast-pkts>
description "Not supported in IOS-XE"; <out-discards>0</out-discards>
} <out-errors>0</out-errors>
} </statistics>
</interface>
</interfaces-state>
YANG deviations allow for vendors to modify from
standard models when required. Outputs modified for screen display

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 32
YANG Summary
YANG Summary

• YANG is a Data Modeling Language


• YANG Modules are constructed to create standard data models for network data
• YANG Data sent to or from a network device will be formatted in either XML or JSON
depending on the protocol (ex: NETCONF or RESTCONF)

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 34
Understanding
NETCONF
Introducing the NETCONF Protocol

Some key details:


• Initial standard in 2006
with RFC4741
• Latest standard
is RFC6241 in 2011
• Does NOT explicitly define
content

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 36
NETCONF Protocol Stack

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 37
Transport - SSH
$ ssh [email protected] -p 830 -s netconf
[email protected]'s password: SSH Login
<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:netconf:capability:candidate:1.0</capability>
<capability>urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring</capability>
Server (Agent)
<capability>urn:ietf:params:xml:ns:yang:ietf-interfaces</capability> sends hello
[output omitted and edited for clarity]
</capabilities>
<session-id>19150</session-id></hello>]]>]]>

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


<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
Client (Manager)
<capabilities>
<capability>urn:ietf:params:netconf:base:1.0</capability> sends hello
</capabilities> Example edited for simplicity and brevity
</hello>]]>]]>

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 38
Transport - SSH
$ ssh [email protected] -p 830 -s netconf
[email protected]'s password: SSH Login
<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:netconf:capability:candidate:1.0</capability>
<capability>urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring</capability>
Server (Agent)
<capability>urn:ietf:params:xml:ns:yang:ietf-interfaces</capability> sends hello
Don’t NETCONF Like this!
[output omitted and edited for clarity]
</capabilities>
<session-id>19150</session-id></hello>]]>]]>

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


<hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"> Client (Manager)
<capabilities> sends hello
<capability>urn:ietf:params:netconf:base:1.0</capability>
</capabilities> Example edited for simplicity and brevity
</hello>]]>]]>

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 39
Messages - Remote Procedure Call (RPC)

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 40
Operations - NETCONF Actions

Operation Description
<get> Retrieve running configuration and device state information
<get-config> Retrieve all or part of specified configuration data store
<edit-config> Loads all or part of a configuration to the specified configuration
data store
<copy-config> Replace an entire configuration data store with another
<delete-config> Delete a configuration data store
<commit> Copy candidate data store to running data store
<lock> / <unlock> Lock or unlock the entire configuration data store system
<close-session> Graceful termination of NETCONF session
<kill-session> Forced termination of NETCONF session

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 41
Additional Operations

• The IETF isn’t able to anticipate every


use case from every vendor.
• Additional operations can be defined write
by the vendor mem? commit
• Support extended through RPC call to ?
vendor-specific YANG model
copy
run
start?

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 42
NETCONF Data Stores

Data Store Key Points


• Entire or partial configuration
• "running" is the only mandatory data
store
• Not all data stores are writeable
• A "URL" data store is supported by
IOS to enable <config-copy>
• Every NETCONF message must
target a data store

result = m.get_config('running')

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 43
NETCONF Communications

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 44
NETCONF in Code
with Python
NETCONF and Python: ncclient

• Full NETCONF Manager


from ncclient import manager
implementation in Python
• https://ncclient.readthedocs.io
m = manager.connect(host="192.168.0.1",
• Simplifies connection and
port=830,
communication. username="admin",
• Deals in raw XML password="cisco123",
hostkey_verify=False
)

m.close_session()

From: http://ncclient.readthedocs.io/en/latest/

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 46
Saying <hello> with Python and ncclient

• example1.py: Saying
<hello> from device_info import ios_xe1
from ncclient import manager

• manager.connect() if __name__ == '__main__':


with manager.connect(host=ios_xe1["address"],
opens NETCONF session port=ios_xe1["port"],
username=ios_xe1["username"],
with device password=ios_xe1["password"],
hostkey_verify=False) as m:
• Parameters: host & port, user &
print("Here are the NETCONF Capabilities")
password for capability in m.server_capabilities:
print(capability)
• hostkey_verify=False
Trust cert
• Stores capabilities
BRKDEV-1368/netconf/device_info.py
BRKDEV-1368/netconf/example1.py

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 47
Understanding the Capabilities List

DevNet$ python example1.py


Here are the NETCONF Capabilities

urn:ietf:params:netconf:base:1.0
urn:ietf:params:netconf:base:1.1
.
urn:ietf:params:xml:ns:yang:ietf-interfaces?module=ietf-interfaces&revision=2014-05-08&features=pre-
provisioning,if-mib,arbitrary-names&deviations=ietf-ip-devs

http://cisco.com/ns/ietf-ip/devs?module=ietf-ip-devs&revision=2016-08-10
Example edited for simplicity and brevity
http://cisco.com/ns/yang/Cisco-IOS-XE-native?module=Cisco-IOS-XE-native&revision=2017-02-07

Two General Types


• Base NETCONF capabilities
• Data Models Supported

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 48
Understanding the Capabilities List

urn:ietf:params:xml:ns:yang:ietf-interfaces
? module=ietf-interfaces
& revision=2014-05-08
& features=pre-provisioning,if-mib,arbitrary-names
& deviations=ietf-ip-devs
.
http://cisco.com/ns/ietf-ip/devs
? module=ietf-ip-devs
& revision=2016-08-10

Data Model Details Example edited for simplicity and brevity

• Model URI
• Module Name and Revision Date
• Protocol Features
• Deviations – Another model that modifies this one
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 49
Automate Your Network
with NETCONF
Getting Interface Details with XML Filter

from device_info import ios_xe1


• example2.py: Retrieving info with from ncclient import manager
import xmltodict
ncclient # NETCONF filter to use
netconf_filter = open("filter-ietf-interfaces.xml").read()

• Send <get> to retrieve config and if __name__ == '__main__':

state data
with manager.connect(host=ios_xe1["address"],
port=ios_xe1["port"],
username=ios_xe1["username"],
password=ios_xe1["password"],
• Process and leverage XML within hostkey_verify=False) as m:

Python # Get Configuration and State Info for Interface


netconf_reply = m.get(netconf_filter)

# Process the XML and store in useful dictionaries


• Report back current state of intf_details = xmltodict.parse(netconf_reply.xml)["rpc-reply"]["data"]
intf_config = intf_details["interfaces"]["interface"]
interface intf_info = intf_details["interfaces-state"]["interface"]

print("")
print("Interface Details:")
print(" Name: {}".format(intf_config["name"]))
print(" Description: {}".format(intf_config["description"]))
print(" Type: {}".format(intf_config["type"]["#text"]))
print(" MAC Address: {}".format(intf_info["phys-address"]))
print(" Packets Input: {}".format(intf_info["statistics"]["in-unicast-pkts"]))
print(" Packets Output: {}".format(intf_info["statistics"]["out-unicast-pkts"]))

BRKDEV-1368/netconf/example2.py
BRKDEV-1368/netconf/filter-ietf-interfaces.xml
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 51
Getting Interface Details with XML Filter

• example2.py: Retrieving info with


ncclient
• Send <get> to retrieve config and <filter>
<interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">
state data <interface>
<name>GigabitEthernet2</name>
</interface>
• Process and leverage XML within </interfaces>
<interfaces-state xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">
Python <interface>
<name>GigabitEthernet2</name>
</interface>
• Report back current state of </interfaces-state>
</filter>
interface

BRKDEV-1368/netconf/example2.py
BRKDEV-1368/netconf/filter-ietf-interfaces.xml
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 52
Getting Interface Details with XML Filter

from device_info import ios_xe1


• example2.py: Retrieving info with from ncclient import manager
import xmltodict
ncclient # NETCONF filter to use
netconf_filter = open("filter-ietf-interfaces.xml").read()

• Send <get> to retrieve config and if __name__ == '__main__':

state data
with manager.connect(host=ios_xe1["address"],
port=ios_xe1["port"],
username=ios_xe1["username"],
password=ios_xe1["password"],
• Process and leverage XML within hostkey_verify=False) as m:

Python # Get Configuration and State Info for Interface


netconf_reply = m.get(netconf_filter)

# Process the XML and store in useful dictionaries


• Report back current state of intf_details = xmltodict.parse(netconf_reply.xml)["rpc-reply"]["data"]
intf_config = intf_details["interfaces"]["interface"]
interface intf_info = intf_details["interfaces-state"]["interface"]

print("")
print("Interface Details:")
print(" Name: {}".format(intf_config["name"]))
print(" Description: {}".format(intf_config["description"]))
print(" Type: {}".format(intf_config["type"]["#text"]))
print(" MAC Address: {}".format(intf_info["phys-address"]))
print(" Packets Input: {}".format(intf_info["statistics"]["in-unicast-pkts"]))
print(" Packets Output: {}".format(intf_info["statistics"]["out-unicast-pkts"]))

BRKDEV-1368/netconf/example2.py
BRKDEV-1368/netconf/filter-ietf-interfaces.xml
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 53
Getting Interface Details

DevNet$ python example2.py

Interface Details:
Name: GigabitEthernet2
Description: DON'T TOUCH ME
Type: ianaift:ethernetCsmacd
MAC Address: 00:50:56:bb:74:d5
Packets Input: 592268689
Packets Output: 21839

BRKDEV-1368/netconf/example2.py
BRKDEV-1368/netconf/filter-ietf-interfaces.xml
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 54
Getting Interface Details with XPath

• example3.py: Retrieving info from device_info import ios_xe1


from ncclient import manager
import xmltodict
with ncclient and XPath if __name__ == '__main__':
with manager.connect(host=ios_xe1["address"],

• Send <get> to retrieve and port=ios_xe1["port"],


username=ios_xe1["username"],
password=ios_xe1["password"],
state data hostkey_verify=False) as m:

# Get Configuration and State Info for Interface

Process the data


netconf_reply = m.get(filter=('xpath' ,
• "/interfaces-state/interface[name='GigabitEthernet1']"
"/statistics/out-unicast-pkts"))

• Report back current state of intf_details = xmltodict.parse(netconf_reply.xml)["rpc-reply"]["data"]


intf_info = intf_details["interfaces-state"]["interface"]

interface print("")
print("Interface Details:")
print(" Name: {}".format(intf_info["name"]))
print(" Packets Output: {}".format(intf_info["statistics"]["out-unicast-pkts"]))
DevNet$python example3.py

Interface Details:
Name: GigabitEthernet1
Packets Output: 415200
BRKDEV-1368/netconf/example3.py
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 55
Configuring Interface Details

from device_info import ios_xe1


from ncclient import manager
• example4.py: Editing # NETCONF Config Template to use
configuration with ncclient netconf_template = open("config-temp-ietf-interfaces.xml").read()

if __name__ == '__main__':

Constructing XML Config


# Build the XML Configuration to Send
• netconf_payload = netconf_template.format(int_name="GigabitEthernet2",
int_desc="Configured by NETCONF",
Payload for NETCONF ip_address="10.255.255.1",
subnet_mask="255.255.255.0"
)
• Sending <edit-config> print("Configuration Payload:")
print("----------------------")
operation with ncclient print(netconf_payload)

with manager.connect(host=ios_xe1["address"], port=ios_xe1["port"],

• Verify result username=ios_xe1["username"],


password=ios_xe1["password"],
hostkey_verify=False) as m:

# Send NETCONF <edit-config>


netconf_reply = m.edit_config(netconf_payload, target="running")

# Print the NETCONF Reply


print(netconf_reply)

BRKDEV-1368/netconf/config-temp-ietf-interfaces.xml
BRKDEV-1368/netconf/example4.py
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 56
Configuring Interface Details
config-temp-ietf-interfaces.xml
<config>
<interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">

• example4.py: Editing <interface>


<name>{int_name}</name>

configuration with ncclient


<description>{int_desc}</description>
<type xmlns:ianaift="urn:ietf:params:xml:ns:yang:iana-if-type">ianaift:ethernetCsmacd</type>
<enabled>true</enabled>
<ipv4 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
<address>
• Constructing XML Config <ip>{ip_address}</ip>
<netmask>{subnet_mask}</netmask>

Payload for NETCONF </address>


</ipv4>
</interface>
</interfaces>

• Sending <edit-config> </config>

operation with ncclient if __name__ == '__main__':


# Build the XML Configuration to Send
• Verify result netconf_payload = netconf_template.format(int_name="GigabitEthernet2",
int_desc="Configured by NETCONF",
ip_address="10.255.255.1",
subnet_mask="255.255.255.0"
)
print("Configuration Payload:")
print("----------------------")
print(netconf_payload)

BRKDEV-1368/netconf/config-temp-ietf-interfaces.xml
BRKDEV-1368/netconf/example3.py
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 57
Configuring Interface Details

from device_info import ios_xe1


from ncclient import manager
• example4.py: Editing configuration # NETCONF Config Template to use
with ncclient netconf_template = open("config-temp-ietf-interfaces.xml").read()

if __name__ == '__main__':
• Constructing XML Config Payload # Build the XML Configuration to Send
netconf_payload = netconf_template.format(int_name="GigabitEthernet2",
for NETCONF int_desc="Configured by NETCONF",
ip_address="10.255.255.1",
subnet_mask="255.255.255.0"
• Sending <edit-config> operation print("Configuration Payload:")
)

with ncclient print("----------------------")


print(netconf_payload)

• Verify result with manager.connect(host=ios_xe1["address"], port=ios_xe1["port"],


username=ios_xe1["username"],
password=ios_xe1["password"],
hostkey_verify=False) as m:

# Send NETCONF <edit-config>


netconf_reply = m.edit_config(netconf_payload, target="running")

# Print the NETCONF Reply


print(netconf_reply)

BRKDEV-1368/netconf/config-temp-ietf-interfaces.xml
BRKDEV-1368/netconf/example4.py
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 58
Configuring Interface Details
DevNet$ python -i example4.py
Configuration Payload:
----------------------
<config>
<interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">
<interface>
<name>GigabitEthernet2</name>
<description>Configured by NETCONF</description>
<type xmlns:ianaift="urn:ietf:params:xml:ns:yang:iana-if-type">
ianaift:ethernetCsmacd
</type>
<enabled>true</enabled>
<ipv4 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
<address>
<ip>10.255.255.1</ip>
<netmask>255.255.255.0</netmask>
</address>
</ipv4>
</interface>
</interfaces>
</config>

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


<rpc-reply xmlns=”urn.." message-id=”..9784" xmlns:nc="urn..">
<ok/>
</rpc-reply>

Example edited for simplicity and brevity

BRKDEV-1368/netconf/config-temp-ietf-interfaces.xml
BRKDEV-1368/netconf/example4.py
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 59
Saving Running Configuration with ncclient

• example5.py: Save running


configuration with ncclient from device_info import ios_xe1
from ncclient import manager, xml_

• Constructing XML Config


if __name__ == '__main__':
Payload for NETCONF with manager.connect(host=ios_xe1["address"],
port=ios_xe1["port"],
username=ios_xe1["username"],

• Sending custom save password=ios_xe1["password"],


hostkey_verify=False) as m:

operation with ncclient


# Build XML Payload for the RPC
save_body = '<cisco-ia:save-config xmlns:cisco-ia="http://cisco.com/yang/cisco-ia"/>'
• Verify result
# Send the RPC to the Device
save_rpc = m.dispatch(xml_.to_ele(save_body))

# Print the NETCONF Reply


print(save_rpc)

BRKDEV-1368/netconf/example5.py
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 60
Saving Running Configuration with ncclient
<?xml version="1.0" encoding="UTF-8"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"
message-id="urn:uuid:d12c3cc5-f638-499e-9e57-c8d2402fdfeb"
xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">
<result xmlns='http://cisco.com/yang/cisco-ia'>
Save running-config successful
</result>
</rpc-reply>

BRKDEV-1368/netconf/example5.py
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 61
NETCONF
Summary
NETCONF Summary

• The elements of the NETCONF transport protocol


• How to leverage ncclient to use NETCONF in Python
• Examples retrieving and configuring data from a NETCONF Agent

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 63
Understanding
RESTCONF
RESTCONF Details

• RFC 8040 - January 2017


“an HTTP-based protocol that provides • Uses HTTPS for transport
a programmatic interface for accessing
data defined in YANG…” • Tightly coupled to the YANG
data model definitions
https://tools.ietf.org/html/rfc8040 • Provides JSON or XML data
formats

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 65
What about NETCONF?

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 66
RESTCONF Protocol Stack & Transport

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 67
Operations - HTTP CRUD

RESTCONF NETCONF
GET <get> , <get-config>
POST <edit-config> (operation="create")
PUT <edit-config> (operation="create/replace")
PATCH <edit-config> (operation="merge")
DELETE <edit-config> (operation="delete")

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 68
Content - XML or JSON

HTTP Headers RESTCONF MIME Types


• Content-Type: Specify the type of data • application/yang-data+json
being sent from the client
• application/yang-data+xml
• Accept: Specify the type of data being
requested by the client

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 69
Constructing RESTCONF URIs for Data
Resources
https://<ADDRESS>/<ROOT>/data/<[YANG MODULE:]CONTAINER>/<LEAF>[?<OPTIONS>]

• ADDRESS - Of the RESTCONF Agent


• ROOT - The main entry point for RESTCONF requests.
Discoverable at https://<ADDRESS>/.well-known/host-meta
• data - The RESTCONF API resource type for data
• The “operations” resource type used to access RPC operations available
• [YANG MODULE:]CONTAINER - The base model container being used. Providing the
module name is optional.
• LEAF - An individual element from within the container
• [?<OPTIONS>] - optional parameters that impact returned results.

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 70
URL Creation Review
https://<ADDRESS>/restconf/data/ietf-interfaces:interfaces/interface=GigabitEthernet1?depth=unbounded

module: ietf-interfaces
+--rw interfaces
| +--rw interface* [name]
| +--rw name string
| +--rw description? string
| +--rw type identityref
| +--rw enabled? boolean Options Examples:
• depth=unbounded
| +--rw link-up-down-trap-enable? enumeration {if-mib}?
Follow nested models to end. Integer also
supported
• content=[all, config, nonconfig]
Query option controls type of data returned.
• fields=expr
Key: Limit what leafs are returned
https://<ADDRESS>/<ROOT>/data>/<[YANG MODULE:]CONTAINER>/<LEAF>[?<OPTIONS>]

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 71
Using RESTCONF
with Postman
Postman: Powerful but Simple REST API Client

• Quickly test APIs in GUI


• Save APIs into Collections for reuse
• Manage multiple environments
• Auto generate code from API calls
https://www.getpostman.com

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 73
Setup Environment for RESTCONF

• Add variables for host, and credentials


• Reference anywhere with {{variable
name}} syntax

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 74
Step 1: Get YANG Modules List via RESTCONF

• GET /restconf/data/ietf-yang-library:modules-state

• Add RESTCONF Headers


• Content-Type and Accept
application/yang-data+json
(or xml)
• Configure Basic Auth with username and
password variables

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 75
Step 1: Get YANG Modules List via RESTCONF

• Send and review results

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 76
Understanding the YANG Modules List
{"ietf-yang-library:modules-state": {"module": [
{
• Data Model Details "name": "ietf-ip",
"revision": "2014-06-16",
"schema": "https://10.10.20.48:443/restconf/tailf/..",
• Model URI "namespace": "urn:ietf:params:xml:ns:yang:ietf-ip",
"feature": [
"ipv6-privacy-autoconf",
• Module Name and "ipv4-non-contiguous-netmasks"
],
Revision Date "deviation": [
{
"name": "cisco-xe-ietf-ip-deviation",
• Protocol Features }
"revision": "2016-08-10"

],
• Deviations – Another },
"conformance-type": "implement"

model that modifies {


"name": "cisco-xe-ietf-ip-deviation",
this one "revision": "2016-08-10",
"schema": "https://10.10.20.48:443/restconf/tailf/...",
"namespace": "http://cisco.com/ns/cisco-xe-ietf-ip-deviation",
"conformance-type": "implement"
}]}}

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 77
Automate Your
Network with
RESTCONF
Getting Interface Details

• GET
restconf/data/ietf-interfaces:interfaces/interface=GigabitEthernet2

• Configure Auth and Headers

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 79
Configuring Interface Details

• PUT
restconf/data/ietf-interfaces:interfaces/interface=GigabitEthernet2

• Configure Auth and Headers


• Configure Body (raw)
• Send and check status code

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 80
Configuring Interface Details - Verification

• GET
restconf/data/ietf-interfaces:interfaces/interface=GigabitEthernet2

• Configure Auth and Headers


• Check that the new config was
successful

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 81
Save Running Configuration to Startup RPC
Operation
• POST
restconf/operations/cisco-ia:save-config/

• Configure Auth and Headers

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 82
RESTCONF with
Python
Python Libraries for RESTCONF

• Treat like other “REST” and HTTP APIs


• Core Python Library
• urllib (urllib.request)

• Other HTTP Library


• Requests: http for humans

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 84
RESTCONF and HTTPS/SSL

• Per RFC8040 RESTCONF requires


HTTPS for security
• HTTPS leverages SSL/TLS
certificates to
• Encrypt data transmitted between server
and client
• Verify a sites identity

• Encryption accomplished through


Private/Public keys in Certificate
• Identity is all about “trust” and the
“signer” of a certificate

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 85
Self-Signed SSL Certificates are Common

• No problems with encryption


• “Trust” fails due to no Certificate
Authority
• Common in most of our daily lives
• Network web GUIs
• Internal corporate web sites
• Poorly managed company sites

• Knee-jerk reaction to click


“Accept” or “Proceed”

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 86
“Accepting” Self-Signed Certificates with Python
Requests
>>> import requests
• Requests (via urllib) performs >>> url = "https://ios-xe-mgmt.cisco.com:9443/.well-known/host-meta"
SSL Validation by default
>>> response = requests.get(url, auth=("root", "D_Vay!_10&"))

Traceback (most recent call last):


File "<pyshell#7>", line 1, in <module>
response = requests.get(url, auth=("root", "D_Vay!_10&"))

SSLError: HTTPSConnectionPool(host='ios-xe-mgmt.cisco.com',
port=9443): Max retries exceeded with url: /.well-known/host-meta
(Caused by SSLError(SSLError(1, u'[SSL: CERTIFICATE_VERIFY_FAILED]
certificate verify failed (_ssl.c:661)'),))

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 87
“Accepting” Self-Signed Certificates with Python
Requests
>>> import requests
• Disable with >>> url = "https://ios-xe-mgmt.cisco.com:9443/.well-known/host-meta"
verify = False
>>> response = requests.get(url, auth=("root", "D_Vay!_10&"), verify=False)
• Still generates a Warning Warning (from warnings module):
notification File "/Users/hapresto/coding/BRKDEV-1368/venv/lib/python2.7/site-
packages/urllib3/connectionpool.py", line 858
InsecureRequestWarning)
• But the request is
InsecureRequestWarning: Unverified HTTPS request is being made. Adding
successful certificate verification is strongly advised. See:
https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings

>>> print(response.text)

<XRD xmlns='http://docs.oasis-open.org/ns/xri/xrd-1.0'>
<Link rel='restconf' href='/restconf'/>
</XRD>

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 88
Disabling Insecure SSL Warnings from urllib

>>> requests.packages.urllib3.disable_warnings()
• Import urllib
• Disable warnings >>> response = requests.get(url, auth=("root", "D_Vay!_10&"), verify=False)

>>> print(response.text)

<XRD xmlns='http://docs.oasis-open.org/ns/xri/xrd-1.0'>
<Link rel='restconf' href='/restconf'/>
</XRD>

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 89
RESTCONF in Python
# Used to configure the IP address on an interface
def configure_ip_address(interface, ip):
# RESTCONF URL for specific interface
url = url_base + "/data/ietf-interfaces:interfaces/interface={i}".format(i=interface)

• Example function to
configure IP with RESTCONF # Create the data payload to reconfigure IP address
# Need to use OrderedDicts to maintain the order of elements
data = OrderedDict([('ietf-interfaces:interface',

• Using “requests” OrderedDict([


('name', interface),
('type', 'iana-if-type:ethernetCsmacd'),
('ietf-ip:ipv4',
OrderedDict([
('address', [OrderedDict([
('ip', ip["address"]),
('netmask', ip["mask"])
])]
)
])
),
])
)])

# Use PUT request to update data


response = requests.put(url,
auth=(USER, PASS),
headers=headers,
verify=False,
json=data
)
print(response.text) BRKDEV-1368/restconf/example1.py
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 90
Is RESTCONF a REST API?

It depends…
(of course it does)

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 91
Richardson Maturity Model for REST

RESTCONF is a Level 2 REST API


• RESTCONF targets resources
• RESTCONF uses HTTP Verbs
• RESTCONF doesn’t use Hypermedia
Controls

Source: https://martinfowler.com/articles/richardsonMaturityModel.html
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 92
RESTCONF
Summary
Review

• The elements of the RESTCONF transport protocol


• How to leverage Postman to use RESTCONF
• Examples retrieving and configuring data using RESTCONF
• Yep, RESTCONF is a REST API!

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 94
Demo Time:
Model Driven Programmability in Action!
Starting Network Topology

• Physical Topology
• IOS XE Routers

• Network has been cabled already


• Management access to devices
enabled
• No other configuration completed

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 96
Desired Network Configuration

• Layer 3 Links between Core/Dist


• Routed /30 networks

• OSPF Configuration
• Multi-Area
• 1 Stub and 1 Totally Stubby Area
• Several connected networks advertised at each
router

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 97
Use our NETCONF / YANG and Python Mastery!

• Standard YANG Models


• Native YANG Models
• Reusable XML Templates
• Store network configuration details in
configuration file
• Use Python + ncclient to send
configurations

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 98
YANG Model: openconfig-interfaces.yang

module: openconfig-interfaces
• Standard model for +--rw interfaces
“managing network +--rw interface* [name]
+--rw name -> ../config/name
interfaces and +--rw config
| +--rw name? string
subinterfaces” | +--rw type identityref
| +--rw mtu? uint16
• Augmented by: | +--rw description? string
| +--rw enabled? boolean
• openconfig-if-ip.yang +--rw subinterfaces
+--rw subinterface* [index]
• openconfig-if- +--rw index -> ../config/index
ethernet.yang +--rw config
| +--rw index? uint32
| +--rw description? string
| +--rw enabled? boolean

* Output edited for display on slide


https://github.com/openconfig/public/blob/master/release/models/interfaces

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 99
YANG Model: Cisco-IOS-XE-ospf.yang

module: Cisco-IOS-XE-ospf
• Native model for augment /ios:native/ios:router:
managing OSPF +--rw ospf* [id]
+--rw id uint16
configuration and state +--rw vrf? string
+--rw area* [id]
• Augments the | +--rw id ios-types:ospf-area-type
| +--rw authentication!
Cisco-IOS-Native.yang | | +--rw message-digest? empty
| +--rw stub!
model | | +--rw no-ext-capability? empty
| | +--rw no-summary? empty
+--rw network* [ip mask]
| +--rw ip inet:ipv4-address
| +--rw mask inet:ipv4-address
| +--rw area? ios-types:ospf-area-type

* Output edited for display on slide


https://github.com/YangModels/yang/tree/master/vendor/cisco/xe/1662

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 100
Creating Reusable
Templates <config>
<interfaces xmlns="http://openconfig.net/yang/interfaces">
{% for interface in interfaces %}
<interface>
<name>{{interface.name}}</name>
<config>
<type xmlns:ianaift="urn:ietf:params:xml:ns:yang:iana-if-type">{{interface.type}}</type>
<name>{{interface.name}}</name>

• Jinja2 Templating Language <enabled>{{interface.enabled}}</enabled>


</config>
<subinterfaces>

http://jinja.pocoo.org <subinterface>
<index>0</index>
<config>
<index>0</index>
• Powerful templating language <name>{{interface.name}}</name>
<enabled>{{interface.enabled}}</enabled>
</config>
• Variable insertion, conditionals, loops <ipv4 xmlns="http://openconfig.net/yang/interfaces/ip">
<addresses>
<address>

• Not just for Python <ip>{{interface.ip}}</ip>


<config>
<ip>{{interface.ip}}</ip>
<prefix-length>{{interface.prefix}}</prefix-length>

• Architects/Designers/Engineers </config>
</address>
</addresses>

create standard configurations </ipv4>


<ipv6 xmlns="http://openconfig.net/yang/interfaces/ip">
<config>
<enabled>false</enabled>
• Combined with specific environment </config>
</ipv6>
details = full configurations </subinterface>
</subinterfaces>
<ethernet xmlns="http://openconfig.net/yang/interfaces/ethernet">
<config>
<auto-negotiate>true</auto-negotiate>
</config>
</ethernet>
</interface>
{% endfor %}
BRKDEV-1368/demo/layer3_interface_config.j2 </interfaces>
</config>
* Output edited for display on slide
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 101
Creating Reusable Templates
Layer 3 Configuration Template
Partial for Discussion
<config>
<interfaces xmlns="http://openconfig.net/yang/interfaces">
{% for interface in interfaces %}
<interface>
<name>{{interface.name}}</name>
<config>
<type xmlns:ianaift="urn:ietf:params:xml:ns:yang:iana-if-type">
{{interface.type}}</type>
<name>{{interface.name}}</name>
<enabled>{{interface.enabled}}</enabled>
</config>
</interface>
{% endfor %}
</interfaces>
</config>
* Output edited for display on slide

BRKDEV-1368/demo/layer3_interface_config.j2
BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 102
Creating Reusable Templates
OSPF Configuration Template
<ospf xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-ospf">
<id>{{ospf.process_id}}</id>
{% for area in ospf.areas %}
<area>
<id>{{area.area}}</id>
{% if area.type == "stub" %}
<stub>
{% if area.no_summary %}
<no-summary />
{% endif %}
</stub>
{% endif %}
</area>
{% endfor %}
<router-id>{{ospf.router_id}}</router-id>
{% for network in ospf.networks %}
<network>
<ip>{{network.network}}</ip>
<mask>{{network.wildcard}}</mask>
<area>{{network.area}}</area>
</network>
{% endfor %}
</ospf>
* Output edited for display on slide
BRKDEV-1368/demo/ospf_config.j2

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 103
Environment Specific Network Configuration
Details
devices:
# IOS XE 1
• 12 Factor Principal - ”strict separation of - name: iosxe1
config from code” interfaces:
- name: GigabitEthernet3
https://www.12factor.net/config enabled: "true"
ip: 10.0.0.5
• ”Config” is everything that varies between
prefix: 30
device deployments type: ianaift:ethernetCsmacd
• Examples: IPs, names, interfaces ospf:
router_id: 1.1.1.1
• Your code should “read in” config from areas:
another source - area: "256"
type: stub
• CMDB, IPAM, data base, configuration file, networks:
etc - network: 10.0.0.1
wildcard: 0.0.0.0
• YAML data format used in demo area: "256"
• Human readable data format used by many
* Output edited for display on slide
orchestration tools BRKDEV-1368/demo/config_details.yaml

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 104
Sending Network Configurations with ncclient

# Load Network Config Details from YAML Config File


Part 1: Loading configuration and print("Loading Network Configuration Details")
templates with open("config_details.yaml") as f:
config = yaml.load(f.read())
• PyYAML library used to process
configuration # Create Jinja Template Objects for NETCONF Payloads
print("Setting Up NETCONF Templates")
• Jinja2 Template objects created for # Layer 3 Interface Configurations
each XML template with open("layer3_interface_config.j2") as f:
l3_template = Template(f.read())

# OSPF Routing Configuration


with open("ospf_config.j2") as f:
ospf_template = Template(f.read())

BRKDEV-1368/demo/push_configs.py

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 105
Sending Network Configurations with ncclient

Part 2: Creating Device


Specific Configurations # Loop over network devices to create and deploy network config
print("Processing Device Configurations")
• “for” loop used across for device in config["devices"]:
devices print("Device: {}".format(device["name"]))
# Create Device Specific Configurations
print(" Creating Device Specific Configurations ")
• Combine device
configuration details with with open("netconf_configs/{}_layer3.cfg".format(device["name"]),
"w") as f:
templates l3_config = l3_template.render(interfaces=device["interfaces"])
f.write(l3_config)
• Save configs to text files
with open("netconf_configs/{}_ospf.cfg".format(device["name"]),
"w") as f:
ospf_config = ospf_template.render(ospf=device["ospf"])
f.write(ospf_config)

BRKDEV-1368/demo/push_configs.py

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 106
Sending Network Configurations with ncclient
# Connect to Device with NETCONF
print(" Connecting to device with NETCONF")
Part 3: Connect to Device and with manager.connect(host=config["network_mgmt_host"],
port=device["netconf_port"],

Send Configurations username=config["username"],


password=config["password"],
hostkey_verify=False,
device_params={'name': 'default'},
• ncclient.manager used to open allow_agent=False,
look_for_keys=False) as m:
single connection
# Send NETCONF Configurations with <edit-config> RPC
• Use <edit-config> to send print(" Sending NETCONF Configuration edit-config operations")
l3_resp = m.edit_config(l3_config, target = "running")
device specific payload ospf_resp = m.edit_config(ospf_config, target = "running")

• Print RPC result for status # Process XML data in replies


l3_reply = xmltodict.parse(l3_resp.xml)
ospf_reply = xmltodict.parse(ospf_resp.xml)

# Print Config Replies


print(" Layer 3 Interface Config: {}".format(
l3_reply["rpc-reply"].keys()[3]))
print(" OSPF Config: {}".format(ospf_reply["rpc-reply"].keys()[3]))
print("")
BRKDEV-1368/demo/push_configs.py

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 107
Let’s see it in
action!
Model Driven
Programmability in
Real Life
That was cool… but is that
really the way networks will be
configured in the future?

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 110
NETCONF/YANG Used in Other Tools
Management & Configuration Network Software
Orchestration Management Controllers Libraries

YANG Development Kit (YDK)

NAPALM

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 111
Example…
Network Service based
Automation
Remember…
What might a YANG Data Model describe?

Device Data Models Service Data Model


- Interface - L3 MPLS VPN
- VLAN - MP-BGP
- Device ACL - Network ACL
- Tunnel - EVPN
- OSPF - System Management
- etc - Network Faults
- etc

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 113
Model Driven EVPN Network Service

• VXLAN EVPN through device/CLI is Tenant 2


Tenant 1
complex and error prone
• 75+ lines of config per spine, 50+ on a leaf
just to initialize fabric*
• A single tenant can require 100+ lines per
leaf**

Goal: Network Service that simplifies


management and provides
consistency
* Sample Fabric Baseline Config
** Sample Tenant Configuration http://bit.ly/demo_evpn

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 114
Example of a YANG Service Model

• Resource Allocation
• Service Birth Certificate
• Verification / Sync API’s
• Subscriptions

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 115
Example of a YANG Service Model
YANG Model Templates

Appearance
what is its abstraction, what is its API, Manifestation
how can it be used? How is this implemented?

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 116
Questions?
Review

• The Road to Model Driven Programmability


• Introduction to YANG Data Models
• Introduction to NETCONF
• Introduction to RESTCONF
• Model Driven Programmability in Action
• Model Driven Programmability in Real Life
• Conclusion and Q/A

Note: All code samples referenced in this presentation are available at


https://github.com/CiscoDevNet/BRKDEV-1368

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 118
What do do next?

• Resources • DevNet Learning Labs


• Overview of the 2002 IAB Network • Introduction to Device Level Interfaces -
Management Workshop NETCONF/YANG
• NETCONF/YANG on Nexus
• Network Configuration Protocol
(NETCONF) • Home Lab: Using NETCONF/YANG from
your Desktop OS
• The YANG 1.1 Data Modeling
Language • Blogs and Videos
• RESTCONF Protocol • Using CLI as Training Wheels with
• YANG Development Kit (YDK) NETCONF/YANG
• Simplifying Network Programmability
with Model Driven APIs
• Network Device APIs Video Lessons

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 119
Got more questions? Stay in touch!

Hank Preston developer.cisco.com


[email protected] @CiscoDevNet

@hfpreston facebook.com/ciscodevnet/

http://github.com/hpreston http://github.com/CiscoDevNet

DEVNET-1725 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 120
Complete your
online session
survey • Please complete your session survey
after each session. Your feedback
is very important.
• Complete a minimum of 4 session
surveys and the Overall Conference
survey (starting on Thursday) to
receive your Cisco Live t-shirt.
• All surveys can be taken in the Cisco Events
Mobile App or by logging in to the Content
Catalog on ciscolive.com/emea.

Cisco Live sessions will be available for viewing on


demand after the event at ciscolive.com.

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 121
Continue your education

Demos in the
Walk-In Labs
Cisco Showcase

Meet the Engineer


Related sessions
1:1 meetings

BRKDEV-1368 © 2020 Cisco and/or its affiliates. All rights reserved. Cisco Public 122
Thank you

You might also like