Automation guides, explanations and reader checklists on whilenetworking.com

Ansible Playbook: Enforcing Idempotent Interface Configurations on Core Switches to Prevent Configuration Drift in Hybrid Clouds

In modern hybrid cloud infrastructures, network configuration drift is a silent but costly threat. When core switches in on-premises data centers diverge…

In modern hybrid cloud infrastructures, network configuration drift is a silent but costly threat. When core switches in on-premises data centers diverge from the intended state due to manual changes or legacy automation scripts, connectivity issues arise, security policies fail, and troubleshooting becomes a nightmare. The solution lies in implementing idempotent configurations using tools like Ansible, which ensures that applying a playbook repeatedly yields the exact same result without unintended side effects. This guide provides a concrete, safe approach to enforcing interface configurations on core switches, suitable for IT students and junior engineers looking to master network automation best practices.

Understanding Idempotency in Network Automation

Idempotency is the principle that performing an action multiple times has the same effect as performing it once. In networking, if you apply a configuration change intended to set an interface speed to 10Gbps, an idempotent script will not crash or reconfigure other settings if the interface is already at 10Gbps. It simply verifies the state and reports success. Without this property, “fixing” a switch might inadvertently overwrite routing protocols or ACLs that were manually tuned for specific legacy requirements.

Ansible excels in this area because it is declarative rather than imperative. You define the desired state of your network (e.g., interface GigabitEthernet1/0/1 should have speed 10000, duplex full, and description "Hybrid-Cloud-Uplink"), and Ansible calculates the difference between the current state and the desired state, applying only the necessary changes.

Prerequisites and Environment Setup

Before writing the playbook, you must establish a safe testing environment. Attempting to automate production core switches without a staging lab is a significant risk. For this guide, we assume a Linux-based control node (such as Ubuntu 22.04 LTS) with Ansible installed via the official repository. You will also need access to network devices that support NetConf/RESTCONF or have SSH access enabled for CLI automation.

Required Tools:
* Ansible: Version 2.9 or higher.
* Netmiko: A Python library used by Ansible’s network_cli module to handle SSH connections to Cisco IOS/XR, Juniper Junos, and others.
* Python: Version 3.8+.

Ensure your inventory file (inventory.ini) contains the target core switches with the correct group names (e.g., core_switches). Define connection variables such as ansible_user, ansible_password (preferably using SSH keys or Ansible Vault for security), and ansible_network_os.

The Playbook Structure: Defining Desired States

A robust Ansible playbook for interface configuration must explicitly define the desired attributes for each interface. Below is a simplified example targeting a Cisco IOS-XR device, which is common in large-scale hybrid clouds.

---
- name: Enforce Idempotent Interface Configurations on Core Switches
  hosts: core_switches
  become: true
  vars:
    target_interface: GigabitEthernet1/0/1
    desired_speed: 10000
    desired_duplex: full
    desired_description: "Hybrid-Cloud-Uplink-To-Azure"

  tasks:
    - name: Configure Interface with Desired Attributes
      cisco.iosxr.iosxr_config:
        provider:
            host: "{{ inventory_hostname }}"
            username: "{{ ansible_user }}"
            password: "{{ ansible_password }}"
            transport: cli
        match: none
        replace: true
        config: |
           interface {{ target_interface }}
             speed {{ desired_speed }}
             duplex {{ desired_duplex }}
             description {{ desired_description }}
             no shutdown
      register: interface_result

    - name: Display Changes Made
      debug:
        msg: "Interface {{ target_interface }} updated. Changed attributes: {{ interface_result.changed }}"

Code Explanation:
* The cisco.iosxr.iosxr_config module connects via SSH and enters configuration mode.
* The match: none parameter tells Ansible to ignore the current running config and apply the new block unconditionally within the specified interface context. This is crucial for idempotency; if you omit this, Ansible might try to preserve existing lines not listed in the config block, leading to partial updates.
* The register: interface_result step captures whether a change actually occurred. If the interface was already configured correctly, changed will be false, and no commands are sent to the device.

Verification and Safe Execution Steps

Before deploying to production, you must verify the logic of your playbook. Always test in an isolated lab environment first.

  1. Dry Run: Use the --check flag with Ansible to simulate execution without sending any commands to the device.
    bash
    ansible-playbook interface_config.yml --check -i inventory.ini

    This step confirms that your variables are correct and that the logic identifies drift correctly.

  2. Inspect Output: Look for the changed status in the output. If changed is false on a device where you know a change was needed, review your variable definitions or the module syntax.

  3. Confirm Connectivity: After applying the changes, verify that the interface comes up (no shutdown) and that the speed/duplex settings match the physical cabling capabilities.
    bash
    ssh user@switch_ip "show run interface {{ target_interface }}"

Common Errors and Troubleshooting

Even with safe instructions, errors occur during automation. Here are frequent pitfalls and their fixes:

  • Error: “Unable to connect to device.”

    • Cause: Incorrect SSH port, missing key authentication, or firewall blocking traffic.
    • Fix: Verify ansible_host uses the management IP, ensure the correct port is defined in inventory, and test SSH manually from the control node (ssh -i ~/.ssh/id_rsa user@host).
  • Error: “Invalid command for device OS.”

    • Cause: Using a Cisco IOS-XR module on a standard Cisco IOS switch.
    • Fix: Update the ansible_network_os variable in your inventory to match the specific hardware and software version (e.g., cisco.ios.ios vs cisco.iosxr.iosxr).
  • Error: Configuration Drift Repeats.

    • Cause: Manual changes made to the switch between playbook runs, or a playbook that lacks the match parameter when specific lines need preservation.
    • Fix: Implement strict change management protocols. If manual changes are unavoidable, update the desired state in the playbook immediately to reflect reality, or use Ansible’s gather_facts to dynamically adjust the play.

Industry Application and Student Practice Task

For industry practitioners, this playbook forms the backbone of a nightly reconciliation job. You can schedule this using cron or a workflow orchestrator like Jenkins or GitLab CI to run every Sunday at 02:00 UTC. The goal is to ensure that any emergency changes made during the week are reverted to the baseline unless explicitly approved for permanent retention.

Student Practice Task:
1. Set up two virtual routers (using GNS3 or Eve-NG) acting as core switches.
2. Create an Ansible inventory file listing both devices.
3. Write a playbook that configures VLAN 10 on interface Gi0/1 with specific IP routing settings.
4. Manually change the configuration on one of the routers via CLI to simulate drift (e.g., change the description or remove an ACL).
5. Run the Ansible playbook and observe that it only corrects the drifted router while leaving the compliant one untouched.
6. Document the stdout showing which device was modified and why.

By mastering these techniques, you move from reactive troubleshooting to proactive infrastructure governance, ensuring your hybrid cloud networks remain stable, secure, and aligned with organizational policy.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.