Infrastructure as Code for Networks
Complete the full lesson to earn 25 points
Work through each section, then tap “Mark as Complete” on the last one.
✦ Skip the page breaks and see fewer ads — read each lesson on a single page with Pro
Infrastructure as Code for Networks: A Comprehensive Guide
Introduction: The Shift from Manual to Automated Networking
Historically, network engineering was a craft defined by manual intervention. When a new VLAN needed to be provisioned or an access control list (ACL) required an update, an engineer would log into a console, type commands directly into the Command Line Interface (CLI), and hope that the human typing the commands didn't make a syntax error. This "box-by-box" management style worked when networks were small and static. However, in today’s environment of cloud-integrated architectures, rapid scaling, and high-velocity application deployment, manual configuration has become a significant bottleneck and a major source of risk.
Infrastructure as Code (IaC) for networks is the practice of managing and provisioning network infrastructure through machine-readable definition files rather than manual hardware configuration. By treating network configurations as software code, we can apply the same rigorous practices used in software development—such as version control, automated testing, and continuous integration—to our network gear. This shift is not just about speed; it is about consistency, auditability, and the ability to reproduce network states reliably across development, staging, and production environments.
In this lesson, we will explore the foundational principles of IaC, the tools that enable it, and the practical workflows required to modernize your network operations. Whether you are managing campus switches, data center fabrics, or cloud virtual private clouds (VPCs), the transition to code-based management is the single most effective way to reduce downtime caused by configuration drift and human error.
The Core Principles of Network IaC
To understand Infrastructure as Code, we must first move away from the "imperative" mindset. Imperative management is what we do when we type interface GigabitEthernet0/1 followed by switchport mode access and switchport access vlan 10. You are telling the device exactly how to change its state. If you run that command again, the device might complain that the state is already set, or worse, execute it blindly.
IaC relies on a "declarative" mindset. In a declarative model, you define the desired end state of the network. You write a configuration file that says, "VLAN 10 should exist, and port 0/1 should be assigned to it." The automation tool then compares the current state of the device to your desired state and performs only the necessary actions to bridge that gap.
Key Pillars of IaC
- Version Control: Every configuration change is tracked in a system like Git. You can see who changed what, when they changed it, and why. If a change causes an outage, you can revert to the previous "known good" state with a single command.
- Idempotency: This is the property where an operation can be applied multiple times without changing the result beyond the initial application. If your configuration file declares that a specific NTP server must be configured, running the automation tool once or one hundred times results in the same, correct configuration.
- Modularity: Instead of writing one massive script to configure an entire data center, IaC encourages breaking configurations into reusable blocks or modules. You might have a module for "standard switch port configuration" that is used across thousands of ports.
- Automated Testing: Because your configurations are now files, you can run them through "linters" (to check for syntax errors) or "pre-flight" simulations (to see if the change will break existing connectivity) before the code ever touches a production device.
Callout: Imperative vs. Declarative Approaches The fundamental difference between traditional CLI management and IaC is the "how" versus the "what." In an imperative model, you act as the operator giving step-by-step instructions. In a declarative model, you act as the architect defining the final outcome. Declarative models are superior for large-scale operations because they eliminate the need to track the current state manually; the tool handles the reconciliation for you.
Essential Tools for the Network Automator
Building an IaC pipeline requires a specific stack of tools. You do not need to learn everything at once, but understanding the roles these tools play is vital for designing a maintainable system.
1. Version Control Systems (Git)
Git is the bedrock of IaC. It allows teams to collaborate on configuration files without overwriting each other’s work. By using branches, you can test a configuration change in a "feature branch" before merging it into the "main" branch, which acts as the source of truth for your production network.
2. Configuration Management and Automation Engines
These tools connect to your network devices and push the configurations defined in your code.
- Ansible: The most popular choice for network automation. It is agentless, meaning it uses standard protocols like SSH or NETCONF to communicate with devices. It is highly readable, using YAML files to describe tasks.
- Terraform: Specifically designed for infrastructure provisioning. It excels at managing resources across cloud providers and physical hardware, maintaining a "state file" that tracks exactly what resources exist in your environment.
- Nornir: A Python-based framework that is gaining traction for its high performance and flexibility. It is ideal for teams that prefer writing Python code over YAML configuration files.
3. Data Serialization Formats
You will spend most of your time writing in YAML (Yet Another Markup Language) or JSON (JavaScript Object Notation). YAML is the preferred format for human-readability. It uses indentation to define structure, making it much easier to read and maintain than complex XML-based configurations.
Practical Example: Implementing IaC with Ansible
Let’s look at a concrete example of how to automate a VLAN deployment using Ansible. In a manual workflow, you would SSH into each switch and type the VLAN commands. With Ansible, you define the VLAN in a YAML file and apply it to a group of devices.
Step 1: Define the Inventory
The inventory file tells Ansible which devices exist and how to categorize them.
# hosts.yml
all:
children:
switches:
hosts:
switch01:
ansible_host: 192.168.1.10
switch02:
ansible_host: 192.168.1.11
Step 2: Write the Playbook
The playbook is where the "what" is defined. We will use the ios_vlan module, which is built into Ansible for Cisco IOS devices.
# deploy_vlan.yml
---
- name: Configure VLANs on switches
hosts: switches
tasks:
- name: Ensure VLAN 10 exists
cisco.ios.ios_vlans:
config:
- vlan_id: 10
name: Engineering_Data
state: merged
Step 3: Execute the Playbook
You run this from your terminal using the ansible-playbook command.
ansible-playbook -i hosts.yml deploy_vlan.yml
When this runs, Ansible connects to the switches, checks if VLAN 10 exists, and if it does not, creates it. If it already exists, Ansible reports that the system is already in the desired state and does nothing. This is the power of idempotency.
Note: Always ensure that your credentials are stored securely. Never commit plaintext passwords to a Git repository. Use tools like
ansible-vaultor environment variables to inject credentials at runtime.
The Workflow: From Code to Production
Moving to IaC requires changing how you work. You can no longer just "fix things in production." You need a structured pipeline that ensures quality and prevents outages.
The Standard IaC Lifecycle
- Develop: The engineer writes the code in a local branch. They use tools like a text editor (VS Code is standard) with YAML linting plugins to ensure the syntax is correct.
- Verify: The engineer runs a "dry-run" or "check mode" of the automation tool. This shows the differences between the current state and the proposed state without actually making changes.
- Review (Pull Request): The engineer submits a "Pull Request" (PR) in Git. A teammate reviews the code to look for logic errors, configuration mistakes, or potential impact on the network.
- Merge: Once approved, the code is merged into the main branch.
- Deploy: A CI/CD tool (like GitLab CI or GitHub Actions) automatically triggers the execution of the playbook against the production network.
Why this Workflow Matters
By requiring a peer review (the Pull Request), you have effectively created a "four-eyes" check on every network change. This drastically reduces the likelihood of a typo taking down a link or a misconfigured VLAN causing a broadcast storm. The automated nature of the deployment also ensures that the configuration is applied exactly the same way every time, eliminating "configuration drift" where devices slowly become different from one another over time.
Advanced Concepts: Abstraction and Data Modeling
One of the most common pitfalls in network automation is treating the network as a collection of individual devices. As you scale, you should move toward Data-Driven Automation. Instead of hardcoding configurations into your playbooks, store your network data in a centralized database or a structured YAML file.
Data Modeling Example
Instead of having the VLAN name, ID, and switch ports scattered across different playbooks, create a "Source of Truth" file:
# network_data.yml
vlans:
- id: 10
name: "Engineering"
- id: 20
name: "HR"
switch_ports:
- switch: switch01
port: GigabitEthernet0/1
vlan: 10
- switch: switch02
port: GigabitEthernet0/5
vlan: 20
Your Ansible playbook then becomes a generic "template" that loops through this data. You no longer need to edit the playbook to add a new VLAN; you simply add a line to the network_data.yml file and push the update. This separates the logic (the playbook) from the data (the configuration parameters), which is a best practice in software engineering.
Callout: The Source of Truth In a mature network automation environment, the "Source of Truth" is not the network device itself. The device is merely an execution target. The true state of your network resides in your version control system or a dedicated IP Address Management (IPAM) or Network Source of Truth (NSoT) tool like NetBox. When you view the network this way, you realize that the running configuration is just a "compiled" version of your data.
Common Pitfalls and How to Avoid Them
Even with the best tools, network automation can fail if you don't account for the unique realities of network hardware.
1. The "Big Bang" Migration
Many engineers try to automate their entire network in one weekend. This is a recipe for disaster. Start small. Pick a low-risk, repetitive task—like updating NTP server addresses or standardizing SNMP strings—and automate that first. Build confidence in your pipeline before moving to core routing protocols or firewall policies.
2. Ignoring Error Handling
Network devices are notoriously fragile. A command that works on version 15.x of an OS might fail on version 16.x. Your automation scripts must include error handling. If a command fails, the script should stop immediately and report the error, rather than continuing to the next device and potentially causing a cascading failure.
3. Lack of Visibility
If you automate a change, you must be able to see the results. Integrate your automation pipeline with your monitoring tools. If you deploy a new configuration, your automation tool should verify that the change was successful (e.g., checking that the interface is "up/up" or that the neighbor adjacency is established) and report the status back to your chat or email system.
4. Over-complication
There is a tendency to use overly complex scripts that handle every possible edge case. Keep your code simple. If a task is so complex that it requires a 500-line Python script, break it down into smaller, modular components. If you can use a native module (like cisco.ios.ios_vlans) instead of writing raw CLI commands, always choose the native module.
Comparison Table: Automation Tools
| Feature | Ansible | Terraform | Python/Netmiko |
|---|---|---|---|
| Primary Use | Task Automation | Provisioning/State | Custom Scripting |
| Learning Curve | Low | Medium | High |
| State Management | No (uses plugins) | Yes | No |
| Agent Required | No | No | No |
| Best For | Configuration changes | Cloud/Multi-vendor | Complex logic |
Step-by-Step: Setting Up Your First Pipeline
If you are ready to begin, follow these steps to build your first professional-grade automation environment.
- Environment Setup: Create a dedicated management workstation or a virtual machine. Install Python 3, Ansible, and Git.
- Git Initialization: Create a new repository for your network configurations. Organize your folders by site or device type (e.g.,
/configs/data_center/,/configs/branch_office/). - Credential Management: Set up an SSH key pair for your network devices. Ensure your automation user has the appropriate privileges (privilege level 15 for Cisco, for example).
- Baseline Collection: Run a simple playbook to back up all current device configurations. This gives you a safety net. If your first automation attempt goes wrong, you have a copy of the original state.
- Small-Scale Test: Pick one non-critical VLAN and attempt to deploy it using a playbook.
- Review and Refine: Once successful, check the diffs in Git. Observe how the automation tool documented the change.
- CI/CD Integration: Once you are comfortable with manual execution, install a CI tool like GitLab Runner. Configure it to run your playbook whenever you push a change to the
mainbranch.
Best Practices for Long-Term Success
- Standardize Your Hardware: Automation is exponentially harder if you have 15 different vendors and 30 different OS versions. As you refresh hardware, push for consistency.
- Document Everything: Even if the code is self-documenting, include a
README.mdfile in your repository explaining how to run the playbooks and what the requirements are. - Treat "Read-Only" as Automation: Before you ever push a change, use automation to read data. Use it to generate audit reports or inventory lists. This builds trust in the tools without the risk of breaking anything.
- Engage the Community: The network automation community is vibrant. Use resources like the "Network to Code" Slack channel or the Ansible network modules documentation. You are rarely the first person to encounter a specific automation challenge.
- Continuous Learning: Automation is a journey. Keep up with new developments, such as the move toward gNMI (gRPC Network Management Interface) and model-driven telemetry, which are replacing older methods like SNMP and CLI scraping.
Troubleshooting Common Issues
"The script worked in the lab but failed in production."
This is usually due to environmental differences. Ensure your lab environment matches your production environment as closely as possible. Use network simulation tools like GNS3, EVE-NG, or Cisco CML to test your configurations before pushing them to physical hardware.
"The device timed out during the update."
Network devices often take longer to process commands than servers. Increase your timeout settings in your automation configuration (e.g., persistent_command_timeout in Ansible).
"The change was applied, but the device state is still wrong."
Verify that your automation tool is using the correct "state" argument. For example, in Ansible, state: merged adds configuration, while state: replaced will remove any configuration not defined in your file. Using the wrong state is the most common cause of unexpected configuration deletions.
Conclusion: The Future of Network Engineering
Infrastructure as Code is not a replacement for the network engineer; it is an evolution of the role. The days of spending hours on the CLI are fading. The future of the network profession lies in building systems that manage themselves, allowing engineers to focus on architecture, security, and performance optimization rather than the repetitive tasks of port configuration and VLAN management.
By adopting IaC, you gain the ability to scale your network without scaling your workload. You move from being a "box-pusher" to a "system architect." The learning curve can be steep, and the transition requires a shift in mindset, but the benefits—increased reliability, faster deployments, and a more resilient network—are well worth the effort.
Key Takeaways
- Declarative over Imperative: Always focus on the desired end state rather than the individual steps to get there.
- Version Control is Non-Negotiable: Use Git for everything. It is your safety net, your audit trail, and your history log.
- Start Small: Automate one repeatable, low-risk task to build confidence and prove the value of your pipeline to the wider team.
- Data-Driven Design: Separate your configuration data (the variables) from your logic (the playbooks) to ensure your automation remains maintainable as your network grows.
- Idempotency is Key: Ensure your automation can be run multiple times without causing side effects or duplicate entries.
- Safety First: Always use dry-runs, peer reviews, and backup procedures to mitigate the risk of automated changes.
- Continuous Improvement: Automation is never "finished." Treat your automation code like any other software project, with regular updates, refactoring, and testing.
As you embark on this path, remember that the goal is not to automate every single thing in your network. Some things are too complex or too rarely changed to justify the time investment. Focus your energy on the tasks that consume the most time and carry the highest risk of human error. By doing so, you will transform your network operations from a reactive, manual process into a proactive, high-velocity infrastructure engine.
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