Staying ahead in the field of network management requires a combination of innovative tools. Enter Nornir, a framework that has been causing a stir in the network automation industry. Nornir Inventory is a solid network management solution created to optimize network operations, increase efficiency, and increase productivity. In this article, we’ll dive into Nornir Inventory’s complexities and look at its setup, structure, choices for modification, and real-world applications.
An Overview of Nornir Inventory
Nornir is a dynamic open-source Python automation framework created primarily for network orchestration and automation. It gives network administrators and engineers a flexible toolkit for managing configurations, automating routine network activities, and improving network infrastructure.
Nornir Inventory is an inventory management system created to collect, organize, and access data on network assets and devices. It helps network managers to preserve important information about equipment, including routers, switches, firewalls, servers, and more. The information can include IP addresses, hostnames, kinds, device access credentials, and any additional metadata required for network management.
With Nornir Inventory, network administrators can do the following:
- Automate routine tasks, such as backups, device provisioning, and configuration changes.
- Ensure configurations are standardized and comply with policies.
- Monitor network changes and respond proactively to issues.
- Enhance security by identifying and addressing vulnerabilities.
- Streamline troubleshooting with accurate device and configuration information.
Why Inventory Matters in Network Automation
The importance of inventory in network automation cannot be overemphasized. Here are some reasons why.
Asset visibility: Inventory offers complete visibility into your network infrastructure. It provides a detailed list of all devices, their locations, configurations, and dependencies. This visibility is essential for accurate decision-making and troubleshooting.
Efficient task execution: Automation relies on precise knowledge of network assets to perform tasks. Inventory ensures that automation scripts can target the right devices, apply configurations, and execute tasks efficiently.
Risk mitigation: Knowing your network’s inventory helps you identify vulnerabilities, outdated devices, and configurations that pose security risks. You can then use automation to remediate these issues promptly.
Consistency: Inventory ensures consistency in network operations. Automation scripts can be applied uniformly across devices to reduce the risk of human errors and make configurations consistent and compliant.
Efficiency and time savings: Automation driven by accurate inventory data can significantly reduce manual tasks, saving time and resources.
Adaptability: Modern networks are dynamic, with devices constantly being added or replaced. Inventory tools can automatically discover and update asset information, keeping your inventory current.
A Practical Guide for Using Nornir Inventory
How to Set it Up
Before you start, make sure you have Python installed on your system as both Nornir and Nornir Inventory are Python-based tools. Once that is done, install Nornir using this command:
pip install nornir
You should get an output like this:
Now that Nornir has been initialized, we’ll use the SimpleInventory
plugin. This plugin makes it possible to pass in inventory data from YAML files. Create a Nornir-project
directory that will contain the files needed for Nornir inventory operations.
Understand the Structure
The Nornir Inventory structure consists of three main components:
- Hosts: individual network devices.
- Groups: collections of hosts.
- Defaults: attributes that are applied to all hosts, regardless of their group assignment.
To access information about the hosts, groups, and defaults, you will have to create a file for each of them.
- Create an
inventory
folder in theNornir-project
directory that you created earlier. - Create a
hosts.yaml
file in that directory. You can use any text editor of your choice to write the content of this file. It will contain information about your network devices, such as hostname, IP address, platform, operating system, and other relevant attributes as you deem fit. Here is an example you can use:
---
R1:
hostname: 192.168.1.1
port: 22
username: netbox
password: netbox123
platform: ios
groups:
- cisco
R2:
hostname: 192.168.1.2
port: 22
username: netbox
password: netbox123
platform: junos
groups:
- juniper
Once you’ve created the hosts.yaml
file, create the groups.yaml
file. The content of the file will include the following:
---
R1: {}
R2: {}
Create the defaults.yaml
file, which will contain the following:
---
username: netbox
password: netbox123
Then create the config.yaml
file.
---
inventory:
plugin: nornir.plugins.inventory.simple.SimpleInventory
options:
host_file: 'inventory/hosts.yaml'
group_file: 'inventory/groups.yaml'
defaults_file: 'inventory/defaults.yaml'
Next, create a nornir-project.py
file in the main directory.
# Import dependencies
from nornir import InitNornir
nr = InitNornir(config_file="config.yaml")
def my_task(task):
print(f"Running my_task on {task.host.name}")
result = nr.run(task=my_task)
Use the following command to run the program:
python nornir-project.py
The output should look like this:
For each host (R1 and R2) defined in the inventory, the script executes the my_task
function. It outputs a message to each host indicating that the task is being executed.
How to Customize and Use Nornir Inventory
After you’ve initialized Nornir Inventory, you can customize it to suit your needs. For example, you can add or remove hosts, groups, and defaults.
You can use Nornir Inventory to filter devices, run tasks, and automate config changes. For instance, here’s how to filter devices based on their platform:
from nornir import InitNornir
nr = InitNornir(config_file="config.yaml")
# Define a function to filter devices based on their platform
def filter_platform(task):
# Specify the platform you want to filter by (e.g., "ios", "junos", etc.)
desired_platform = "ios"
return task.host.platform == desired_platform
# Filter devices based on platform
filtered_hosts = nr.filter(filter_func=filter_platform)
# Define a task to run on the filtered devices
def my_task(task):
print(f"Running my_task on {task.host.name} with platform {task.host.platform}")
# Run the task on the filtered devices
result = filtered_hosts.run(task=my_task)
This code will run the my_task
function only on the hosts that have the specified platform (e.g., ios
). You can adjust the desired_platform
variable to filter hosts based on different platforms. The output should look like this:
Here is another example of how Nornir Inventory can be used to automate configuration changes:
from nornir import InitNornir
from nornir.plugins.tasks.networking import napalm_configure
from nornir.plugins.functions.text import print_result
# Initialize Nornir and load the configuration from "config.yaml"
nr = InitNornir(config_file="config.yaml")
# Define a function to filter devices based on their platform
def filter_platform(task):
desired_platforms = ["ios", "junos"] # Platforms you want to target
return task.host.platform in desired_platforms
# Filter devices based on platform
filtered_hosts = nr.filter(filter_func=filter_platform)
# Define a configuration task using Napalm for Cisco IOS devices
def configure_ios(task):
ios_config = [
"interface Loopback0",
"ip address 10.0.0.1 255.255.255.255",
"description Nornir Loopback",
]
task.run(
task=napalm_configure,
dry_run=True, # Set to False to actually make changes
replace=False, # Set to True to replace the entire configuration
configuration="\n".join(ios_config),
)
# Run the configuration task on filtered devices
config_result = filtered_hosts.run(task=configure_ios)
# Print the results
print_result(config_result)
This code shows how to use Nornir and Napalm to automate configuration updates on a subset of network devices based on their platform. Configure the configure_ios
job and filtering criteria to your individual use case and network environment. The output should look like this:
This output indicates that the configuration task for two devices, cisco-ios-01.cisco.com
and juniper-junos-01.juniper.com
, was successful. It displays the changes performed (if any) and any cautions for each device. It configures a loopback interface on the IOS device and updates the interface configuration on the Junos device in this example.
Consider Netbox as an Inventory
Netbox is a free and open-source online application for managing network infrastructure. It’s a one-stop shop for managing and documenting everything about your network, from devices and IP addresses to circuits and rack elevations. Netbox is well-known for its versatility and comprehensive feature set, which makes it an effective tool for network engineers.
Now, here’s where the magic happens: by integrating Netbox as an inventory source for Nornir, you gain access to a wealth of data and functionalities that can supercharge your automation workflows.
Centralized data: Netbox acts as a single source of truth for your network data. Nornir pulling information directly from Netbox helps you ensure that your automation tasks are based on the most up-to-date and accurate data.
Robust device information: Netbox stores detailed information about network devices, including their type, status, location, and connections. Nornir can harness this wealth of information to effectively execute tasks and automate configurations.
IP address management: Managing IP addresses becomes a breeze when you leverage Netbox’s IP address management capabilities. Nornir can seamlessly integrate with Netbox to allocate and manage IP addresses as needed during automation tasks.
Custom metadata: Netbox allows you to add custom metadata fields to your network objects. Whether it’s tagging devices for specific purposes or adding custom attributes, Nornir can use this metadata to drive automation decisions.
How to Use Netbox as an Inventory
You can use Netbox as a Nornir Inventory by using the nornir_netbox
plugin.
To do that, you will have to install the plugin using the following command:
pip install nornir_netbox
You then need to know the following from your NetBox instance:
- The NetBox URL
- A NetBox API token
Once you have these there are two options to configure Nornir to use NetBoxInvetory2
as the inventory source:
- Defining the inventory in Nornir’s configuration
config.yaml
file - Defining the inventory in Nornir’s
InitNornir
constructor
Nornir configuration file
The relevant section of the configuration is the inventory
section. In this section we will have to specify the plugin you want to use and the options to configure the plugin.
---
inventory:
plugin: NetBoxInventory2
options:
nb_url: https://netbox.local:8000
nb_token: "1234567890"
You can then use the configuration file to initialise Nornir:
from nornir import InitNornir
nr = InitNornir(config_file="config.yaml")
Nornir constructor
You can achieve the same goal by using the Nornir InitNornir
constructor. InitNornir
accepts an inventory argument, which allows us to specify the inventory plugin to use.
from nornir import InitNornir
nr = InitNornir(
inventory={
"plugin":"NetBoxInventory2",
"options": {
"nb_url": "https://netbox.local:8000",
"nb_token": "1234567890"
}
}
)
Both options will create a Nornir Inventory object that will be populated with data from Netbox. You can then use Nornir Inventory for your needs, be it to filter devices, run tasks, and automate configuration changes. You can more detailed set up information in the official docs for the nornir_netbox inventory plugin.
For more information, check out Nornir Python Tutorial: Get Started With Network Automation.
Conclusion
Nornir Inventory is a powerful tool that can help you automate your network tasks. As a network engineer or administrator, you can streamline your tasks, improve network security, and guarantee the effective operation of your infrastructure by making use of its flexibility, extensibility, and parallel execution capabilities. Nornir Inventory is a network management solution that is worth exploring whether your network is small or enterprise-level.
For more information on how to use Nornir Inventory, please visit the Nornir Documentation and NetBox Blog.
This post was written by James Ajayi. James is a Software Developer and Technical Writer. He is passionate about frontend development and enjoys creating educative and engaging content that simplifies technical concepts for readers to easily understand. With his content, he helps SaaS brands to increase brand awareness, product usage, and user retention.