The script should iterate over the XE group, and do a “sync-from” for each device
You can make a change to R1 and R2 to confirm that it works properly.
Task 1 Answer
# Sync-from all devices in NCS manually
ncs_cli -Cu admin
devices device-group XE sync-from
# Make a change to R1 and R2 directly
int Lo12
ip address 12.12.12.12 255.255.255.255
# Use the "sync_from()" method to sync from the device
# Use the devices.device_group[name].device_name list to
# get a list of devices in that group
import ncs
with ncs.maapi.single_read_trans('admin', 'python') as t:
root = ncs.maagic.get_root(t)
device_group = root.devices.device_group['XE']
for device in device_group.device_name:
device_object = root.devices.device[device]
print(f'syncing from {device_object.name}')
device_object.sync_from()
Check that the change was successfully synced:
A note about iterating through the device group
All NCS config is modeled via XML, which means it can be accessed hierarchically from the python API. You simply replace the hyphens with an underscore.
For example, notice that a device group contains a leaf-list of device-names:
This becomes devices.device_group[’XE’].device_name in python. You can then grab each device name and index that device name via root.devices.device[device_name]:
with ncs.maapi.single_read_trans('admin', 'python') as t:
root = ncs.maagic.get_root(t)
device_group = root.devices.device_group['XE']
for device in device_group.device_name:
device_object = root.devices.device[device]
Task 2. Delete loopback script
Create a new script that deletes any loopback12 on all XE routers.
Task 2 Answer
import ncs
with ncs.maapi.single_write_trans('admin', 'python') as t:
root = ncs.maagic.get_root(t)
device_group = root.devices.device_group['XE']
for device in device_group.device_name:
device_object = root.devices.device[device]
print(f'Deleting Loop12 for {device_object.name}')
del device_object.config.ios__interface.Loopback['12']
try:
t.apply()
except Exception as e:
print(e)
pass
Where does the “ios__interface” come from? You can gather this by showing the full config in NCS and displaying as xpath. The colon (:) is replaced with double underscore (__) in python:
Note that only a single transaction is supported per transaction opened using “with ncs.maapi.single_write_transaction()”. This means you need to iterate over all devices, and then at the end apply the transaction. You cannot apply the transaction after each device change.