How to Create Your First Cisco NSO Playbook

Learn how Cisco NSO automates network configuration using model-driven orchestration, transactional commits, and RESTCONF APIs.


Cisco CCNA Automation course – 037 – Describe the capabilities of Cisco network management platforms and APIs (NSO)

Watch Full Demo on YouTube:


Introduction

One of the key platforms in this section is Cisco NSO — Network Services Orchestrator. NSO is not a monitoring tool or a simple dashboard. It is a network automation and orchestration engine that sits between your automation layer and your actual network devices, and it manages configuration changes in a structured, model-driven, and fully transactional way.

If you have ever had to make the same configuration change across dozens of routers or switches by logging into each one manually, you already understand the problem NSO is designed to solve. If you have ever made a change on a device and later needed to undo it, but had no clean way to reverse exactly what you did, you understand why NSO’s rollback capability matters. And if you have ever wanted to push configuration to devices through a Python script without worrying about SSH sessions, command-line syntax differences between vendors, or inconsistent outputs, you understand why NSO’s API matters.

This post covers both the theory behind NSO and a hands-on lab walkthrough, including a Python RESTCONF script that creates loopback interfaces on multiple devices simultaneously through the NSO API.


What Is Cisco NSO?

Cisco NSO is a network automation and orchestration platform that allows you to manage the configuration of network devices from a single centralised system. It supports multi-vendor environments, meaning it can manage Cisco devices, and devices from other vendors — all through the same platform.

NSO sits between you and your devices. Instead of sending configuration directly to a device through SSH or a proprietary tool, you work through NSO. NSO understands the configuration model for each device type, translates your intended changes into the correct syntax for that device, pushes the change, tracks what was done, and gives you the ability to roll it back if needed.

This changes the operational model significantly. Instead of thinking about devices individually, you start thinking about configuration intent and letting NSO handle the translation and delivery to each device.

NSO uses a model-driven approach. Every piece of configuration that NSO manages is defined in a data model using a language called YANG. YANG models describe the structure and constraints of configuration data in a precise and structured way. This is what allows NSO to understand configuration at a higher level of abstraction rather than just storing raw CLI text.


What Problem Does NSO Solve?

The core problem NSO solves is the operational complexity of managing configuration across a large number of devices in a consistent, safe, and auditable way.

In a traditional network operations model, engineers SSH into devices individually, type commands manually, and hope that the changes applied correctly. If something goes wrong, the only way to undo it is to either remember exactly what was changed and reverse it manually, or rely on a backup that may be hours old. If the same change needs to be applied to fifty devices, it either gets scripted in a way that is hard to validate or done manually in a way that is slow and error-prone.

NSO addresses this by providing a transactional model for network configuration. Every change you make in NSO is treated as a transaction. Before the change goes anywhere near a device, NSO validates it, shows you exactly what is going to be changed, and allows you to review it. When you commit, NSO pushes the change to the device. If the commit fails for any reason, NSO can roll back automatically. And after a successful commit, NSO stores a rollback file that lets you reverse the change at any time in the future.

NSO also solves the multi-vendor problem. Different device types have different CLI syntax, different NETCONF schemas, and different configuration models. NSO abstracts all of this through Network Element Drivers, which we will cover shortly. From your perspective, you work with a consistent data model regardless of which vendor’s device you are targeting.

Another problem NSO solves is configuration drift. Configuration drift happens when a device’s actual running configuration no longer matches what your automation system believes it should be. This commonly happens when someone makes a manual change directly on a device outside of the automation platform. NSO has a sync mechanism that can detect and flag these inconsistencies.


NSO Core Architecture and Key Components

Understanding NSO’s architecture helps you understand how it manages devices and why it behaves the way it does.

The Configuration Database (CDB)

The Configuration Database, or CDB, is NSO’s internal database. It stores a structured representation of the configuration for every device NSO manages. This is not raw CLI text — it is structured, YANG-modelled data that NSO can read, compare, validate, and push to devices.

The CDB is the source of truth inside NSO. When NSO needs to know what configuration a device should have, it reads from the CDB. When you make a change in NSO, you are writing to the CDB. When NSO syncs with a device, it is comparing the device’s live configuration against what the CDB has stored.

The CDB has different datastores. The running datastore is the active, committed configuration. The candidate datastore is where changes are staged before they are committed. This separation is important because it means you can build up a set of changes, review them, and only apply them when you are ready.

Network Element Drivers (NEDs)

A Network Element Driver, or NED, is a plugin that teaches NSO how to communicate with a specific type of device. Every device family that NSO manages requires a corresponding NED.

The NED does two things. First, it defines the YANG data model for that device, which tells NSO what configuration options are available and how they are structured. Second, it handles the communication protocol — whether that is SSH with CLI, NETCONF, SNMP, or a REST API. The NED translates between NSO’s internal data model and the actual commands or protocol operations the device understands.

From your perspective as a user, the NED is what makes the abstraction possible. You define what you want the device to look like in NSO’s data model, and the NED figures out the right commands to send to make that happen on the actual device.

Services

Services in NSO are automation models that represent a higher-level intent rather than raw device configuration. A service takes a set of input parameters and translates them into the device-level configuration needed to deliver that service across one or more devices.

For example, a VLAN service might take a VLAN ID and a list of switches as input, and then automatically generate and push the correct VLAN configuration to each of those switches. An L3VPN service might take customer and routing details and generate all the configuration needed across multiple routers to establish that VPN.

Services in NSO are defined as packages using YANG models and code. When a service is deployed, NSO tracks exactly which device configuration it created. When the service is deleted, NSO automatically removes that configuration from all the affected devices. This is called service lifecycle management.

Packages

Packages are how functionality is added to NSO. A package can contain a NED for a device type, a service model, a utility tool, or a combination of these things. NSO loads packages at startup and can reload them without restarting the whole system.

The packages installed on an NSO instance determine which device types it can manage and which services it can offer. A minimal NSO instance might only have one or two packages. A production NSO instance managing a large multi-vendor network might have many packages for different device types and services.

The Northbound Interfaces

NSO exposes several interfaces for external systems and users to interact with it. These are called northbound interfaces.

The CLI is a command-line interface that experienced NSO users and developers use for advanced operations and debugging. The web UI is the browser-based dashboard that provides a graphical way to navigate devices, services, the configuration editor, and tools. NETCONF is a standards-based protocol for configuration management and is commonly used for programmatic integration. RESTCONF is a REST API implementation based on the same YANG data model, and this is what Python scripts most commonly use. SNMP and JSON-RPC are also supported for specific integration scenarios.


The NSO Dashboard Walkthrough

The NSO web interface provides a structured way to navigate all of the platform’s capabilities. Let’s walk through each section.

Home

The home page is the entry point for the NSO web UI. It gives you a clean launchpad with cards linking to Devices, Services, Config Editor, and Tools. It also shows any installed packages. In a minimal lab environment, you might only see one package such as the REST API Explorer. In a production environment, you would expect to see multiple packages listed here representing the NEDs and service models that have been loaded into the system.

Devices

The Devices section is where NSO maintains its inventory of managed network devices. This is not just a list — it is the record of every device NSO knows about, including each device’s management IP address, connection settings, authentication group, sync status, and current alarm state.

The Devices section has three tabs. Device Management is the main inventory list. Device Groups lets you organise devices into logical collections so you can perform bulk operations across a group of related devices. Authgroups is where you manage authentication credentials. Rather than storing a username and password against every single device record, you create an authgroup with the credentials and assign multiple devices to it. This makes credential rotation much simpler.

From the Device Management list, you can select one or more devices and access the Actions menu. The Actions menu provides several important operations.

Connect establishes a connection to the device to verify that NSO can reach it. Sync From pulls the current running configuration from the device and updates NSO’s CDB. This is what you use when someone has made a manual change directly on the device and you need NSO to catch up. Sync To pushes NSO’s stored configuration out to the device, overwriting whatever is currently on the device. Check Sync compares what NSO has in the CDB against the device’s live configuration and reports whether they match or whether there is a drift. Fetch SSH Host Keys retrieves the device’s SSH host key and stores it in NSO as part of secure connectivity setup. Apply Template stamps a reusable configuration template onto the selected devices.

Services

The Services section is where deployed service instances are managed. You first select a service type from a dropdown, and then NSO shows you all the active instances of that service type.

The service type dropdown is only populated if service packages have been loaded into NSO. In a lab environment with only the REST API Explorer package installed, the dropdown will be empty. In a production environment with service packages deployed, you would see service types such as L3VPN, VLAN provisioning, BGP peering, and whatever else has been developed and loaded as packages.

When you delete a service instance in NSO, NSO does not just remove the record. It automatically calculates and pushes the reversal of every configuration change that service had deployed across all affected devices. This is the service lifecycle management capability that makes NSO so powerful.

Configuration Editor

The Configuration Editor is a visual browser for NSO’s entire YANG data model. Every module that NSO has loaded — whether from a NED, a service package, or NSO’s own internal model — appears here as a navigable entry. You can click into any module and browse the data tree to read configuration values, make changes, and inspect the state of the system.

Some of the most important modules you will see in the Configuration Editor include ncs:devices which holds all device configuration data, ncs:services which holds all service instance data, ncs:packages which lists installed packages, rollback:rollback-files which stores rollback snapshots for every commit, ncs:compliance for compliance reporting, and ncs:zombies which represents service instances that have been deleted but whose device configuration could not be fully cleaned up and are waiting for resolution.

The Configuration Editor is particularly useful during development and troubleshooting because it lets you see exactly what data NSO has stored for any device or service without needing to use the CLI.

Tools — Insights

The Insights page is NSO’s operational health dashboard. It shows real-time metrics about what NSO is doing internally.

The Real Time Insights panel shows the number of running transactions, the commit queue state, the number of open northbound sessions broken down by protocol, and rate-of-change statistics over 1-minute, 5-minute, and 15-minute windows.

The Northbound Sessions panel shows how many sessions have been closed since the last restart and breaks them down by protocol — CLI, JSONRPC, NETCONF, RESTCONF, and SNMP. This tells you which interfaces are being used to interact with NSO.

The Transactions panel shows commit statistics since the last restart including total committed, aborted, and conflicting transactions. It also breaks down where time is being spent in the transaction processing pipeline — in service execution, in validation, in the critical section, and waiting for locks.

The Devices panel shows the total number of managed devices, the number of sync-from and sync-to operations that have been performed, successful and failing connects, and out-of-sync detections.

The CDB panel shows the current size of NSO’s configuration database in both memory and on disk, broken down by config data, operational data, and snapshot data.

Tools — Commit Manager

The Commit Manager is where staged configuration changes are reviewed and committed. This is one of the most important tools in NSO’s UI because it gives you full visibility and control over what is about to be pushed to your network before it actually happens.

The Commit Manager shows the current transaction status at the top — for example, “Current transaction (3 – webui-one) is VALID”. This immediate validation feedback tells you whether NSO has detected any errors in your pending changes before you even look at the details.

There are two important action buttons alongside the Commit button. Revert discards all staged changes and returns the candidate configuration to the last committed state. Load/Save lets you save your pending changes to a file or load a previously saved configuration — useful when working on complex multi-step changes.

The Commit Manager has five tabs.

The Changes tab gives you a detailed, row-by-row breakdown of every modification in the current transaction. Each row shows the full YANG path to the changed element, the type of operation being performed (such as value_set, created, or modified), the old value, and the new value. The paths are clickable links that take you directly to that element in the Configuration Editor. This level of granularity means there is no ambiguity about what the transaction contains.

The Errors tab shows any validation errors that NSO has detected in the pending changes. If the transaction status shows VALID, this tab will be empty.

The Warnings tab shows non-blocking issues — things that are not errors but that NSO wants to flag for your attention before you commit.

The Config tab shows a side-by-side diff view of the configuration. The left side shows the current state and the right side shows what the configuration will look like after the commit. New additions are highlighted in green with plus symbols. Removals would appear in red with minus symbols. This visual diff is extremely clear and removes any guesswork about what is going to change.

The Native Config tab shows the actual device-level CLI commands or NETCONF operations that will be sent to each device as a result of this commit. This is the translation that NSO’s NED performs — from the abstract YANG model all the way down to the specific syntax the device understands.

The Commit Queue tab shows how NSO will handle the delivery of this transaction. You can control whether changes are pushed immediately or queued. In environments with many devices, the commit queue allows you to control sequencing and handle devices that may be temporarily unreachable.


Python RESTCONF Script — Creating Loopback Interfaces via NSO API

The final part of the lab demonstrates NSO’s RESTCONF API by using a Python script to create Loopback99 on two routers simultaneously.

The Script

import json
import requests
from requests.auth import HTTPBasicAuth
from urllib.parse import quote

# -----------------------------
# NSO Connection Details
# -----------------------------
NSO_BASE_URL = "http://10.10.20.47:8080"
NSO_USERNAME = "developer"
NSO_PASSWORD = "C1sco12345"

# -----------------------------
# Loopback Details
# -----------------------------
LOOPBACK_ID = 99
LOOPBACK_DESCRIPTION = "Created by NSO API"

# -----------------------------
# Target IOS-XE Devices
# -----------------------------
TARGET_DEVICES = [
    {
        "device": "dist-rtr01",
        "ip_address": "10.10.20.175",
        "subnet_mask": "255.255.255.255",
    },
    {
        "device": "dev-dist-rtr01",
        "ip_address": "10.10.20.176",
        "subnet_mask": "255.255.255.255",
    },
]

# -----------------------------
# RESTCONF Headers
# -----------------------------
HEADERS = {
    "Accept": "application/yang-data+json",
    "Content-Type": "application/yang-data+json",
}


def build_loopback_url(device_name):
    encoded_device_name = quote(device_name, safe="")
    return (
        f"{NSO_BASE_URL}/restconf/data/"
        f"tailf-ncs:devices/device={encoded_device_name}/"
        f"config/tailf-ned-cisco-ios:interface/"
        f"Loopback={LOOPBACK_ID}"
    )


def build_loopback_payload(ip_address, subnet_mask):
    return {
        "tailf-ned-cisco-ios:Loopback": [
            {
                "name": LOOPBACK_ID,
                "description": LOOPBACK_DESCRIPTION,
                "ip": {
                    "address": {
                        "primary": {
                            "address": ip_address,
                            "mask": subnet_mask,
                        }
                    }
                },
            }
        ]
    }


def create_loopback_on_device(device_info):
    device_name = device_info["device"]
    ip_address = device_info["ip_address"]
    subnet_mask = device_info["subnet_mask"]

    url = build_loopback_url(device_name)
    payload = build_loopback_payload(ip_address, subnet_mask)

    print("=" * 70)
    print(f"Creating Loopback{LOOPBACK_ID} on {device_name}")
    print("=" * 70)
    print(f"Device       : {device_name}")
    print(f"Loopback     : Loopback{LOOPBACK_ID}")
    print(f"IP Address   : {ip_address}")
    print(f"Subnet Mask  : {subnet_mask}")
    print(f"API Endpoint : {url}")
    print()

    response = requests.put(
        url,
        headers=HEADERS,
        auth=HTTPBasicAuth(NSO_USERNAME, NSO_PASSWORD),
        data=json.dumps(payload),
        timeout=30,
    )

    print(f"Status Code: {response.status_code}")

    if response.text:
        print("Response:")
        print(response.text)

    if response.status_code in [200, 201, 204]:
        print(f"SUCCESS: Loopback{LOOPBACK_ID} was created on {device_name}.")
        return True

    print(f"FAILED: Could not create Loopback{LOOPBACK_ID} on {device_name}.")
    return False


def main():
    print("=" * 70)
    print("Creating Loopback Interfaces via NSO RESTCONF API")
    print("=" * 70)
    print(f"NSO URL      : {NSO_BASE_URL}")
    print(f"Loopback ID  : {LOOPBACK_ID}")
    print(f"Description  : {LOOPBACK_DESCRIPTION}")
    print()

    success_count = 0
    for device_info in TARGET_DEVICES:
        if create_loopback_on_device(device_info):
            success_count += 1
        print()

    print("=" * 70)
    print("Summary")
    print("=" * 70)
    print(f"Total devices attempted : {len(TARGET_DEVICES)}")
    print(f"Successful changes      : {success_count}")
    print(f"Failed changes          : {len(TARGET_DEVICES) - success_count}")


if __name__ == "__main__":
    main()

Walking Through the Script

The imports bring in four libraries. json handles serialising Python dictionaries into JSON strings for the request body. requests is the HTTP library used to make the RESTCONF API calls. HTTPBasicAuth wraps the username and password in the correct format for HTTP Basic Authentication. quote from urllib.parse safely encodes device names in the URL so that special characters do not break the path.

The global variables are organised into four clear sections at the top of the script. The NSO connection details define the base URL and credentials. The loopback details define the interface ID and description. The TARGET_DEVICES list defines which devices to target and what IP address to assign on each. The HEADERS dictionary defines the correct MIME type for RESTCONF — application/yang-data+json — which must appear in both the Accept and Content-Type headers.

The main function is the entry point. It prints a summary header, initialises a success counter, loops through every device in TARGET_DEVICES, calls create_loopback_on_device() for each one, and prints a final summary showing how many succeeded and how many failed. This structure means the script handles multiple devices cleanly and reports clearly without stopping entirely if one device fails.

The build_loopback_url function constructs the RESTCONF path for a specific device’s Loopback interface. The path navigates through tailf-ncs:devices, into the specific device using device={device_name}, into its config, into the Cisco IOS interface model using tailf-ned-cisco-ios:interface, and finally targets Loopback=99. This path mirrors the YANG model hierarchy exactly.

The build_loopback_payload function builds the JSON body for the API request. The structure follows the YANG model for a Cisco IOS loopback interface, with the interface name, description, and IP address nested inside tailf-ned-cisco-ios:Loopback. The nesting must match the YANG model exactly or NSO will reject the request.

The create_loopback_on_device function is where the API call happens. It retrieves the device details, builds the URL and payload, prints a detailed block of information to the terminal, and then fires a requests.put() call. PUT is used because RESTCONF uses PUT to create or replace a specific resource at a known path. The function checks the HTTP status code — 200, 201, or 204 all indicate success — and returns True or False accordingly.

The Script Output

======================================================================
Creating Loopback Interfaces via NSO RESTCONF API
======================================================================
NSO URL      : http://10.10.20.47:8080
Loopback ID  : 99
Description  : Created by NSO API

======================================================================
Creating Loopback99 on dist-rtr01
======================================================================
Device       : dist-rtr01
Loopback     : Loopback99
IP Address   : 10.10.20.175
Subnet Mask  : 255.255.255.255
API Endpoint : http://10.10.20.47:8080/restconf/data/tailf-ncs:devices/device=dist-rtr01/config/tailf-ned-cisco-ios:interface/Loopback=99
Status Code: 201
SUCCESS: Loopback99 was created on dist-rtr01.

======================================================================
Creating Loopback99 on dev-dist-rtr01
======================================================================
Device       : dev-dist-rtr01
Loopback     : Loopback99
IP Address   : 10.10.20.176
Subnet Mask  : 255.255.255.255
API Endpoint : http://10.10.20.47:8080/restconf/data/tailf-ncs:devices/device=dev-dist-rtr01/config/tailf-ned-cisco-ios:interface/Loopback=99
Status Code: 201
SUCCESS: Loopback99 was created on dev-dist-rtr01.

======================================================================
Summary
======================================================================
Total devices attempted : 2
Successful changes      : 2
Failed changes          : 0

Both devices returned HTTP status 201, meaning the loopback interfaces were successfully created. The summary at the end confirms two attempts, two successes, and zero failures. Because NSO processed these as proper transactions, both changes are tracked in NSO’s CDB, are visible in the Commit Manager’s history, and can be rolled back if needed.


NSO vs Direct Device Management

It is worth stepping back and comparing what the NSO approach looks like versus traditional direct device management.

In a traditional model, you SSH into each device individually, type the configuration commands, verify the output manually, and move to the next device. If something goes wrong, you manually undo what you did. If you need to apply the same change to fifty devices, you either write a script that talks directly to each device or you do it by hand. There is no central record of what was changed or why.

With NSO, you define the change once through the UI or API, NSO validates it, you review it in the Commit Manager before anything is pushed, NSO pushes it to all targeted devices simultaneously, a rollback file is automatically created, and the change is permanently tracked in the CDB. If you need to undo it, one rollback operation reverses everything cleanly.

The difference becomes even more significant at scale. The Python script in this lab targeted two devices. With exactly the same script, you could target two hundred devices by adding entries to the TARGET_DEVICES list. NSO handles the delivery to every device consistently, in parallel, with full transactional safety.


Conclusion

Cisco NSO is one of the most powerful platforms in the CCNA Automation and DevNet Associate curriculum because it demonstrates what enterprise-grade network automation really looks like in practice. It is not just about scripts talking to devices. It is about having a platform that understands your network’s configuration model, validates every change before it is applied, maintains a complete history of what was done, and gives you a safe and reversible way to manage configuration at scale.

The NSO dashboard gives you a visual way to manage devices, review staged changes in the Commit Manager, browse the entire configuration model in the Configuration Editor, and monitor the platform’s health through the Insights tool. The NSO RESTCONF API gives you a programmable way to do all of the same things — and that is what makes NSO genuinely powerful for network automation.

Whether you are making a single VLAN change through the UI or pushing loopback interfaces to dozens of routers with a Python script, the experience is the same — structured, validated, traceable, and reversible. That is the promise of network automation with NSO, and by the end of this lab, you have seen it working end to end.


References

DevNet Associate – Cisco

DevNet Associate Exam Topics

Cisco NSO Documentation

NSO RESTCONF API Guide

How to get started with the Cisco CCNA Automation course


Discover more from IEE

Subscribe to get the latest posts sent to your email.


Discover more from IEE

Subscribe now to keep reading and get access to the full archive.

Continue reading