NSO API using Python
Load blank.ssh.enabled.cfg
Create a python script that interacts with NSO’s northbound API.
The script should create Lo303 on R3 with ip address 30.30.30.30/32
After creating that loopback, the script should interate through all XE devices and print out each Loopback with its name and IP address.
Answer
Create the following python script on the nso server.
Explanation
First, we need to understand how the loopback interface is accessed in modeled config. This is different than the native IOS-XE config. We have two ways we can see this. One is using “ | display xpath” from NSO:
Another is by staging the config and displaying in XML before aborting.
This gives us the modeled data for a loopback interface.
First the script starts with the following line, which means to do a single write transaction. The next line gets us to the root of the NCS config database. When opening a transaction, you must at minimum specify the user (’admin’) and the context (’python’, as opposed to CLI, web UI etc). This just allows NSO to audit where the change came from.
Next, we start specifically at device r3 and create the loopback first. We must use the create() method. We can’t just assign a new container/list-element using python logic such as [’Loopback’][’300’] = …. Instead we need to use create() so that NSO can validate the new data against the YANG schema.
However, note that while we need to use .create() to create a new list, we can use the python del to delete a leaf. This is because deleting information does not need to be validated against a YANG schema.
Finally, we add the attributes of the interface (the address and mask). Once the container is created using create(), we can add attributes using standard python logic. Using t.apply() applies the config (does a commit) within the transaction that we opened.
Next, we use a single read transaction to iterate through all XE devices and print their loopback information. I use an if statement that checks the NED to determine whether this is XE or XR. We’ll see a better way to iterate over a group in the next lab.
Last updated