Ansible for Network Automation
Complete the full lesson to earn 25 points
Work through each section, then tap “Mark as Complete” on the last one.
Module: Network Operations and Monitoring
Lesson: Ansible for Network Automation
Introduction: The Shift to Programmable Networks
In the traditional landscape of network engineering, managing infrastructure was a labor-intensive, manual process. Engineers spent countless hours logging into individual switches, routers, and firewalls via Command Line Interfaces (CLI), executing repetitive commands, and documenting changes in spreadsheets. This manual approach is not only slow but also highly prone to human error. A single typo in a VLAN configuration or an access control list (ACL) can lead to widespread network outages, resulting in significant downtime for business operations.
Network automation represents a fundamental shift in how we build and maintain connectivity. Instead of treating network devices as "black boxes" that require manual intervention, we treat the network as code. Ansible has emerged as the industry standard for this transition because it is agentless, human-readable, and designed for simplicity. By using Ansible, you can define your network state in simple text files and push those configurations across your entire infrastructure simultaneously, ensuring consistency and reliability.
Understanding Ansible for network automation is no longer an optional skill for network engineers; it is a necessity. As networks grow in complexity—incorporating cloud gateways, software-defined perimeters, and massive data center fabrics—manual configuration cannot keep pace. This lesson will guide you through the core concepts of Ansible, how it interacts with network hardware, and the best practices for building a sustainable automation pipeline.
The Core Architecture of Ansible
At its heart, Ansible is an automation engine that uses a "push" model. Unlike other configuration management tools that require you to install a software agent on every device you manage, Ansible connects to your network devices using standard protocols like SSH or NETCONF. This is a massive advantage in the networking world, where proprietary operating systems often prevent the installation of third-party software.
How Ansible Communicates with Devices
Ansible uses "Modules" to perform tasks. When you want to configure a Cisco IOS switch, you use a specific module designed for that platform. The module translates your high-level instructions (e.g., "Set the description of interface GigabitEthernet0/1 to 'Core-Uplink'") into the specific commands required by the device's operating system.
The communication flow follows this pattern:
- Control Node: The machine where Ansible is installed. This is usually a Linux workstation or a dedicated automation server.
- Inventory: A file that lists the IP addresses, hostnames, and credentials of your network devices.
- Playbooks: YAML-formatted files where you define the tasks you want to execute.
- Modules: The small programs Ansible sends to the device to execute the task.
Callout: Agent vs. Agentless Most automation tools fall into two categories: agent-based or agentless. Agent-based tools require software to be installed directly on the managed device. In networking, this is rarely possible because hardware vendors provide locked-down operating systems. Ansible is agentless, meaning it communicates via existing management protocols like SSH, making it compatible with almost any device that supports a CLI or an API.
Setting Up Your Environment
Before you can automate, you need to prepare your control node. While you can run Ansible on any machine with Python, a Linux environment (like Ubuntu or CentOS) is the industry standard.
Step 1: Installing Ansible
You can install Ansible using the Python package manager, pip. This ensures you have the latest version of the core engine and the necessary libraries for network automation.
# Update your system package list
sudo apt update
# Install python3 and pip
sudo apt install python3-pip -y
# Install Ansible
pip3 install ansible
Step 2: Configuring the Inventory
The inventory file is the map of your network. You organize devices into groups to make them easier to target. For example, you might create groups for core_switches, access_switches, and firewalls.
Example hosts.ini file:
[core_switches]
core-01 ansible_host=192.168.1.1
core-02 ansible_host=192.168.1.2
[access_switches]
acc-01 ansible_host=192.168.2.1
acc-02 ansible_host=192.168.2.2
[all:vars]
ansible_user=admin
ansible_password=secret_password
ansible_network_os=cisco.ios.ios
Note: Storing passwords in plain text within an inventory file is a major security risk. In production environments, always use Ansible Vault to encrypt sensitive information or integrate with a secret management system like HashiCorp Vault.
Understanding Playbooks and YAML
Ansible Playbooks are written in YAML (YAML Ain't Markup Language). YAML is designed to be human-readable, which is vital for network engineers who need to audit configuration changes quickly. A playbook consists of one or more "plays," which map a group of hosts to a set of tasks.
Anatomy of a Simple Playbook
Let’s look at a playbook that performs a simple task: checking the version of the operating system on all core switches.
---
- name: Network Status Check
hosts: core_switches
gather_facts: false
tasks:
- name: Get device facts
cisco.ios.ios_facts:
gather_subset: hardware
In this example:
hosts: Refers to the group defined in your inventory file.gather_facts: Set tofalsebecause we are performing a specific network task, and we don't need the default system facts that Ansible usually gathers from Linux hosts.tasks: A list of actions to perform sequentially.cisco.ios.ios_facts: The specific module that talks to Cisco IOS devices to retrieve hardware information.
The Power of Idempotency
One of the most important concepts in Ansible—and automation in general—is idempotency. An idempotent operation is one that can be applied multiple times without changing the result beyond the initial application.
If you write a playbook to ensure that a VLAN exists, Ansible will check if the VLAN is already there. If it is, Ansible does nothing. If it is missing, Ansible creates it. This prevents the "configuration drift" that occurs when scripts are run repeatedly, potentially causing duplicate entries or errors.
Practical Example: Interface Configuration
Instead of using a script that blindly sends "interface GigabitEthernet0/1" followed by "description Uplink," you use an Ansible module that defines the state.
- name: Configure interface description
cisco.ios.ios_l3_interfaces:
config:
- name: GigabitEthernet0/1
description: "Uplink to Core"
state: merged
If you run this playbook ten times, the description remains "Uplink to Core." You don't have to worry about adding the same line ten times into the running configuration.
Handling Network-Specific Modules
Network vendors have their own collections within the Ansible ecosystem. Instead of relying on generic SSH commands, you should use platform-specific collections. These collections are maintained by the vendors (Cisco, Juniper, Arista, etc.) and provide robust support for their specific command structures.
Common Platform Collections
| Vendor | Collection Name | Use Case |
|---|---|---|
| Cisco | cisco.ios |
IOS, IOS-XE |
| Juniper | junipernetworks.junos |
Junos OS |
| Arista | arista.eos |
Arista EOS |
| Palo Alto | paloaltonetworks.panos |
Firewalls |
To install a collection, you use the ansible-galaxy command:
ansible-galaxy collection install cisco.ios
This command downloads the latest modules, documentation, and plugins for Cisco IOS, allowing you to use them immediately in your playbooks.
Advanced Automation: Variables and Templates
As your network grows, you cannot keep all your configurations in hard-coded playbooks. You need to separate the logic (the playbook) from the data (the device configuration). This is where Jinja2 templates and variable files come in.
Using Jinja2 Templates
Imagine you need to deploy a standard configuration for 50 access switches. You don't want 50 different playbooks. Instead, you create a template file (interface.j2) and use variables to fill in the blanks.
Template (interface.j2):
interface {{ interface_name }}
description {{ interface_desc }}
switchport mode access
switchport access vlan {{ vlan_id }}
Playbook implementation:
- name: Configure interfaces from template
cisco.ios.ios_config:
src: interface.j2
vars:
interface_name: "GigabitEthernet0/1"
interface_desc: "Office_Printer"
vlan_id: 10
This approach allows you to scale your automation significantly. You can keep all your device-specific data in a YAML file and simply loop through that file to configure hundreds of ports in seconds.
Best Practices for Network Automation
Automation is a journey, not a destination. To ensure your automation efforts are successful and don't lead to accidental network-wide outages, follow these industry-standard best practices.
1. Always Use Version Control (Git)
Treat your playbooks, inventory files, and templates like production code. Store them in a Git repository. This allows you to track who changed what, when they changed it, and provides an easy way to "roll back" to a previous working configuration if an update causes an issue.
2. Implement a Lab Environment
Never test a new playbook directly on your production network. Build a small virtual lab using tools like GNS3, EVE-NG, or Cisco Modeling Labs (CML). Validate that your playbook performs as expected in a simulated environment before moving to the live network.
3. Start Small (The "Read-Only" Phase)
When you first start with Ansible, begin by writing playbooks that only gather information (like ios_facts or ios_command). This builds confidence in your connection settings and inventory without the risk of changing any configurations. Once you are comfortable gathering data, move on to simple, non-disruptive changes.
4. Use Check Mode
Ansible has a "check mode" (the --check flag) that simulates the playbook execution without actually applying changes to the device. It will show you exactly what commands would be sent.
ansible-playbook configure_vlan.yml --check --diff
The --diff flag is particularly useful because it displays the exact lines that would be added or removed from the configuration, allowing you to perform a manual review before committing to the change.
Warning: The "Automation Trap" A common mistake is trying to automate everything at once. This leads to complex, unmanageable code. Focus on high-value, repetitive tasks first—such as VLAN creation, description updates, or interface state changes—rather than trying to automate complex routing protocols on your first day.
Troubleshooting Common Pitfalls
Even with the best planning, things will go wrong. Here are the most common issues you will encounter when starting with Ansible for networking.
Connection Timeouts
Network devices are often slower to respond than Linux servers. If your Ansible playbooks are failing with timeout errors, check your ansible.cfg file. You may need to increase the timeout limit.
[defaults]
timeout = 30
Improper Privilege Escalation
Many network devices require you to log in as a standard user and then "enable" to enter configuration mode. Ensure your Ansible variables are set correctly to handle this escalation.
vars:
ansible_become: yes
ansible_become_method: enable
Syntax Errors in YAML
YAML is extremely strict about indentation. Using a tab character instead of spaces, or having an uneven number of spaces, will cause the playbook to fail. Use a text editor like VS Code with a YAML extension that highlights indentation levels.
Comparison: Manual vs. Automated Configuration
| Feature | Manual (CLI) | Automated (Ansible) |
|---|---|---|
| Speed | Slow (device-by-device) | Instant (parallel execution) |
| Accuracy | High risk of human error | Consistent and repeatable |
| Audit Trail | Requires manual logging | Version-controlled (Git history) |
| Scalability | Does not scale well | Highly scalable |
| Documentation | Manual spreadsheets | Code is the documentation |
Integrating Ansible into the CI/CD Pipeline
For advanced organizations, Ansible is just one piece of the puzzle. You can integrate it into a Continuous Integration/Continuous Deployment (CI/CD) pipeline using tools like Jenkins or GitLab CI.
In this workflow, a network engineer pushes a change to a Git repository. This triggers a pipeline that:
- Runs a linter to check for syntax errors.
- Deploys the configuration to a virtual lab environment.
- Runs automated tests to ensure connectivity (e.g., pinging a gateway).
- Only if all tests pass, the pipeline prompts the engineer to merge the code into the production branch.
This approach effectively turns your network into a software product, where quality assurance is handled by automated testing rather than manual troubleshooting.
Key Takeaways
- Agentless Architecture: Ansible's ability to manage devices without installing local software makes it uniquely suited for the restrictive environments found in networking hardware.
- Idempotency is Essential: Always design your tasks to define a "desired state" rather than a series of commands. This prevents errors when the same configuration is applied multiple times.
- Inventory Management: Organize your network logically using groups, but remember to keep sensitive credentials secure by using Ansible Vault or external secret managers.
- Use Version Control: Treat your network automation code exactly like application code. Git is your best friend for tracking changes, collaborating with teammates, and managing rollbacks.
- Simulate Before You Act: Always use the
--checkand--diffflags to preview changes before pushing them to live production equipment. - Start with Read-Only Tasks: Build confidence by gathering information before you start making changes. This ensures your connectivity, credentials, and inventory are correctly configured.
- The Infrastructure as Code Philosophy: Shift your mindset from "configuring individual boxes" to "managing network infrastructure as a consistent, versioned, and testable system."
By following these principles, you move away from the reactive "firefighting" mode of network administration and into a proactive, scalable, and highly reliable operational model. Start small, test thoroughly, and gradually expand your automation footprint across your entire network.
Enjoying the courses?
Everything stays free. Pro shows fewer ads, doubles your daily points limit so you progress twice as fast, and lets you read each lesson on one page.
- ✓ Fewer advertisements
- ✓ 2× daily points limit
- ✓ Distraction-free lessons