Introduction

In today’s dynamic network environments, keeping an accurate and up-to-date inventory of your network devices is crucial. NetBox, a powerful open-source IP address management (IPAM) and data center infrastructure management (DCIM) tool, serves as a single source of truth for network configurations. However, manually updating NetBox with changes from network devices can be time-consuming and error-prone.

This blog post explores a streamlined approach to automate the process of updating NetBox with the latest configurations from Cisco IOS-XE devices. By leveraging the automation capabilities of Ansible, the flexibility of Python, and the scheduling power of cron jobs, you can ensure your NetBox instance remains current with minimal manual intervention. I will walk you through setting up this automation pipeline, from configuring your network devices to ensuring NetBox reflects the latest configurations, all with practical examples and detailed steps.

This guide will cover:

1. Setting Up NetBox: Adding your Cisco IOS-XE devices to NetBox.

2. Configuring Ansible and Python: Fetching device configurations and updating NetBox.

3. Automating with Cron Jobs: Scheduling regular updates to maintain synchronization.

4. Practical Example: Updating NetBox with a new VLAN and SVI configuration on a Cisco IOS-XE 9300.

By the end of this tutorial, you’ll have a robust solution to keep your network device configurations in sync with NetBox, enhancing your network management efficiency and accuracy.

File Structure

/AutomateNetBox/
├── fetch_config.yml
├── update_netbox.yml
├── inventory
├── scripts/
│ └── update_netbox.py

We will use a single IOS-XE device as an example, but feel free to add all your network devices to the ansible inventory host file.

Step 1: Set Up NetBox

  1. Log in to NetBox: Use your browser to navigate to your NetBox instance and log in.
  2. Add the Device: Go to Devices > Add Device and fill out the form to add your Cisco IOS-XE 9300 device. Ensure that you set the device name to match the name you will use in your scripts (e.g., ios-xe-9300-1).

Step 2: Install Required Tools

Make sure Ansible, Python, and the necessary libraries are installed

pip install ansible netmiko pynetbox

Step 3: Configure Ansible Inventory

Create an inventory file for your IOS-XE device.

AutomateNetBox/inventory

[ios_devices] 172.16.20.1 ansible_user=your_username ansible_password=your_password ansible_network_os=ios

Step 4: Create Ansible Playbook to Fetch Device Configurations

Create an Ansible playbook to fetch the current configurations from the IOS-XE device.

AutomateNetBox/fetch_config.yml


– name: Fetch IOS Device Configurations
hosts: ios_devices
gather_facts: no
tasks:
– name: Gather running configuration
ios_command:
commands:
– show running-config
register: running_config

– name: Save configuration to file
copy:
content: “{{ running_config.stdout[0] }}”
dest: “/tmp/{{ inventory_hostname }}_config.txt”

Step 5: Create Python Script to Update NetBox

Create a Python script that reads the configurations and updates NetBox.

AutomateNetBox/scripts/update_netbox.py

import pynetbox
import sys
import os

NETBOX_URL = ‘http://your-netbox-url’
NETBOX_TOKEN = ‘your-netbox-api-token’

def parse_config(config_file):
interfaces = []
with open(config_file, ‘r’) as file:
for line in file:
if line.startswith(‘interface’):
interface = line.split()[1]
interfaces.append(interface)
elif line.strip().startswith(‘ip address’):
ip_address = line.strip().split()[2]
interfaces[-1] = (interfaces[-1], ip_address)
return interfaces

def update_netbox(device_name, interfaces):
nb = pynetbox.api(NETBOX_URL, token=NETBOX_TOKEN)
device = nb.dcim.devices.get(name=device_name)

if not device:
print(f”Device {device_name} not found in NetBox”)
return

for interface_name, ip_address in interfaces:
interface = nb.dcim.interfaces.get(device_id=device.id, name=interface_name)

if not interface:
print(f”Interface {interface_name} not found in NetBox for device {device_name}”)
continue

ip_check = nb.ipam.ip_addresses.filter(address=ip_address)
if not ip_check:
nb.ipam.ip_addresses.create({
‘address’: ip_address,
‘assigned_object_id’: interface.id,
‘assigned_object_type’: ‘dcim.interface’,
})

if __name__ == “__main__”:
config_dir = ‘/tmp’
for config_file in os.listdir(config_dir):
if config_file.endswith(‘_config.txt’):
device_name = config_file.split(‘_’)[0]
interfaces = parse_config(os.path.join(config_dir, config_file))
update_netbox(device_name, interfaces)

Step 6: Create Ansible Playbook to Run Python Script

Create an Ansible playbook to run the Python script after fetching the configurations.

AutomateNetBox/update_netbox.yml


– name: Update NetBox with IOS Configurations
hosts: localhost
gather_facts: no
tasks:
– name: Run Python script to update NetBox
command: python3 /AutomateNetBox/scripts/update_netbox.py

Step 7: Set Up Cron Job for Periodic Updates

Set up a cron job to run the Ansible playbooks periodically.

  1. Open Crontab:

crontab -e

  1. Add the Cron Job:

*/30 * * * * /usr/bin/ansible-playbook -i /path/to/ansible/inventory /path/to/ansible/fetch_config.yml && /usr/bin/ansible-playbook -i /path/to/ansible/inventory /path/to/ansible/update_netbox.yml

Summary

By following these steps, you’ll have a system where Ansible periodically fetches the current configurations from your network device and updates NetBox with any changes. The cron job ensures that this process runs every 30 minutes, keeping your NetBox data in sync with the actual device configurations.

If you add all network devices to your Ansible host file – all devices will be reconciled with Netbox as long as they existed in Devices under Netbox.

Practical Example

I’ll guide you through an example of the process by creating a VLAN and SVI on a Cisco IOS-XE 9300 using a simple Netmiko script and demonstrate how NetBox is automatically updated with these changes. I’ll also show you what the updated NetBox entries would look like after the configurations are updated.

Step 1: Create VLAN and SVI on IOS-XE using Netmiko

First, create a Python script using Netmiko to configure VLAN 20 and SVI 192.168.1.1 on the IOS-XE 9300.

create_vlan_svi.py

from netmiko import ConnectHandler

Device details

ios_device = {
‘device_type’: ‘cisco_ios’,
‘host’: ‘172.16.20.1’,
‘username’: ‘your_username’,
‘password’: ‘your_password’,
‘secret’: ‘your_enable_password’, # Optional if needed
}

Connect to the device

net_connect = ConnectHandler(**ios_device)
net_connect.enable()

Configuration commands

config_commands = [
‘vlan 20’,
‘name Management_VLAN’,
‘interface Vlan20’,
‘ip address 192.168.1.1 255.255.255.0’,
]

Send configuration commands

output = net_connect.send_config_set(config_commands)
print(output)

Save configuration

net_connect.send_command(‘write memory’)

Disconnect from the device

net_connect.disconnect()

Run this script to configure VLAN 20 and SVI on the IOS-XE 9300.

python create_vlan_svi.py

Step 2: Reconciled NetBox with Device Configuration using the automated workflow

Assuming 30 minutes has passed and cron job has been executed.

Step 3: Updated NetBox Entries

Assuming the Cronjob to update NetBox works correctly, here’s what you can expect in the updated NetBox entries:

1. Device Details: The device should already be listed in NetBox if it was added previously.

2. Interfaces: The new VLAN interface (Vlan20) will be added with its IP address.

Example Updated NetBox Entries

Device: ios-xe-9300-1

Name: ios-xe-9300-1

• Device Type: Cisco IOS-XE 9300

• Management IP Address: 172.16.20.1

Interfaces:

• GigabitEthernet1:

• Description: Existing description

• IP Address: Existing IP address (if any)

• Vlan20:

• Description: Configured by Ansible (or any specific description)

• IP Address: 192.168.1.1/24

IP Addresses:

• 192.168.1.1/24:

• Assigned to: Interface Vlan20 on ios-xe-9300-1

NetBox Verification

To verify the updated entries in NetBox, you can use the NetBox web UI:

1. Navigate to Devices:

• Go to Devices and select ios-xe-9300-1.

• Verify that the interface Vlan20 has been added with the correct IP address.

2. Navigate to IP Addresses:

• Go to IPAM > IP Addresses.

• Search for 192.168.1.1.

• Verify that the IP address is assigned to Vlan20 on ios-xe-9300-1.

Conclusion

By following these steps, you’ve:

1. Configured VLAN and SVI: Used a Netmiko script to configure VLAN 20 and SVI 192.168.1.1 on the IOS-XE 9300.

2. Fetched Updated Configurations: Used Ansible to fetch the updated configurations

3. Updated NetBox: Used a Python script within an Ansible playbook to update NetBox with the new configurations.

4. Verified Changes: Verified that the new VLAN and SVI are correctly reflected in NetBox.

This ensures that your NetBox instance is always up-to-date with the latest configurations from your network devices. Making Netbox your source of truth for your network device configurations.

Leave a comment

Trending