Firewall Automation with NAPALM Scripts and Ansible

Managing network security's become seriously complex, so keeping those firewalls in check—efficiently, accurately, and fast—is more critical than ever. Tools like Ansible and NAPALM (Network Automation and Programmability Abstraction Layer with Multivendor support) let you automate tasks across your routers, switches, and firewalls like it's second nature, totally changing how efficient your network can be.
Before we go into the details of NAPALM, here's a TLDR on some important concepts.
A TL;DR to Network Automation
Trying to manually manage hundreds (or thousands!) of network devices (switches, routers, firewalls) is just asking for trouble. Automation tools like Ansible and NAPALM make network jobs simpler, ensuring consistency and lowering the risk of command-line slip-ups.
Read more: Why Network Automation is Critical in IT
Here are some of the benefits:
- Better efficiency: Automate those repetitive tasks, cutting down on manual effort and freeing up time.
- Fewer slip-ups: Scripts bring down the chance of human error during setup and upkeep.
- More consistent setups: Automation makes sure setups are consistent right across the board.
- Faster rollouts: Quickly push out setup tweaks and new services.
- More nimble: React fast to changing business demands and security dangers.
A TL;DR to Ansible
Ansible, a favorite among network engineers, automates complex tasks. This open-source solution configures network devices (switches, routers, and firewalls) using simple, yet powerful scripts. Tasks that once took hours can now wrap up in minutes.
Further Reading:
We've written a comprehensive guide on the Ansible automation platform. Also, check out our guide on setting up Ansible for network automation
What is NAPALM?
NAPALM is a Python library that makes network automation easier by providing a single API for handling devices, including firewalls, from different makers. This layer of abstraction does away with maker-specific setups, making it a tool for network engineers in shops using gear from multiple suppliers. Its abstraction makes it easier for beginners to get into NAPALM network automation.
What are the benefits of NAPALM?
Here's why NAPALM should be in your network automation toolkit:
- The library offers simple Python methods to interact with devices, making it accessible to those new to network automation.
- By abstracting vendor-specific nuances, engineers can write scripts that work across multiple devices without additional customization.
- NAPALM integrates well with tools like Ansible, SaltStack, and Puppet, allowing you to build comprehensive automation workflows.
Why NAPALM for Firewall Automation?
While NAPALM's general benefits are clear, NAPALM's architecture and features provide distinct advantages for managing firewalls.
Vendor-Agnostic Firewall Management
Firewalls often have significant vendor-specific configurations and command structures. Palo Alto Networks, Cisco, Juniper, or other platforms, each requires a unique set of CLI commands or API calls for basic tasks. NAPALM addresses this challenge by abstracting away these vendor-specific details.
Using its driver-based design and plugins like napalm-panos
for Palo Alto Networks firewalls, NAPALM gives you one API to talk to different firewall platforms. You can write automation scripts using NAPALM that can be used on different makers' gear.
Easier Scripting with Python Modules
NAPALM uses Python's strengths by offering modules that just make sense for network automation tasks. Instead of fighting with complex, maker-specific scripting languages or CLIs, engineers can use Python and NAPALM's well-laid-out functions to build solid firewall automation scripts more efficiently.
Rich Functionality for Firewall Operations
NAPALM's modules handle core network operations:
Configuration Management
NAPALM provides functions to load, merge, replace, commit, compare, and rollback firewall configurations, enabling complete lifecycle management of firewall policies and settings through automation. NAPALM makes sure changes are all-or-nothing and that you can roll back if needed, which is key for keeping firewalls stable during automated setup changes.
State Retrieval
NAPALM's getters module
grabs structured data from firewalls, including interface status, IP setups, routing tables, and how things are running. It also pulls policy setups, session info, and security stats, giving you insights for keeping an eye on things and figuring out what's what.
Operational Tasks
NAPALM can also do operational tasks on firewalls, depending on the driver and plugins you have.
Strong Community Support and Documentation
NAPALM has a lively community of network automation fans and developers who pitch in to make it better, create drivers for new platforms, and help users out. NAPALM also has lots of good docs that you can use to learn the library, figure out its modules, and troubleshoot stuff.
Broad Support for Firewall Vendors
NAPALM and its community plugins generally work with most major vendors. Platforms supported natively and through plugins include:
- Arista EOS
- Cisco IOS, IOS-XR, NX-OS
- Juniper JunOS
- Palo Alto Networks (via napalm-panos plugin)
For the latest list of supported makers, network operating systems, and platforms, check the official NAPALM docs and community resources.
Network Automation Examples with Firewall Use Cases and NAPALM
Configuration Management
NAPALM makes firewall setup easier by providing a single API for talking to devices and automating routine tasks.
- Automate creating and rolling out new firewall rules across multiple devices, using YAML files to lay out firewall objects and policies, which are then turned into setups using
Jinja2
templates and put in place via Ansible playbooks. - Script changes to existing rules, like tweaking IPs, ports, or services, and automate getting rid of old or unneeded rules to keep your rule base lean.
- Enforce consistent setups across all firewalls to up security and compliance. NAPALM can load setups in bulk while ensuring changes are all-or-nothing through its
load_merge_candidate
orload_replace_candidate
methods.
Compliance and Auditing
NAPALM also handles compliance checking and auditing, making sure you're sticking to security policies and standards.
- Retrieve firewall configurations and verify compliance with industry standards like PCI DSS or HIPAA using tools like NAPALM compliance reporting. YAML-based validation files can check for specific requirements (e.g., OS versions or security policies) and generate JSON reports.
- Analyze rule sets to identify redundant or overly permissive rules. Integrate this into CI pipelines for automated validation.
- Compare running configurations against a "golden" configuration to detect unauthorized changes, ensuring that firewalls remain secure over time.
Security Incident Response
Automating incident response with NAPALM cuts down on response times when things hit the fan.
- Quickly deploy temporary rules to block malicious traffic or quarantine compromised systems during incidents. NAPALM scripts can integrate with SIEM platforms to automate updates based on threat intelligence feeds boosting protection.
- Pair NAPALM with orchestration tools (like Ansible Tower) to put in place zero-touch responses for dealing with threats in real time.
Backup and Restore
NAPALM has tools for automating backup and restoration.
- Set up regular backups of firewall setups to make sure you can recover. Keep these backups in inventory systems for tracking what's happened.
- Automate restoring by loading backup files into firewalls using NAPALM's
load_replace_candidate
method.
Reporting and Monitoring
NAPALM gives you better visibility into firewall operations through automated reporting.
- Make reports on device inventory, including model numbers, software versions, and interface statuses.
- Create summaries of active policies, including rule counts and policy effectiveness metrics.
- Keep an eye on resource utilization (e.g., CPU, memory) and session statistics for proactive troubleshooting.
Introduction to CloudMyLab
With CloudMyLab, you're in charge of your network gear. CloudMyLab is rock-solid when it comes to automated setups, fault management, and making sure things run smoothly. It lets you easily drop tools like Nornir, Python, and NAPALM into your day-to-day work.
CloudMyLab provides lab setups in the cloud for networking pros that can grow as you need them. The platform lets you pair Ansible's automation with hands-on network simulations, making it easier to learn and get things done.
Getting Started with NAPALM
This part of our guide walks you through setting things up, getting your Python environment ready, and taking the first steps in hooking up to a network device.
Python Installation
Before setting up NAPALM, Python needs to be on your system. NAPALM works with Python 3.7 and up.
- Windows: Download and install Python from the official website.
- Linux: Most distributions come with Python pre-installed. You can check if it's installed by running:
python3 --version
Installing pip
Pip is the package manager for Python, which you'll use to install NAPALM. t usually comes with Python. To see if pip is ready, run:
pip --version
If it’s not installed, you can install it using:
- Windows: Follow instructions on the pip installation page.
- Linux:
sudo apt-get install python3-pip # For Debian/Ubuntu
sudo yum install python3-pip # For CentOS/RHEL
Installing NAPALM via pip
Once you have Python and pip ready, setting up NAPALM is a piece of cake:
pip install napalm
This command sets up the core NAPALM library and all the drivers you need for different network devices.
For maker-specific drivers (like Fortinet, Palo Alto), you might need to do a bit more:
Fortinet:
pip install git+https://github.com/glennake/napalm-fortinet.git
Palo Alto:
pip install git+https://github.com/napalm-automation-community/napalm-panos.git
Connecting to Network Devices
Make sure the machine you're automating from can get to the firewall using protocols that work (like SSH, NETCONF). Open the ports you need (like port 22 for SSH) and have your credentials or API keys handy.
- Secure Shell (SSH) for secure communications to your switches.
- Simple Network Management Protocol (SNMP) to help in monitoring and managing your network devices.
- Vendor APIs to make setting things up and pulling data easier.
- Direct console access for managing devices locally.
- Network Configuration Protocol (NETCONF) to set up, tweak, and wipe out the setup of network devices.
Connecting to Firewalls with NAPALM
NAPALM uses drivers to interact with specific vendors’ devices. Here are some examples:
- ios for Cisco IOS devices.
- fortinet for FortiGate firewalls.
- panos for Palo Alto firewalls.
Here's how it looks:
from napalm import get_network_driver
# Specify the driver for your device (e.g., ios, junos)
driver = get_network_driver("fortinet")
device = driver(
hostname="192.168.1.1",
username="admin",
password="password",
optional_args={"port": 22} # Optional arguments like port numbers
)
# Open the connection to the device
device.open()
# Retrieve and print device facts (basic information)
facts = device.get_facts()
print(facts)
# Close the connection when done
device.close()
Core NAPALM Modules and Functions
Getters Module
Getters retrieve information from firewalls in a structured format.
Common Getters for Firewalls:
get_facts
: Retrieve basic device information (model, OS version, serial number).get_interfaces
: Fetch interface details.get_interfaces_ip
: Retrieve IP addresses assigned to interfaces.get_arp_table
: Fetch the ARP table.
Example: Retrieving Firewall Facts
facts = device.get_facts()
print(f"Model: {facts['model']}, OS Version: {facts['os_version']}")
Configuration Management Modules
NAPALM helps you manage setups so that changes are all-or-nothing and can be undone.
load_merge_candidate
Merge new configurations with the running configuration.
device.load_merge_candidate(filename="new_config.txt")
load_replace_candidate
Replace the entire running configuration with a new one.
device.load_replace_candidate(filename="full_config.txt")
compare_config
Preview changes before committing them.
print(device.compare_config())
commit_config
Apply changes to the firewall.
device.commit_config()
rollback_config
Revert to the previous configuration if needed.
device.rollback()
Example Workflow: Putting New Rules In Place
# Load new rules into candidate config
device.load_merge_candidate(filename="firewall_rules.txt")
# Compare changes before committing
print(device.compare_config())
# Commit changes if satisfied
device.commit_config()
Handling Vendor Variations with Conditional Logic
When writing NAPALM scripts, you might see that different makers need slightly different commands or setups. Here's how to handle it:
- Know what's different: Before scripting, figure out what's different between makers that might not work across the board.
- Use If-Then logic: You can use Python's if-then statements to run different bits of code depending on the maker. Here's how:
from napalm import get_network_driver
# Define device details
vendor = "ios" # This should be dynamically set based on your environment
hostname = "192.168.1.1"
username = "admin"
password = "password"
# Get the appropriate driver
driver = get_network_driver(vendor)
device = driver(hostname=hostname, username=username, password=password)
device.open()
# Conditional logic for vendor-specific commands
if vendor == "ios":
# Cisco IOS specific command
device.load_merge_candidate(config="interface GigabitEthernet0/1\ndescription Cisco Interface")
elif vendor == "junos":
# Juniper Junos specific command
device.load_merge_candidate(config="interfaces {\n ge-0/0/1 {\n description Juniper Interface;\n }\n}")
else:
print("Unsupported vendor")
device.commit_config()
device.close()
Importance of Testing Scripts in a Lab Environment with CloudMyLab
Before deploying automation scripts in a production environment, test them thoroughly in a lab setting. CloudMyLab has cloud lab solutions that you can tweak and that won't break the bank.
- Identify and resolve vendor-specific issues without impacting live networks. CloudMyLab provides hosted emulators like GNS3, EVE-NG, and CML 2.0, allowing for hardware-free network building and realistic network simulations.
- Ensure your scripts work as intended across different devices and configurations, verifying that commands execute correctly and configurations are applied as expected. CloudMyLab's Ansible stack (featuring RedHat AAP Server, GitLab CE Server, Rundeck Server, and a Windows Jump Server) enables efficient automation testing.
- Minimize the risk of unintended consequences when applying changes to production devices. CloudMyLab offers Bare Metal Hosted Services providing high-performance dedicated servers, ideal for running resource-intensive automation tests.
- Use the network lab environment for iterative testing and refinement of your scripts based on observed behavior and results. CloudMyLab’s Lab as a Service and Learning Labs are designed to improve your team’s ability to test, migrate, and deploy newer solutions in a flexible and risk-free environment.
- Ensure your team can test in a vendor-agnostic environment, utilizing CloudMyLab's Proof of Concept labs backed by professional services.
Integration with Automation Platforms: NAPALM and Ansible
Integrating NAPALM scripts with higher-level automation platforms such as Ansible, StackStorm, or CI/CD pipelines enables network engineers to orchestrate complex automation workflows involving multiple firewalls and network devices.
Ansible Integration
NAPALM integrates with Ansible, an automation tool that uses playbooks to define automation tasks. The napalm-ansible
module allows you to leverage NAPALM's unified API within Ansible playbooks. This integration enables:
- Multi-Device Management: Automate configuration changes across devices from different vendors using a single playbook.
- Idempotency: Ensure tasks are only applied when necessary, which reduces the risk of unintended changes.
A playbook example:
name: Configure firewall rules
hosts: firewalls
tasks:
name: Load candidate configuration
napalm_load_merge_candidate:
src: /path/to/config_file.txt
provider:
hostname: ""
username: "admin"
password: "password"
name: Commit changes
napalm_commit_config:
provider:
hostname: ""
username: "admin"
password: "password"
Creating Ansible playbooks is crucial for network automation. Through YAML syntax, you define tasks and workflows.
Read more: How to write your first Ansible playbook
StackStorm Integration
StackStorm is an event-driven automation platform that can use NAPALM for network device management through its integration pack. This allows for:
- Trigger NAPALM scripts based on specific events in the network, such as alerts or changes in device state.
- Create workflows involving multiple steps and conditions, enabling automation scenarios.
StackStorm can listen for events (e.g., a device going down) and execute predefined NAPALM actions to remediate the situation automatically.
CI/CD Pipelines
Integrating NAPALM into CI/CD pipelines allows teams to automate testing and deployment of network configurations as part of their software development lifecycle. You can:
- Validate configurations against a set of criteria before deployment, ensuring compliance and functionality.
- Automatically apply tested configurations to production devices without manual intervention.
In a CI/CD pipeline, you could have a stage where NAPALM scripts run to check the current configuration of devices, compare it against the desired state, and apply any necessary changes.
Orchestrating Complex Automation Workflows
By integrating NAPALM with these automation platforms, organizations can orchestrate complex workflows involving multiple firewalls and network devices, leading to:
- Managing configurations across diverse environments from a single platform, reducing complexity and improving efficiency.
- Scaling automation efforts across devices easily without needing to write custom scripts for each vendor.
- Improving team collaboration on automation tasks using shared playbooks or workflows, leading to better consistency and faster deployment times.
- Gaining insights into network configurations and states through automated reporting and monitoring integrated into these platforms.
Taking the Next Steps with Firewall Automation and NAPALM
NAPALM offers a solution to modernize and enhance your firewall operations through its vendor abstraction, Python-based scripting, and rich functionality.
Explore how CloudMyLab can help you:
- Access our extensive library of articles, tutorials, and guides on network automation, including in-depth resources on NAPALM and firewall technologies, to deepen your knowledge.
- Enroll in our specialized training programs and workshops designed to equip your team with the hands-on skills needed to master NAPALM scripting and firewall automation techniques, developing practical skills.
- Leverage our expert consulting services to design, deploy, and optimize your NAPALM-based firewall automation solutions, ensuring a smooth and successful transition, accelerating your implementation.
Visit CloudMyLab today to discover how we can empower your organization to achieve next-level network automation and firewall management.
FAQ
How do I integrate NAPALM with Ansible?
To integrate NAPALM with Ansible, you need to use the napalm-ansible modules. Here’s a brief overview of the steps involved:
Install napalm-ansible: You can install it via pip:
pip install napalm-ansible
Use NAPALM Modules: In your Ansible playbooks, you can utilize modules such as napalm_get_facts, napalm_install_config, and others to interact with network devices.
Example Playbook:
name: Configure network devices
hosts: all
connection: local
tasks:
name: Get facts from device
napalm_get_facts:
hostname: ""
username: "admin"
password: "password"
dev_os: "ios"
Connection Plugin: Starting from Ansible 2.8, you can also use the NAPALM connection plugin for persistent connections, but ensure that NAPALM is installed on your Ansible controller. Read more here as well.
Can NAPALM handle multiple network devices simultaneously?
Yes, NAPALM can handle multiple network devices simultaneously. When integrated with Ansible, you can define a group of devices in your inventory file and execute tasks across all of them in parallel, enabling efficient management of configurations and data retrieval.
Which Python version is recommended for running NAPALM scripts?
Use Python 3.7 or later for running NAPALM scripts for compatibility with the latest features and improvements in both Python and the NAPALM library. Read the NAPALM documentation here.
What is the role of CloudMyLab in network automation?
CloudMyLab provides a cloud-based lab environment that enables you to test and validate network automation scripts without physical hardware. It offers customizable labs that support various networking technologies and tools, including NAPALM, so you can:
- Experiment with automation workflows safely.
- Validate configurations and scripts against real-world scenarios.
- Facilitate learning and development in a controlled environment without impacting live networks.
CloudMyLab enhances network automation practices while minimizing risks associated with deploying untested configurations in production environments.