Chapter 11

NETCONF and RESTCONF

This chapter covers the following topics:

  • Catalyst for NETCONF: This section covers the reasons and benefits for NETCONF.

  • Atomic and Model-Driven Configuration Management: This section covers the differences between atomic, templatized, and model-driven configuration management.

  • How to Implement NETCONF: This section covers the methods for implementing NETCONF, the skills needed, and sample configuration guidelines.

  • YANG Models: This section covers the reasons and benefits for YANG models.

  • The Evolution with RESTCONF: This section covers the additional benefits beyond NETCONF provided with RESTCONF.

  • Management Solutions Using NETCONF and RESTCONF: This section provides insights into the current management tool offerings that leverage NETCONF and/or RESTCONF. Both commercial and open-source examples are shared.

This chapter maps to the Developing Applications Using Cisco Core Platforms and APIs v1.0 (350-901) Exam Blueprint Section 5.2, “Utilize RESTCONF to configure a network device including interfaces, static routes, and VLANs (IOS XE only).”

NETCONF and RESTCONF are relatively new but mature management protocols that are well suited for network programmability. This chapter covers the basic theory behind NETCONF and RESTCONF. It shows examples of how to use them so that you can apply them in your Cisco network environment.

“Do I Know This Already?” Quiz

The “Do I Know This Already?” quiz allows you to assess if you should read this entire chapter. If you miss no more than one of these self-assessment questions, you might want to move ahead to the “Exam Preparation Tasks” section. Table 11-1 lists the major headings in this chapter and the “Do I Know This Already?” quiz questions covering the material in those headings so you can assess your knowledge of these specific areas. You can find the answers in Appendix A, “Answers to the ‘Do I Know This Already?’ Quizzes.”

Table 11-1 “Do I Know This Already?” Section-to-Question Mapping

Foundation Topics Section

Questions

Catalyst for NETCONF

1–2

Atomic and Model-Driven Configuration Management

3

How to Implement NETCONF

4–6

YANG Models

7–8

The Evolution with RESTCONF

9–10

1. Which standards body started the work on NETCONF?

  1. ANSI

  2. IETF

  3. ITU

  4. TMF

2. What RFCs defined NETCONF, initially and lately?

  1. RFCs 3413 and 4741

  2. RFCs 3413 and 8040

  3. RFCs 4741 and 8040

  4. RFCs 4741 and 6241

3. What is a key characteristic of model-driven configuration management?

  1. Model-driven management reflects relationships across deployed networks and nodes to configure accurate intent.

  2. Model-driven management treats networks and devices with segmentation.

  3. Model-driven management applies to the RC hobby industry.

  4. Model-driven management uses inference engines to dynamically generate configuration parameters.

4. Which command do you use to enable NETCONF on an IOS XE device?

  1. netconf enable

  2. netconf start

  3. netconf-yang

  4. enable netconf

  5. None of these answers are correct.

5. What is the standard port for NETCONF sessions?

  1. TCP/443

  2. UDP/443

  3. TCP/830

  4. UDP/830

  5. None of these answers are correct.

6. What is the ending sequence for a NETCONF RPC hello exchange over an SSH session?

  1. ..END..

  2. ]]>]]>

  3. >>]>>]

  4. <EOF>

7. What IETF working group worked on YANG, and what function does it provide?

  1. NETCONF; it serves as a data abstraction protocol that serves to normalize firmware images.

  2. NETCONF; it provides a complementary encoding method to YIN.

  3. NETMOD; it serves as a data modeling language to characterize configuration, state, and administrative functions.

  4. NETMOD; it is the next-generation availability monitoring protocol that extends ICMP ping.

8. What are common YANG objects?

  1. Module, container, list, leaf

  2. Container, spine, leaf

  3. spine, leaf, interconnect

  4. None of these answers are correct.

9. What header and value should be provided in a RESTCONF operation to identify an intent to receive results in JSON format?

  1. Content-Type: application/json

  2. Content-Type: application/yang-data+json

  3. Accept: application/json

  4. Accept: application/yang-data+json

10. Suppose you want to update an existing configuration setting via RESTCONF. What would be the most appropriate operation type?

  1. GET

  2. POST

  3. PUT

  4. DELETE

Foundation Topics

Catalyst for NETCONF

As the number of network equipment manufacturers increased, so did the variety of configuration syntaxes and parameters to provision and monitor those systems. Sometimes, as it was for Cisco, network equipment suppliers had multiple product lines that used different software—essentially network operating systems. These different operating systems often meant different command syntax and provisioning arguments. Even considering a fundamental feature like Border Gateway Protocol (BGP) meant different “golden configs” or templates across operating systems for Cisco IOS, Cisco IOS XE, Cisco NX-OS, Cisco IOS-XR, Juniper Junos OS, HPE Comware, Arista EOS, and so on. This difference in configuring the same function across different device vendors, models, and operating systems led to many network engineers maintaining multiple configuration standards. Having multiple configuration standards meant a higher probability of variance, especially when periodic review and synchronization were not part of a standard process. The industry, most notably the service provider segment, sought a way to have “one configuration to rule them all.” We’re sure this would make Frodo the network engineer happy!

In May 2003, the Internet Engineering Task Force (IETF) formed the NETCONF (network configuration) working group. Their work was first published as RFC 4741 in December 2006. Cisco provided initial support all the way back in IOS 12.4(9)T and presented the NETCONF topic at the CiscoLive 2009 event in San Diego. Several updates and enhancements have been developed over the years; the foundational protocol was updated as RFC 6241 in June 2011.

Figure 11-1 shows the layered model for NETCONF, which includes a bottoms-up transport layer, messaging container, operational directives, and content payload.

Figure 11-1 NETCONF Conceptual Layers

Content

Originally, the content of NETCONF operations was founded on the Extensible Markup Language (XML). XML provided structure and syntax for encoding data in a format that is both human-readable and machine-readable. This provision served the needs of both traditional network engineers who wanted more control over the provisioning and monitoring of their network and devices with those who wanted more programmatic options. The NETCONF protocol has also been enhanced to support JavaScript Object Notation (JSON) (note RFC 7951), but it remains common to see XML in implementations.

Later in this chapter, you learn how the NETMOD (network modeling) working group aimed to define a modeling language that was also easy to use for humans. It would define semantics of operational data, configuration data, notifications, and operations in a standard called YANG.

XML has its origins in Standard Generalized Markup Language (SGML) and has similarities to Hypertext Markup Language (HTML). Markup is a type of artificial language used to annotate a document’s content to give instructions regarding structure or how it is to be displayed (rendered). XML is used to describe data, whereas HTML is used to display or render the data.

XML provides many benefits: it promotes the capability to use data or text in many ways from one original input source. This capability promotes data exchange and enables cross-platform data sharing. XML provides a software- and hardware-independent markup language for structuring and transmitting data. So the early days of NETCONF drove market trends leaning to it for configuration management and provisioning, verification, fault, and operational state monitoring. Later and more currently, JSON is being used more prominently for data encoding in the network IT discipline.

Operations

To effectively manage device configurations, different tasks and operation types have to be accommodated. The standard editing and deleting of a configuration are nearly universal across vendors and products. The support of more sophisticated methods, such as locking a configuration, varies in device implementation.

The base NETCONF protocol defines several operation types, as seen in Table 11-2.

Table 11-2 NETCONF Protocol Operations

Operation

Description

get

Retrieves running configuration and device state information

get-config

Retrieves all or part of a specified configuration

edit-config

Loads all or part of a specified configuration to the specified target configuration

copy-config

Creates or replaces an entire configuration datastore with the contents of another complete configuration datastore

delete-config

Deletes a configuration datastore

lock

Locks an entire configuration datastore of a device

unlock

Releases a configuration lock previously obtained with the <lock> operation

close-session

Requests graceful termination of a NETCONF session

kill-session

Forces the termination of a NETCONF session

Messages

The NETCONF messages layer is a simple, transport-independent framing mechanism for encoding directives. Remote-procedure calls (RPCs) are declared with <rpc> messages. The RPC results are handled with <rpc-reply> messages, and asynchronous notifications or alerts are defined by <notification> message types.

Every NETCONF message is a well-formed XML document. An original <rpc> message provides an association to <rpc-reply> with a message-id attribute. Multiple NETCONF messages can be sent without waiting for sequential RPC result messages. Figure 11-2 shows a simple XML-encoded NETCONF message. Note the structure and message-id linkage. We cover more specifics in the “How to Implement NETCONF” section.

Figure 11-2 NETCONF Request and Reply

Transport

When you are dealing with the transfer of critical infrastructure configurations, it is mandatory to keep the information private and secure. This was a shortcoming in version 1 and 2c of the Simple Network Management Protocol (SNMP). SNMP did not have inherent security for the authentication of management systems or the encryption of the data being transferred. SNMPv3 transformed the protocol by bringing both authentication and encryption. The IETF NETCONF working group planned security as a foundational requirement for NETCONF. The initial RFC 4741 stipulated that NETCONF connections must provide authentication, data integrity, and confidentiality. It further provided that connections may be encrypted in Transport Layer Security (TLS) or Secure Shell (SSH). The most widely used implementations were the transport layer for NETCONF using SSHv2. An additional option was the Blocks Extensible Exchange Protocol (BEEP); however, it was not widely supported and is not suggested for future implementations.

RFC 7589 has brought additional functionality in TLS with Mutual X.509 Authentication.

Atomic and Model-Driven Configuration Management

Using atomic configuration management techniques is common and familiar. Most engineers are comfortable with the model of creating a configuration template and noting the variable parameters that must be reconciled among deployments. Maybe you’re deploying a standard interface configuration for an access layer switch and its downstream connection to a server, as in Figure 11-3.

Figure 11-3 Sample Configuration Template

Or maybe you’ve deployed configurations using Configuration Management functions in a templatized sense that were part of commercial tools, like Prime Infrastructure, as in Figure 11-4.

Figure 11-4 Configuration Management with Templates in Prime Infrastructure

There’s even the next level of sophistication, where you’ve deployed configurations by answering questions in provisioning wizards that generated the configurations, as with DNA Center.

In any case, these systems depended on a known set of conventions with the command syntax and arguments where the network engineer provided answers to the variables. Additionally, this atomic model generally referred to specific devices and did not maintain an awareness or understanding of interdependencies among the devices. The configuration management function was unintelligent; it merely pushed what it was told without consideration of peering relationships and dependencies.

If you consider a well-known feature such as Hot Standby Router Protocol (HSRP), you can recognize there’s a configuration template for the primary router and a similar but slightly different configuration template for the standby router(s). An atomic configuration management solution would not recognize the interdependencies and would allow you to push the changes in a way that may not function or could cause a larger service outage.

Conversely, model-driven configuration management strives to abstract the individual device configurations in favor of the deployment of a service or feature. The resulting configuration(s) generated may involve multiple devices as they form the basis for deploying the service/feature. The model is either fully deployed successfully, or it is rolled back or removed entirely so that no partial configuration fragments are left on any devices.

Another well-known but more advanced example would be deploying Multiprotocol Label Switching (MPLS). Figure 11-5 depicts a standard architecture for MPLS.

Figure 11-5 Standard MPLS Architecture

Consider how a virtual routing and forwarding (VRF) feature is deployed. It involves several device types and functions. In a typical MPLS deployment, a customer edge (CE) router performs local routing and shares routing information with the provider edge (PE) where routing tables are virtualized. PE routers encapsulate traffic, marking it to identify the VRF instance, and transmit it across the service provider backbone network over provider devices to the destination PE router. The destination PE router then decapsulates the traffic and forwards it to the CE router at the destination. The backbone network is completely transparent to the customer equipment, allowing multiple customers or user communities to use the common backbone network while maintaining end-to-end traffic separation.

Now consider the previous architecture with a bit more configuration definition. In Figure 11-6 note the commonalities across the highlighted devices.

Figure 11-6 MPLS CE-PE Configlets

In a traditional, atomic configuration model, those configlets would be templates, and the highlighted parts would be parameters that need to be reconciled across the deployment to two (or more) devices. It would be up to the network engineer and operations personnel to correctly reconcile the variables and deploy them device by device. The deployment personnel would be responsible for each device implementation and have to gauge its correct deployment or remove all associated configurations from all the devices, again device by device. Can you see the possibility for user-induced error?

In a model-driven configuration management approach, those templates would be merged into a common model that would deploy the rendered configlets appropriately to the devices involved in the service. The configurations would deploy accurately, or they would be rolled back from each associated device so that no partially deployed configurations would remain. The network administrator would still need to identify the device(s), their role(s), and the required parameters to deploy the service, but they wouldn’t need to treat each device individually.

How to Implement NETCONF

As mentioned earlier, NETCONF interactions are typically done via an SSH transport and the NETCONF subsystem; the default port is TCP/830. A specifically formed XML document is transmitted to share a hello and capabilities exchange. The hello and capabilities exchange is typically followed by the NETCONF directives and response. Most Cisco devices running IOS XR, IOS XE, or NX-OS, and recent software versions support NETCONF/YANG because it is a mature feature. Initial support for NETCONF was released all the way back to traditional IOS 12.4(9)T and later, and IOS XE 2.1.

Tip

If you want to get some hands-on experience with the feature but would rather not use your own equipment (or don’t have dev-test equipment), then check out the DevNet Always On Labs and Sandbox environments at https://developer.cisco.com/site/sandbox/. There are shared Always On environments for IOS XE, IOS XR, and NX-OS to use.

Let’s get started by enabling the feature and work from there.

Enabling NETCONF on IOS XE

If you wish to have a separate NETCONF user account (which is recommended), then ensure it is enabled in your AAA (or local) configuration with level 15 access.

Enable the NETCONF (and YANG) feature from the configuration mode with

Device (config)# netconf-yang

That’s it!

Candidate datastores (essentially “work in progress” or “scratch config” spaces) can be enabled with

Device (config)# netconf-yang feature candidate-datastore

You can validate the NETCONF feature with the following command:

Device# show netconf-yang datastores

Datastore Name              : running

The command output shows any configuration locks, if they exist, by session identifier and date-time.

If there are current sessions, they can be identified with the command shown in Example 11-1.

Example 11-1 Identifying Current Sessions with show netconf-yang sessions

Device# show netconf-yang sessions

R: Global-lock on running datastore
C: Global-lock on candidate datastore
S: Global-lock on startup datastore
Number of sessions : 4
session-id transport username source-host global-lock
---------------------------------------------------------
10         netconf-ssh admin  10.15.1.110 None
12         netconf-ssh admin  10.15.1.110 None
14         netconf-ssh admin  10.15.1.110 None
16         netconf-ssh admin  10.15.1.110 None

You can obtain detailed NETCONF session data with the command shown in Example 11-2.

Example 11-2 Using show netconfig-yang to Get Detailed Session Data

Device# show netconf-yang sessions detail

R: Global-lock on running datastore
C: Global-lock on candidate datastore
S: Global-lock on startup datastore

Number of sessions     : 1

session-id             : 10
transport              : netconf-ssh
username               : netconf-admin
source-host            : 2001:db8::110
login-time             : 2021-04-15T10:22:13+00:00
in-rpcs                : 0
in-bad-rpcs            : 0
out-rpc-errors         : 0
out-notifications      : 0
global-lock            : None

Finally, if you’re interested in the amount of NETCONF feature use, you can use the command shown in Example 11-3.

Example 11-3 Using show netconf-yang to Get Feature Statistics

Device# show netconf-yang statistics
netconf-start-time : 2021-04-15T10:25:33+00: 00

in-rpcs : 0
in-bad-rpcs : 0
out-rpc-errors : 0
out-notifications : 15
in-sessions : 124
dropped-sessions : 0
in-bad-hellos : 0

Enabling NETCONF on IOS XR

If you wish to have a separate NETCONF user account (which is recommended), then ensure it is enabled in your AAA (or local) configuration.

Enable the NETCONF (and YANG) feature from the configuration mode with

RP/0/RSP0/CPU0:router (config)# netconf agent ssh

RP/0/RSP0/CPU0:router (config)# ssh server netconf vrf NETCONF_VRF
ipv4 access-list IPV4_NETOPS ipv6 access-list IPV6_NETOPS

RP/0/RSP0/CPU0:router (config)# ssh server netconf port 830

The VRF and access-list definition should be defined to suit your environment. The last command, ssh server netconf port, can be omitted if you use the default port 830; otherwise, include the custom port desired.

To view the NETCONF (and YANG) statistics, you can use the command shown in Example 11-4.

Example 11-4 Using show netconfig-yang to Extract Statistics

RP/0/RSP0/CPU0:router# show netconf-yang statistics
Summary statistics   reqs|        total time|   min time / req|   max time / req|
  avg time / req|
other                   0|  0h  0m  0s   0ms| 0h  0m  0s   0ms| 0h  0m  0s   0ms|
  0h  0m  0s   0ms|
close-session           4|  0h  0m  0s   3ms| 0h  0m  0s   0ms| 0h  0m  0s   1ms|
  0h  0m  0s   0ms|
kill-session            0|  0h  0m  0s   0ms| 0h  0m  0s   0ms| 0h  0m  0s   0ms|
  0h  0m  0s   0ms|
get-schema              0|  0h  0m  0s   0ms| 0h  0m  0s   0ms| 0h  0m  0s   0ms|
  0h  0m  0s   0ms|
get                     0|  0h  0m  0s   0ms| 0h  0m  0s   0ms| 0h  0m  0s   0ms|
  0h  0m  0s
get-config              1|  0h  0m  0s   1ms| 0h  0m  0s   1ms| 0h  0m  0s   1ms|
  0h  0m  0s   1ms|
edit-config             3|  0h  0m  0s   2ms| 0h  0m  0s   0ms| 0h  0m  0s   1ms|
  0h  0m  0s   0ms|
commit                  0|  0h  0m  0s   0ms| 0h  0m  0s   0ms| 0h  0m  0s   0ms|
  0h  0m  0s   0ms|
cancel-commit           0|  0h  0m  0s   0ms| 0h  0m  0s   0ms| 0h  0m  0s   0ms|
  0h  0m  0s   0ms|
lock                    0|  0h  0m  0s   0ms| 0h  0m  0s   0ms| 0h  0m  0s   0ms|
  0h  0m  0s   0ms|
unlock                  0|  0h  0m  0s   0ms| 0h  0m  0s   0ms| 0h  0m  0s   0ms|
  0h  0m  0s   0ms|
discard-changes         0|  0h  0m  0s   0ms| 0h  0m  0s   0ms| 0h  0m  0s   0ms|
  0h  0m  0s   0ms|
validate                0|  0h  0m  0s   0ms| 0h  0m  0s   0ms| 0h  0m  0s   0ms|
  0h  0m  0s   0ms|

Additionally, you can obtain detailed session and client information with the following command:

RP/0/RSP0/CPU0:router# show netconf-yang clients

client session ID| NC version| client connect time|   last OP
  time|   last OP type|  <lock>|

               423|         1.1|      0d  1h 13m 33s|
14:36:24|  close-session|     No|

               424          1.1|      0d  1h 35m  1s|
14:57:25|     get-config|      No|

Enabling NETCONF on NX-OS

If you wish to have a separate NETCONF user account (which is recommended), then ensure it is enabled in your AAA (or local) configuration and has level 15 privilege.

Ensure the SSHv2 feature is enabled.

Enable the NETCONF (and YANG) feature from the configuration mode with

switch(config)# feature netconf

switch(config)# netconf idle-timeout 10

switch(config)# netconf sessions 5

Basic Manual Use of NETCONF

Now that the NETCONF agent is enabled on the device, you can start to interact with it. For the sake of learning, you can use manual SSH sessions to show the exchanges between the manager (the SSH terminal emulator) and the NETCONF device. These interactions would be done behind the scenes by NETCONF-enabled management tools, such as Cisco Network Services Orchestrator (NSO) and others.

First, connect to the device’s NETCONF subsystem using your preferred SSH terminal emulator (connecting to default port 830) or with a common SSH command-line tool, as seen in any common Linux or macOS distribution in the next example:

client-host$ ssh -s [email protected] -p 830 netconf

The device responds with a capabilities exchange, which could be hundreds of lines long reflecting all the features and YANG models that are supported and installed, like that shown in Example 11-5.

Example 11-5 NETCONF Capabilities Exchange/Hello

<?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>
<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>urn:ietf:params:netconf:capability:notification:1.0</capability>
<capability>urn:ietf:params:netconf:capability:interleave:1.0</capability>
<capability>urn:ietf:params:netconf:capability:with-defaults:1.0?basicmode=
explicit&also-supported=report-all-tagged</
capability>
<capability>urn:ietf:params:netconf:capability:yang-library:1.0?revision=2016-
06-21&module-set-id=7294e20b121b24ac71a8fb609b7d3afd</
capability>
<capability>http://tail-f.com/ns/netconf/actions/1.0</capability>
<capability>http://tail-f.com/ns/netconf/extensions</capability>
<capability>http://cisco.com/ns/cisco-xe-ietf-ipdeviation?
module=cisco-xe-ietf-ip-deviation&revision=2016-08-10</
capability>
<capability>http://cisco.com/ns/cisco-xe-ietf-ipv4-unicast-routingdeviation?
module=cisco-xe-ietf-ipv4-unicast-routing-deviation&revis
ion=2015-09-11</capability>
<capability>http://cisco.com/ns/cisco-xe-ietf-ipv6-unicast-routingdeviation?
module=cisco-xe-ietf-ipv6-unicast-routing-deviation&revis
ion=2015-09-11</capability>
. . . (MANY lines omitted) . . .
<capability>urn:ietf:params:xml:ns:yang:ietf-netconf-withdefaults?
module=ietf-netconf-with-defaults&revision=2011-06-01</
capability>
<capability>
        urn:ietf:params:netconf:capability:notification:1.1
   </capability>
</capabilities>
<session-id>21</session-id></hello>]]>]]>

Some items of note: the usual XML declaration line is followed by a <hello> element, followed by a <capabilities> list element of many <capability> child elements. Finally, there’s a session identifier (21 in this case), some closing tags, and a unique session ending sequence:

]]>]]>

This sequence is important for both manager and managed device to recognize the end of an exchange.

To (manually) interact with the NETCONF agent, you must send your capabilities also, or the agent will not respond to any other input. For example, you can send into the SSH terminal the text (pasted) shown in Example 11-6.

Example 11-6 NETCONF Hello from Management Station

<?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>
    </capabilities>
</hello>]]>]]>

You do not see any results from the device, but it registers your capabilities (NETCONF base 1.0) and awaits your next directives.

NETCONF uses RPCs to wrap the directives. Let’s assume the next thing you want to do is obtain the running configuration from the device. Using this method is a good way to understand the structure and syntax of an XML-encoded configuration. You would send the code shown in Example 11-7 in your SSH session.

Note

The device may time out after a few minutes of nonactivity. If so, reconnect and resend the capabilities exchange.

Example 11-7 NETCONF XML Payload to Get Configuration

<?xml version="1.0" encoding="UTF-8" ?>
<rpc message-id="200" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
    <get-config>
        <source>
            <running/>
        </source>
    </get-config>
</rpc>]]>]]>

In this case, the device immediately responds with the running configuration in a compact XML form, as shown in Example 11-8.

Example 11-8 NETCONF Response from Device

<?xml version="1.0" encoding="UTF-8"?>
<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message
-id="200"><data><native xmlns="http://cisco.com/ns/yang/
Cisco-IOS-XE-native"><version>16.9</version><boot-start-marker/><boot-end-
marker/><banner><motd><banner>^C</banner></motd></banner><service><timestamps><debug
><datetime><msec></msec></datetime></debug><log><datetime><msec/></datetime></log></
timestamps></service><platform><console xmlns="http://cisco.com/ns/yang/Cisco-IOS-
XE-platform"><output>virtual</output></console></platform><hostname>csr1000v-1</host
name><enable><secret><type>5</type>
. . . (A LOT OF CONFIG OMITTED . . .
</routing-instance></routing></data></rpc-reply>]]>]]>

Running this response through an XML formatting utility may be useful to discern the structure.

Note

Don’t copy and paste the XML-formatted configuration of one of your devices into an online XML utility. It is hard to say whether those free online services are retaining your data input. One of the easiest ways to view this without an external or a third-party resource is to save the output, minus the ]]>]]> closing sequence, to a text file with an .xml file extension and then load that text file into your browser. The browser renders it formatted and enables you to expand or close branches of configurations. Figure 11-7 shows the results of a browser processing the compact XML output from Example 11-8.

Figure 11-7 NETCONF Configuration as XML Rendered in a Browser

Now let’s do a simple NETCONF configuration editing operation. In this example, you change an interface description, so what you learn does not impact the service. If you collapse much of the XML structure from the configuration shown in Figure 11-7 in your browser, you can see some structure that is helpful. Focus on GigabitEthernet2 in this example (see Figure 11-8).

Figure 11-8 NETCONF Configuration of Gig2 Interface as XML Rendered in a Browser

To (manually) create the XML RPC to do a configuration change, you need to retain the XML hierarchy after the <data> element, down to the specific interface and the <description> element you wish to change. Example 11-9 shows the partial XML of interest.

Example 11-9 XML Fragment for RPC Building

<native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native">
<interface>
 <GigabitEthernet>
   <name>2</name>
 <description>

The intermediary parts are nonessential and can be omitted. You only need to send in the hierarchy and the element being changed. Example 11-10 shows how to change Gigabit-Ethernet2’s port description.

Example 11-10 NETCONF XML Payload to Edit the Configuration

<?xml version="1.0" encoding="UTF-8"?>
<rpc xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="300">
    <edit-config>
        <target>
            <running/>
        </target>
        <config>
            <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native">
                <interface>
                    <GigabitEthernet>
                        <name>2</name>
                        <description>My Description from NETCONF message-id 300</
                          description>
                    </GigabitEthernet>
                </interface>
            </native>
        </config>
    </edit-config>
</rpc>]]>]]>

When you push that into an active NETCONF session (with the capabilities exchange already being complete), you get the following result from the device:

<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-
id="300"><ok/></rpc-reply>]]>]]>

The highlighted <ok/> element signifies a good result from the device. You can confirm that in several ways. You can log in to the device and look at the interface descriptions, such as that shown in Example 11-11.

Example 11-11 Device Interface Descriptions

csr1000v-1# show int description
Interface         Status         Protocol Description
Gi1               up             up       MANAGEMENT INTERFACE - DON'T TOUCH ME
Gi2               admin down     down     My Description from NETCONF message-id 300
Gi3               admin down     down     Network Interface
csr1000v-1#

Or, more appropriately to your network programmability interest, you could execute the same <get-config> operation as before and get the configuration back in XML form, as seen in Figure 11-9, rendered in an XML editor.

Figure 11-9 NETCONF Configuration Updated as XML Rendered in a Browser

Note that the GigabitEthernet2 port description in the boxed area reflects the change you pushed with the <edit-config> operation.

If you’re an astute observer of the XML structure, you may have also noticed the use of the <native xmlns="http://cisco.com/ns/yang/Cisco-IOS-XE-native"> hierarchy to edit the configuration. However, there is also an element reference of <interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces">.

The first reference managed the device using its native syntax and model. This may not be especially portable. The second reference mentioning YANG and IETF provides a more cross-platform approach to referencing device configurations and represents the spirit of NETCONF’s focus: cross-platform configuration management. We cover that in the next section. The device could have been configured in either native or YANG model methods; both models also show the same results when getting the configuration.

It is helpful that the device and operating system supported both models, so you have options in how you want to manage the device—familiar, native syntax or cross-platform, device-abstracted syntax. Get familiar with both methods; you will find, however, the YANG model approach provides the closest option to that single “golden configuration standard” that can be applied across multiple devices.

YANG Models

NETCONF provides the protocol layer for managing device configurations in a programmatic and consistent way, but to be more effective, a data modeling language needed to be paired with NETCONF. The Yet Another Next Generation, or YANG, data modeling language provides a standardized way to represent operational and configuration data of a network device. YANG is protocol independent and can be converted into any encoding format, such as XML or JSON. You may also hear YANG referred to as a data model or even device data.

Similar to NETCONF, YANG was born from an IETF working group. The NETMOD working group was charged with creating a “human-friendly” modeling language to define semantics of operational data, configuration data, notifications, and operations. The original version of YANG was defined in RFC 6020 with an update (version 1.1) in RFC 7950. RFC 6991 defined “Common YANG Data Types,” such as seen in Table 11-3. Although SNMP is not a foundational component of the DEVCOR exam, the SMIv2 types are shown for comparison for those with SNMP background.

Table 11-3 IETF YANG Types Compared to SMIv2 Types

YANG Type

Equivalent SMIv2 type (module)

counter32

Counter32 (SNMPv2-SMI)

zero-based-counter32

ZeroBasedCounter32 (RMON2-MIB)

counter64

Counter64 (SNMPv2-SMI)

zero-based-counter64

ZeroBasedCounter64 (HCNUM-TC)

gauge32

Gauge32 (SNMPv2-SMI)

gauge64

CounterBasedGauge64 (HCNUM-TC)

object-identifier

object-identifier-128

OBJECT IDENTIFIER

yang-identifier

date-and-time

timeticks

TimeTicks (SNMPv2-SMI)

timestamp

TimeStamp (SNMPv2-TC)

phys-address

PhysAddress (SNMPv2-TC)

mac-address

MacAddress (SNMPv2-TC)

xpath1.0

hex-string

uuid

dotted-quad

Separate Internet types, ietf-inet-types, were also defined and can be seen in Table 11-4.

Table 11-4 IETF INET Types Compared to SMIv2 Types

YANG Type

Equivalent SMIv2 type (module)

ip-version

InetVersion (INET-ADDRESS-MIB)

dscp

Dscp (DIFFSERV-DSCP-TC)

ipv6-flow-label

IPv6FlowLabl (IPV6-FLOW-LABEL-MIB)

port-number

InetPortNumber (INET-ADDRESS-MIB)

ip-address

ipv4-address

ipv6-address

ip-prefix

ipv4-prefix

ipv6-prefix

domain-name

host

uri

Uri (URI-TC-MIB)

NETMOD also worked on foundational configuration models such as system, interface, and routing. These models are part of a class of open models that are meant to be independent from the platform. The intent is also to normalize configuration syntax across vendors. Open YANG models are developed by the IETF, the ITU agency, the OpenConfig consortium, and other standards bodies. Conversely, native models are developed by equipment manufacturers. The models may be specialized to features or syntax specific to that device type, model, or platform.

Besides being the data modeling language for NETCONF, YANG also became associated with RESTCONF and gRPC, which is covered in Chapter 12, “Model-Driven Telemetry,” for streaming telemetry.

Let’s look at some of the structure of YANG modules by using a familiar construct such as device interfaces. Review the IETF’s implementation of the interface’s YANG model at https://github.com/YangModels/yang/blob/master/standard/ietf/RFC/ietf-interfaces.yang.

As we review Figure 11-10, you’ll see some easy-to-understand constructs.

Figure 11-10 ietf-interfaces YANG Model

In this figure, you can see a module name, ietf-interfaces, with version, namespace, and prefix. The standard ietf-yang-types, mentioned earlier, are imported for use in this model, so data types are recognized. If you navigate down to the interfaces section as in Figure 11-11, you see more familiar structure.

Figure 11-11 ETF-interfaces YANG Model—Interfaces Section

Specifically, note the container component called interfaces, which has hierarchy over a of list of individual interface items, keyed by name. Then below that in the hierarchy is the name as a leaf component.

At this point, the verbosity of the YANG model may make comprehension a bit difficult. Using a tool like pyang from Github at https://github.com/mbj4668/pyang can be more helpful in familiarizing yourself with the model.

The pyang tool is used to validate and transform YANG models. It also has a code generator function, which is helpful when you get more in depth with YANG. It can easily be installed to a Python development environment, such as a virtual environment, with the pip command shown in Example 11-12.

Example 11-12 Pip Installing pyang

(pyang) [yanguser@pthon-vm pyang]$ pip install pyang
Collecting pyang
  Downloading https://files.pythonhosted.org/packages/12/22/16c98564086f4f5901b7e8d8
86ad928ce6eceb577b3504edc333762df92f/pyang-2.4.0-py2.py3-none-any.whl (591kB)
      593kB 1.8MB/s
Collecting lxml (from pyang)
  Downloading
https://files.pythonhosted.org/packages/e5/d7/2d8b9e1d4fe05b8b72b3d2345d5a741b005640
681482502b5ce3d8f020d4/lxml-4.6.3-cp38-cp38-manylinux1_x86_64.whl (5.4MB)
      5.4MB 29.2MB/s
Installing collected packages: lxml, pyang
Successfully installed lxml-4.6.3 pyang-2.4.0
(pyang) [yanguser@pthon-vm pyang]$

After installing the pyang utility, you can use it to review the ietf-interfaces.yang module. First, you need to download the YANG module; then you use the utility to read it in a tree format. Because you’re looking at the GitHub ietf-interfaces YANG model, note that the official reference of https://github.com/YangModels/yang/blob/master/standard/ietf/RFC/ietf-interfaces.yang is actually a symbolic link to a date-referenced version that aligns to RFC updates. As of this writing, the latest correct reference is https://raw.githubusercontent.com/YangModels/yang/master/standard/ietf/RFC/ietf-interfaces%402018-02-20.yang; this is what you should reference to download with wget, as shown in Example 11-13.

Example 11-13 Using the wget Utility to Download the YANG Model

(pyang) [yanguser@python-vm pyang]$ wget https://raw.githubusercontent.com/
YangModels/yang/master/standard/ietf/RFC/ietf-interfaces%402018-02-20.yang
--2021-04-18 16:59:41-- https://raw.githubusercontent.com/YangModels/yang/master/
standard/ietf/RFC/ietf-interfaces%402018-02-20.yang
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133,
185.199.110.133, 185.199.109.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.
com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 39365 (38K) [text/plain]
Saving to: '[email protected]'

[email protected] 100%[===============================================
=======>] 38.44K --.-KB/s in 0.008s

2021-04-18 16:59:41 (4.67 MB/s) - '[email protected]' saved
[39365/39365]

(pyang) [yanguser@python-vm pyang]$ pyang -f tree [email protected]
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 admin-status                 enumeration {if-mib}?
  |     +--ro oper-status                  enumeration
  |     +--ro last-change?                yang:date-and-time
  |     +--ro if-index                     int32 {if-mib}?
  |     +--ro phys-address?               yang:phys-address
  |     +--ro higher-layer-if*             interface-ref
  |     +--ro lower-layer-if*              interface-ref
  |     +--ro speed?                      yang:gauge64
  |     +--ro statistics
  |        +--ro discontinuity-time     yang:date-and-time
  |        +--ro in-octets?            yang:counter64
  |        +--ro in-unicast-pkts?      yang:counter64
  |        +--ro in-broadcast-pkts?    yang:counter64
  |        +--ro in-multicast-pkts?    yang:counter64
  |        +--ro in-discards?          yang:counter32
  |        +--ro in-errors?            yang:counter32
  |        +--ro in-unknown-protos?    yang:counter32
  |        +--ro out-octets?           yang:counter64
  |        +--ro out-unicast-pkts?     yang:counter64
  |        +--ro out-broadcast-pkts?   yang:counter64
  |        +--ro out-multicast-pkts?   yang:counter64
  |        +--ro out-discards?         yang:counter32
  |        +--ro out-errors?           yang:counter32
  x--ro interfaces-state
     x--ro interface* [name]
        x--ro name                string
        x--ro type                identityref
        x--ro admin-status        enumeration {if-mib}?
        x--ro oper-status         enumeration
        x--ro last-change?       yang:date-and-time
        x--ro if-index            int32 {if-mib}?
        x--ro phys-address?      yang:phys-address
        x--ro higher-layer-if*    interface-state-ref
        x--ro lower-layer-if*     interface-state-ref
        x--ro speed?             yang:gauge64
        x--ro statistics
           x--ro discontinuity-time     yang:date-and-time
           x--ro in-octets?            yang:counter64
           x--ro in-unicast-pkts?      yang:counter64
           x--ro in-broadcast-pkts?    yang:counter64
           x--ro in-multicast-pkts?    yang:counter64
           x--ro in-discards?          yang:counter32
           x--ro in-errors?            yang:counter32
           x--ro in-unknown-protos?    yang:counter32
           x--ro out-octets?           yang:counter64
           x--ro out-unicast-pkts?     yang:counter64
           x--ro out-broadcast-pkts?   yang:counter64
           x--ro out-multicast-pkts?   yang:counter64
           x--ro out-discards?         yang:counter32
           x--ro out-errors?           yang:counter32
(pyang) [yanguser@python-vm pyang]$

Looking at Figure 11-12 with annotations, you can more easily understand the structure, syntax, and data-type representations.

Figure 11-12 ietf-interfaces YANG Model Processed Through pyang

The Evolution with RESTCONF

Although NETCONF was a lot of fun to start with in 2007, YANG brought better structure to the use of the protocol in 2010. However, the notion of software-defined networking (SDN) lit a fire under vendors to enable their management products and devices with APIs. RESTful APIs were useful for many use cases. The question became, “Can we make NETCONF a bit more RESTful API like?” Thus, RESTCONF came into being with the publication of the IETF’s RFC 8040 in 2017. There, it is defined as

an HTTP-based protocol that provides a programmatic interface for accessing data defined in YANG, using the datastore concepts defined in the Network Configuration Protocol (NETCONF).

While RESTCONF provides an API-like functionality using familiar HTTP-based techniques, some feature-parity still must be addressed. You may find yourself using hybrid management tasks that include both NETCONF and RESTCONF until that time comes.

The RESTCONF Protocol Stack

As defined in RFC 8040, RESTCONF is an HTTP-based protocol, but HTTPS is the only supported transport. For obvious security reasons, HTTPS was defined as the secure extension to HTTP. Installing and configuring an SSL/TLS certificate enable the use of the HTTPS protocol to establish a secure connection with the network device.

RESTCONF continues the alignment to YANG data model definitions that you learned with NETCONF. It also facilitates the use of XML or JSON data encoding. When you look at Figure 11-13, the RESTCONF protocol stack becomes more clear.

Figure 11-13 RESTCONF Protocol Stack

RESTCONF Operations

Similar to RESTful APIs, RESTCONF uses a familiar request/response model where the management tool or application makes a request to the network device that provides the response. Ideally, you get a familiar HTTP 200 OK response!

The use of REST APIs also parallels create, retrieve, update, delete (CRUD)–style operations. Table 11-5 shows a mapping of NETCONF operations to HTTP operation and RESTCONF equivalents.

Table 11-5 Mapping of NETCONF to HTTP/RESTCONF Operations

NETCONF

RESTCONF (HTTP)

<get>, <get-config>

GET

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

POST

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

PUT

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

PATCH

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

DELETE

Content-Type and Accept headers are often used to define the data type being sent from the requester and the desired type to be returned. Here are the options to define the data being sent from the requester:

Content-Type: application/yang-data+json

Content-Type: application/yang-data+xml

And here are the options to define the desired data type to be returned:

Accept: application/yang-data+json

Accept: application/yang-data+xml

RESTCONF and Authentication

RESTCONF operates much like other RESTful APIs and requires authentication. It uses basic authentication, as defined in RFC 7617, where a request contains a header field in the form of Authorization: Basic <credentials>. In this form, credentials is the Base64 encoding of username and password joined by a single colon (:).

It is simple to generate the authentication string on macOS or other Linux derivatives using the built-in openssl binary. Windows platforms can achieve the same by installing OpenSSL or obtaining a Base64 encoding utility.

Note

Do not use an online website to generate Base64-encoded authentication strings. It is not known whether the site is logging the user input, and security may be undermined.

Example 11-14 shows an example of generating a basic authentication string with openssl on macOS. Try it on your system.

Example 11-14 Generating Base64 Basic Authentication String on a Mac

Mac ~ % echo -n 'myusername:DevNet4U!' | openssl base64
bXl1c2VybmFtZTpEZXZOZXQ0VSE=

The basic authentication mechanism does not provide confidentiality of the transmitted credentials. Base64 is only encoding data; it is not equivalent to encryption or hashing. So, basic authentication must be used in conjunction with HTTPS to provide confidentiality through an encrypted transport session, as is required in RESTCONF.

RESTCONF URIs

All RESTCONF URIs follow this format:

https://<DeviceNameOrIP>/<ROOT>/data/<[YANGMODULE:]CONTAINER>/

   <LEAF>[?<OPTIONS>]

The components are explained in Table 11-6.

Table 11-6 RESTCONF URI Components

Component

Explanation

https://

The default, secure HTTP transport, as specified by RFC 8040.

DeviceNameOrIP

The DNS name or IP address for the RESTCONF agent; also provides the port (such as 8443) if using a nonstandard port other than 443.

<ROOT>

The main branch for RESTCONF requests. The de facto convention is restconf, but it should be verified to ensure proper operation.

data

The RESTCONF API resource type for data. An operations resource type accesses RPC operations.

[YANG MODULE:]CONTAINER

The base model container being used; inclusion of the module name is optional.

LEAF

An individual element from within the container.

[?<OPTIONS>]

Query parameters that modify or filter returned results; see Table 11-7.

Optional query parameters or options are explained in Table 11-7.

Table 11-7 Optional RESTCONF Query Parameters

Query Parameter

Explanation

depth=unbounded

Follow nested models to end [Integer value] = only to specified hierarchical depth

depth=N

Follow nested model to hierarchical depth of N level(s)

content=all

Show all types of returned data (default)

content=config

Show only configuration-related data

content=nonconfig

Show only non-configuration-related data, essentially operational data

fields=<expr>

Limit what leaves are returned to the expression, <expr>

Before connecting to a RESTCONF server, you must determine the root, or the main branch, for NETCONF requests. Per the RESTCONF standard and RFC 6415, devices expose a resource called /.well-known/host-meta to enable discovery of the root programmatically.

Example 11-15 shows how to obtain this information via cURL, but you can use well-known tools like Postman that are shown in the next section. You access the DevNet Sandbox environment and the IOS XE on CSR Recommended Code Always On lab. For the latest DevNet Sandbox information, go to https://devnetsandbox.cisco.com.

Example 11-15 Determining Main Branch for NETCONF Requests

[restconfuser@python-vm ~]$ curl --insecure -u developer:C1sco12345 https://sandbox-
iosxe-latest-1.cisco.com:443/.well-known/host-meta
<XRD xmlns='http://docs.oasis-open.org/ns/xri/xrd-1.0'>
    <Link rel='restconf' href='/restconf'/>
</XRD>

In your situation, use the --insecure option if using a self-signed certificate on the managed device, or remove it if using registered certificates. For the DevNet Sandbox environment, the NETCONF agent is purposely registered on port 9443, which is different than yours if using defaults. Also, your specific username-password combination for basic authentication will be different.

Note that the device returns XML-formatted data with an XRD element. There also may be multiple Link child elements; if so, the one of note is the entry with the rel attribute of restconf. In this case, the href attribute value of /restconf/ is the information you need, ­matching the normal convention.

Performing a RESTCONF GET Operation with cURL

For the next example, let’s continue the focus on device interfaces in the IETF-INTERFACES YANG model, as we discussed earlier. In Example 11-16, you can continue to use cURL, but now access the NETCONF URI at https://sandbox-iosxe-latest-1.cisco.com:443/restconf/data/ietf-interfaces:interfaces.

Example 11-16 Using RESTCONF to Get Interface Information with cURL

[restconfuser@python-vm ~]$ curl --insecure -u developer:C1sco12345 https:// sand-
box-iosxe-latest-1.cisco.com:443/restconf/data/ietf-interfaces:interfaces

<interfaces xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces" xmlns:if="urn:ietf:
params:xml:ns:yang:ietf-interfaces">
  <interface>
    <name>GigabitEthernet1</name>
    <description>MANAGEMENT INTERFACE - DON’T TOUCH ME</description>
    <type xmlns:ianaift="urn:ietf:params:xml:ns:yang:i
ana-if-type">ianaift:ethernetCsmacd</type>
    <enabled>true</enabled>
    <ipv4 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
      <address>
        <ip>10.10.20.48</ip>
        <netmask>255.255.255.0</netmask>
      </address>
    </ipv4>
    <ipv6 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
    </ipv6>
  </interface>
  <interface>
    <name>GigabitEthernet2</name>
    <description>Configured by RESTCONF</description>
    <type xmlns:ianaift="urn:ietf:params:xml:ns:yang:i
ana-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>
      <address>
        <ip>10.255.255.1</ip>
        <netmask>255.255.255.0</netmask>
      </address>
    </ipv4>
    <ipv6 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
    </ipv6>
  </interface>
  <interface>
    <name>GigabitEthernet3</name>
    <description>Configured by RSTconf</description>
    <type xmlns:ianaift="urn:ietf:params:xml:ns:yang:i
ana-if-type">ianaift:ethernetCsmacd</type>
    <enabled>true</enabled>
    <ipv4 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
      <address>
        <ip>10.255.244.14</ip>
        <netmask>255.255.255.0</netmask>
      </address>
    </ipv4>
    <ipv6 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
    </ipv6>
  </interface>
  <interface>
    <name>Loopback1000</name>
    <description>Added with Restconf</description>
    <type xmlns:ianaift="urn:ietf:params:xml:ns:yang:i
ana-if-type">ianaift:softwareLoopback</type>
    <enabled>true</enabled>
    <ipv4 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
      <address>
        <ip>1.1.5.5</ip>
        <netmask>255.255.255.255</netmask>
      </address>
    </ipv4>
    <ipv6 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
    </ipv6>
  </interface>
  <interface>
    <name>Loopback1313</name>
    <description>'test interface'</description>
    <type xmlns:ianaift="urn:ietf:params:xml:ns:yang:i
ana-if-type">ianaift:softwareLoopback</type>
    <enabled>false</enabled>
    <ipv4 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
      <address>
        <ip>13.13.13.13</ip>
        <netmask>255.255.255.255</netmask>
      </address>
    </ipv4>
    <ipv6 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
    </ipv6>
  </interface>
</interfaces>

How many interfaces do you see in the DevNet Sandbox IOS XE on CSR Recommended Code Always On lab device? How many interfaces are enabled?

If you had another device with many interfaces, this could be a much larger result! You can get a subset of this information by specifying a desired leaf, as with Example 11-17, using the following URI: https://sandbox-iosxe-latest-1.cisco.com:443/restconf/data/ietf-interfaces:interfaces/interface=GigabitEthernet2.

Example 11-17 Querying for Interface-Specific Results with RESTCONF and cURL

[restconfuser@python-vm ~]$ curl --insecure -u developer:C1sco12345 https://
sandbox-iosxe-latest-1.cisco.com:443/restconf/data/ietf-interfaces:interfaces/
interface=GigabitEthernet2

<interface xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces" xmlns:if="urn:ietf:p
arams:xml:ns:yang:ietf-interfaces">
  <name>GigabitEthernet2</name>
  <description>Configured by RESTCONF</description>
  <type xmlns:ianaift="urn:ietf:params:xml:ns:yang:i
ana-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>
    <address>
      <ip>10.255.255.1</ip>
      <netmask>255.255.255.0</netmask>
    </address>
  </ipv4>
  <ipv6 xmlns="urn:ietf:params:xml:ns:yang:ietf-ip">
  </ipv6>
</interface>

Excellent! Now you can try your hand at modifying a configuration using RESTCONF.

Performing RESTCONF GET Operations with the Postman Utility

Because we’re going to eventually pivot to performing a REST PUT operation, you can also switch to using the Postman utility. Postman is a multiplatform utility that is helpful in doing API testing. It also has a helpful code generator that can be the starting point for scripting work. You can obtain Postman free from https://www.postman.com. You may also be interested in the DevNet Postman collection at https://www.postman.com/ciscodevnet.

For this example, create a new collection called RESTCONF, as seen in Figure 11-14.

Figure 11-14 Creating a Postman Collection

Also, for ease of use, on the collection-level Authorization tab, set Type to Basic Auth and the username and password to their appropriate values. Setting the values at the collection-level allows you to inherit these authorization sessions for all other requests in the containing collection or folder.

To reinforce the previous experience with cURL, build a Postman equivalent of pulling the same IETF-INTERFACES YANG model data. Yours should look similar to Figure 11-15.

Figure 11-15 Creating a Postman Request to a GET Interface

On the Authorization tab, you should see Inherit Auth from Parent. The operation should be GET, and the request URL should be https://sandbox-iosxe-latest-1.cisco.com:443/restconf/data/ietf-interfaces:interfaces/interface=GigabitEthernet2.

Now, if you execute the request by clicking the Send button, you get results similar to Figure 11-16.

Figure 11-16 Executing a Postman Request to a GET Interface

If you click the Code button, which appears as the </> icon, on the right side and select Python > Requests, then you get the helpful code snippet shown in Example 11-18.

Example 11-18 Postman Code Snippet

import requests

url = "https://sandbox-iosxe-latest-1.cisco.com:443/restconf/data/
ietf-interfaces:interfaces/interface=GigabitEthernet2"

payload={}
headers = {
  'Authorization': 'Basic ZGV2ZWxvcGVyOkMxc2NvMTIzNDU='
}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)

How cool is that!? This code can serve to seed a more sophisticated Python script. Of course, you should do some appropriate security cleanup, such as removing the credentials from being fixed in your script, but it’s a start!

Let’s do one more GET operation to exercise your understanding of using query options (parameters). Now create a copy of the earlier Postman request, but this time onto the end of the URI, add ?fields=name;description;enabled. Your entry (and execution) should be similar to Figure 11-17.

Figure 11-17 Executing a Postman Request to GET Interface with Query Option

Now that you’ve rebuilt the GET method in Postman, you can pivot to doing a PUT operation and pushing an updated interface description into the device, as you did earlier with NETCONF means.

Create a copy of the GET Interface request, but save it as PUT Interface Description. In the new request, change the request type from GET to PUT. Select the Headers tab and create or modify the Content-Type header to a value of application/yang-data+xml. On the Body tab, select the Raw option and paste the following:

<interface xmlns="urn:ietf:params:xml:ns:yang:ietf-interfaces"  xml
ns:if="urn:ietf:params:xml:ns:yang:ietf-interfaces">

    <name>GigabitEthernet2</name>

    <description>Configured by RESTCONF again</description>

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

</interface>

You can make the description anything you like. After you click Send, the results should appear similar to Figure 11-18.

Figure 11-18 Creating and Executing a Postman Request to PUT Interface Description

Again, you can use the Postman Code feature to generate a Python-Requests code snippet, allowing you to create more robust scripts that would programmatically change the device configuration with RESTCONF via Python.

Try your hand at getting information in JSON format. Remember that you’ll need to change the Accept header for a GET operation to application/yang-data+json. See Figure 11-19 as the JSON equivalent to the operation performed in Figure 11-16.

Figure 11-19 Executing a Postman Request to GET Interface Information as JSON

Hopefully, you’re seeing the prospects of using RESTCONF to programmatically obtain and change device settings.

Management Solutions Using NETCONF and RESTCONF

By now, you’ve seen a few manual methods to interact with NETCONF using an SSH terminal emulator. You’ve also seen manual methods to interact with RESTCONF using cURL, Postman, and the Python code snippets it generates. Some commercial management products that leverage NETCONF and RESTCONF methods may be appealing in your situation.

Tail-f Systems was one of the first companies to release a commercial application that embraced NETCONF. The company’s Network Control System (NCS) product was created by several industry shapers of the NETCONF protocol. Cisco acquired Tail-f Systems in 2014, with the product evolving into Cisco’s Network Services Orchestrator (NSO). NSO is a multivendor configuration management platform that provides a north-bound abstraction layer to managed devices using network element drivers (NEDs), which may involve NETCONF, SNMP, SSH, or REST methods to interact with the managed devices.

NSO is widely used by large service providers and enterprise companies to solve their multivendor and model-driven configuration management challenges. More information is available on NSO at https://www.cisco.com/c/en/us/products/cloud-systems-management/network-services-orchestrator/index.html.

A DevNet-specific portal for NSO can be found at https://developer.cisco.com/site/nso/.

Increasingly more and more management tools are pivoting from SNMP-initiated TFTPing of configurations as text files or SSH-driven pasting of the same to NETCONF- and RESTCONF-style management. Be on the lookout for NETCONF/RESTCONF setting requirements with your next set of tools, and ask your vendors when they’ll support the newer style management methods!

If you’re using open-source solutions, pyang is an excellent utility for validating and inspecting YANG models without the verbosity of the YANG model file. Cisco has provided another graphical tool, YANG Suite, available at https://developer.cisco.com/yangsuite/.

Ansible supports the following modules that are helpful with NETCONF:

  • community.yang.fetch

  • community.yang.get

  • community.yang.configure

  • community.yang.generate_spec

In the summer of 2020, work was started on the ansible.netcommon.restconf HttpApi plug-in for devices supporting RESTCONF API.

If you are a Puppet user, check out this DevNet Code Exchange entry that uses Puppet and NETCONF to manage IOS XR-based devices: https://developer.cisco.com/codeexchange/github/repo/cisco/cisco-yang-puppet-module/.

The previous examples of using Postman and the Code generator, especially for Python-Requests code snippets, should be helpful to get you started with RESTCONF options. Consider the next time you have a need to change all Syslog and SNMP trap receivers in your environment. In the past, have you simply jammed the new ones in the configurations and held off on removing the old ones? Were you sure you got all decommissioned options out of the configuration? By using the newer manageability protocols and some simple Python scripting, you will be able to execute mass configuration updates and do it quickly and effectively!

Exam Preparation Tasks

As mentioned in the section “How to Use This Book” in the Introduction, you have a couple of choices for exam preparation: the exercises here, Chapter 17, “Final Preparation,” and the exam simulation questions in the Pearson Test Prep Software Online.

Review All Key Topics

Review the most important topics in this chapter, noted with the Key Topic icon in the outer margin of the page. Table 11-8 lists a reference of these key topics and the page numbers on which each is found.

Table 11-8 Key Topics for Chapter 11

Key Topic Element

Description

Page Number

Paragraph

NETCONF definition

348

Figure 11-1

NETCONF Conceptual Layers

349

Table 11-2

NETCONF Protocol Operations

350

Paragraph

Enabling NETCONF on IOS-XE

355

Paragraph

Enabling NETCONF on NX-OS

358

Paragraph

YANG definition

365

Example 11-13

Using the wget Utility to Download the YANG Model

369

Figure 11-13

RESTCONF Protocol Stack

372

Paragraph

NETCONF/YANG IETF interfaces

375

Complete Tables and Lists from Memory

Print a copy of Appendix C, “Memory Tables” (found on the companion website), or at least the section for this chapter, and complete the tables and lists from memory. Appendix D, “Memory Tables Answer Key,” also on the companion website, includes completed tables and lists to check your work.

Define Key Terms

Define the following key terms from this chapter and check your answers in the glossary:

NETCONF (network configuration)

RESTCONF

YANG

References

URL

QR Code

https://developer.cisco.com/site/sandbox/

https://github.com/YangModels/yang/blob/master/standard/ietf/RFC/ietf-interfaces.yang

https://github.com/mbj4668/pyang

https://devnetsandbox.cisco.com

https://www.postman.com

https://www.postman.com/ciscodevnet

https://www.cisco.com/c/en/us/products/cloud-systems-management/network-services-orchestrator/index.html

https://developer.cisco.com/site/nso/

https://developer.cisco.com/yangsuite/

https://developer.cisco.com/codeexchange/github/repo/cisco/cisco-yang-puppet-module/

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.195.97