
Image by: Brett Sayles
Did you know that according to industry studies, over 70% of network outages are caused by manual configuration errors rather than hardware failures? For network engineers and sysadmins, the “fat-finger” mistake isn’t just an embarrassment; it is a multi-million dollar risk. Imagine a scenario where a single misplaced subnet mask or an incorrectly applied ACL on a core switch brings down an entire data center. As networks grow in complexity, the traditional method of SSH-ing into individual devices to execute commands is no longer scalable or safe. This guide provides a comprehensive, step-by-step tutorial on how to leverage Ansible for automating enterprise network and firewall configurations. You will learn how to manage multi-vendor environments, specifically Cisco and Fortinet, to ensure consistency, security, and rapid recovery.
The shift toward network automation
The era of the “CLI warrior”—the engineer who spends eight hours a day manually typing commands into terminal windows—is rapidly coming to an end. Modern enterprise networks are too large and too dynamic for manual intervention. We are seeing a massive transition toward Network Infrastructure as Code (NIaC), where network changes are treated with the same rigor as software deployments.
Traditional management relies on imperative workflows: you tell the device how to do something (e.g., “conf t”, “interface Gi0/1”, “shutdown”). Ansible introduces a declarative approach, where you define the desired state of the network, and Ansible handles the execution. This distinction is critical for scalability. When you need to update an NTP server across 500 switches, a declarative approach ensures every device reaches that state without the engineer needing to monitor 500 individual SSH sessions.
By adopting Ansible, organizations can achieve several key objectives:
- Reproducibility: Deploying the same configuration template across multiple sites without variation.
- Speed: Reducing deployment windows from hours to minutes.
- Auditability: Keeping a version-controlled history of every change made to the network fabric.
As you move toward more advanced automation, it is helpful to understand how these changes impact your overall infrastructure management strategy. The goal is not just to type faster, but to build a resilient, self-healing network architecture.
Setting up your Ansible environment for network automation
Before you can push your first configuration to a production router, you need a robust control node environment. Ansible is agentless, which is its greatest advantage in networking; it doesn’t require you to install software on the switches themselves. Instead, it uses standard protocols like SSH, NETCONF, or APIs to communicate.
Prerequisites and core components
To begin, you need a Linux-based control node (Ubuntu or RHEL are preferred) with Python installed. The core components you will interact with include:
- Inventory File: A file (usually YAML) that lists your network devices, grouped by function (e.g., [core_switches], [edge_firewalls]).
- Playbooks: YAML files that define the tasks to be performed.
- Modules: The “workers” of Ansible. For Cisco, you will use
cisco.ios.ios_config; for Fortinet, you might usefortinet.fortimanager.fortimanager_config. - Variables: Storing sensitive data like passwords and IP addresses in
group_varsorhost_varsto keep playbooks clean and secure.
Managing credentials securely
Never hardcode passwords in your playbooks. This is the most common mistake in beginner automation. Use Ansible Vault to encrypt your sensitive data. By encrypting your `group_vars/all.yml` file, you can safely commit your configuration logic to a Git repository without exposing your administrative credentials.
A well-structured directory layout is essential for enterprise-grade automation. Consider this structure for your projects:
project/ ├── inventory/ │ ├── production.ini │ └── staging.ini ├── group_vars/ │ └── all.yml (Encrypted with Ansible Vault) ├── roles/ │ ├── cisco_ios/ │ └── fortinet_fw/ ├── site.yml └── ansible.cfg
Automating Cisco IOS configurations with Ansible
Cisco devices are the backbone of many enterprises, and automating them requires a specific approach to handle the hierarchical nature of IOS configuration. When writing playbooks for Cisco, we rely on the `cisco.ios` collection.
Writing a basic configuration playbook
The goal is to move away from sending raw strings and instead use templates. Using Jinja2 templates allows you to create a “golden configuration” that can be adapted for different sites by simply changing a few variables. For example, if you need to update the VLAN database across multiple access switches, your playbook would look like this:
- name: Update VLANs on Cisco switches
hosts: access_switches
gather_facts: no
tasks:
- name: Apply VLAN configuration
cisco.ios.ios_vlans:
config:
- vlan_id: 10
name: Users
- vlan_id: 20
name: IoT_Devices
state: merged
The importance of “State”
The `state` parameter in Ansible Cisco modules is what makes the automation powerful. You can choose from several modes:
- Merged: Adds the configuration to the existing running-config.
- Replaced: Replaces specific parts of the configuration (useful for interface settings).
- Overridden: Wipes the current configuration for that specific feature and replaces it entirely with what is in your playbook.
- Deleted: Removes the configuration specified.
Using overridden is the ultimate way to enforce compliance, but it is also the most dangerous. It is highly recommended to test these playbooks in a virtual environment like Cisco Modeling Labs (CML) before applying them to production hardware.
Securing the perimeter: Fortinet automation
Firewall automation is inherently higher risk than switch automation. A mistake in a routing protocol on a switch might cause a local outage, but a mistake in a Fortinet firewall rule can expose your entire internal network to the public internet. To automate Fortinet devices, you should ideally use the FortiManager API or the `fortinet.fortimanager` Ansible collection.
Managing Firewall Policies
Automating firewall policies allows you to ensure that security rules are consistent across a global fleet of FortiGate appliances. Instead of manually clicking through the FortiOS GUI, you can define your security policy in a YAML file and push it via Ansible.
Below is a comparison of how different automation approaches handle firewall management:
| Feature | Manual (CLI/GUI) | Ansible (Direct to FortiGate) | Ansible (via FortiManager) |
|---|---|---|---|
| Speed | Slow & Error-prone | Fast | Very Fast (Centralized) |
| Error Risk | High (Human error) | Medium (Script error) | Low (Orchestrated) |
| Audit Trail | System Logs only | Git History | Full Version Control |
| Complexity | Low | Medium | High (Requires FortiManager) |
Enforcing Security Compliance
Automation allows for “Continuous Compliance.” You can write a playbook that checks for specific security requirements, such as ensuring that “Telnet” is disabled and “SSH” is enabled on all Fortinet interfaces. If the check fails, Ansible can automatically trigger a remediation task to fix the setting. This proactive approach turns your security posture from reactive to proactive.
Automating configuration backups and compliance
If a network event occurs, your first question will be: “What changed?” If you have automated your configuration backups, you have a time machine. A recurring Ansible job can connect to every device in your inventory, pull the running-configuration, and store it in a centralized version control system like Git.
Building a backup workflow
An enterprise-grade backup workflow follows these steps:
- Discovery: Identify all active devices via the inventory file.
- Retrieval: Use the `ios_command` or `fortios_command` modules to pull the configuration.
- Sanitization: Remove device-specific secrets or timestamps that cause unnecessary “diffs” in Git.
- Storage: Commit the configuration to a Git repository.
“Automation is not just about making changes; it is about ensuring that every change is documented, reversible, and verifiable. Without a backup-and-verify loop, you aren’t automating; you are just speeding up your mistakes.”
By implementing this, you can use tools like Ansible Lint and Batfish to validate your configurations before they ever hit a physical device. Batfish, specifically, can analyze your configuration files to predict how they will affect routing and security, providing a layer of mathematical certainty to your network changes. This is a cornerstone of modern network security practices.
Mitigating manual deployment errors through CI/CD
To reach the highest level of maturity, network engineers should adopt Continuous Integration and Continuous Deployment (CI/CD). In a CI/CD pipeline, your network configuration is treated exactly like application code.
The Network CI/CD Pipeline
A typical pipeline for a network engineer looks like this:
- Commit: An engineer modifies a YAML file representing a new VLAN and pushes it to Git.
- Linting: An automated runner (like GitLab CI or GitHub Actions) runs
ansible-lintto check for syntax errors. - Simulation: The playbook is run against a virtual lab (CML, EVE-NG, or GNS3) to ensure the routing table behaves as expected.
- Testing: Automated tests (using
pyATSortestinfra) verify that the new configuration didn’t break connectivity to critical services. - Deployment: Once tests pass, the change is automatically pushed to the production environment during a scheduled maintenance window.
This “Infrastructure as Code” approach mitigates the most dangerous aspect of network management: the lack of a safety net. By moving the validation phase “left” (earlier in the process), you identify errors in a sandbox environment rather than on a live production backbone. This drastically reduces the Mean Time To Repair (MTTR) and increases the overall stability of the enterprise network.
Frequently asked questions
Do I need to know Python to use Ansible for networking?
While you do not need to be a software developer, a basic understanding of Python and YAML is highly beneficial. Most Ansible modules are written in Python, and configuration templates are written in Jinja2, which is a Python-based templating engine. You don’t need to write complex scripts, but knowing the fundamentals will help you troubleshoot.
Is Ansible better than Netmiko for network automation?
It isn’t necessarily better; they serve different purposes. Netmiko is a library used for sending SSH commands, while Ansible is an orchestration tool that uses modules (which often use Netmiko under the hood) to manage state. Netmiko is great for simple scripts, while Ansible is better for managing large-scale, complex infrastructures with repeatable tasks.
Can Ansible manage multi-vendor environments?
Yes, this is one of Ansible’s greatest strengths. You can use a single playbook to push configuration changes to a mix of Cisco, Fortinet, Juniper, and Arista devices by leveraging the specific modules designed for each vendor. You simply group your devices in the inventory file by vendor type.
How do I handle sensitive data like passwords in Ansible?
You should always use Ansible Vault. It allows you to encrypt specific variables or entire files, ensuring that secrets are never stored in plain text within your version control system. This is a fundamental requirement for security compliance in enterprise environments.
Conclusion
Transitioning from manual CLI management to automated workflows via Ansible is a journey, not an overnight event. By implementing structured playbooks for Cisco and Fortinet devices, you move from being a reactive “troubleshooter” to a proactive “network architect.” We have covered the essential steps: setting up a robust control node, utilizing Jinja2 templates for multi-vendor compatibility, securing credentials with Ansible Vault, and implementing a CI/CD pipeline to catch errors before they impact production.
As you begin your automation journey, start small. Begin with low-risk tasks like routine configuration backups or verifying NTP settings before moving on to high-stakes tasks like firewall policy changes. The goal is to build confidence in your automated processes. If you are ready to modernize your network operations, start by automating your backups today. Your future, rested self will thank you.
