[Day #21 Pyats Series] VLAN database validation before/after changes using pyATS for Cisco

[Day #21 PyATS Series] VLAN Database Validation Before/After Changes Using pyATS for Cisco [Python for Network Engineer]

Introduction

In modern enterprise networks, VLAN management is crucial for traffic segmentation and security. Manual VLAN database validation often leads to human errors and downtime during changes. This is where pyATS, Cisco’s test automation framework, shines. In this article, we’ll learn how to automate VLAN database validation before and after making configuration changes using pyATS. This is a vendor-agnostic approach that helps network engineers gain confidence in their changes while ensuring operational stability.

This guide is tailored for Python for Network Engineer enthusiasts who want to adopt automation-first network validation techniques. By the end of this post, you’ll have a production-ready script that can verify VLAN consistency, detect unintended deletions or additions, and confirm changes across Cisco devices in seconds.


Topology Overview

For our VLAN validation, we’ll use a simple two-switch topology:

  • SW1 – Cisco Catalyst 9300 (Core switch)
  • SW2 – Cisco Catalyst 9200 (Access switch)

These switches are interconnected via trunk links and share the same VLAN database. This script is scalable for multiple devices in larger networks.

VLAN database changes might include adding new VLANs, deleting unused VLANs, or renaming existing VLANs. We’ll validate the database before and after these changes.


Topology & Communications

Communication happens over SSH using pyATS’ testbed configuration. The script:

  • Connects to all switches in the topology
  • Captures pre-change VLAN database
  • Applies configuration changes manually or via automation tools
  • Reconnects to capture post-change VLAN database
  • Compares results to detect anomalies

This is critical for change management processes where pre/post validations are required before closing a change request.


Workflow Script

Here’s the full VLAN database validation script using pyATS:

from genie.testbed import load
from genie.libs.parser.utils.common import parsergen
import json

# Load testbed
testbed = load('testbed.yml')

# Function to capture VLANs
def capture_vlans(device):
    device.connect(log_stdout=False)
    output = device.parse('show vlan brief')
    device.disconnect()
    return output

# Compare VLAN databases
def compare_vlan(pre_vlan, post_vlan):
    pre_set = set(pre_vlan['vlans'].keys())
    post_set = set(post_vlan['vlans'].keys())
    added = post_set - pre_set
    removed = pre_set - post_set
    return added, removed

# Main Execution
if __name__ == "__main__":
    devices = testbed.devices
    vlan_results = {}

    for name, device in devices.items():
        print(f"Capturing VLANs on {name} before changes...")
        vlan_results[name] = {}
        vlan_results[name]['before'] = capture_vlans(device)

    print("Apply VLAN changes now... Press Enter when done.")
    input()

    for name, device in devices.items():
        print(f"Capturing VLANs on {name} after changes...")
        vlan_results[name]['after'] = capture_vlans(device)
        added, removed = compare_vlan(vlan_results[name]['before'], vlan_results[name]['after'])
        print(f"Device: {name}\nAdded VLANs: {added}\nRemoved VLANs: {removed}\n")

    with open('vlan_validation_report.json', 'w') as f:
        json.dump(vlan_results, f, indent=4)

Explanation by Line

  • Import modules: We use Genie (pyATS) to load testbed and parse CLI outputs.
  • capture_vlans(): Connects to the switch, runs show vlan brief, and returns a structured dictionary.
  • compare_vlan(): Compares pre/post VLAN dictionaries and returns added/removed VLANs.
  • Execution:
    • Loop through all devices, capturing VLANs before changes.
    • Wait for manual configuration changes.
    • Capture VLANs after changes and print the differences.
    • Save results to a JSON report.

This modular approach allows you to integrate it into CI/CD pipelines or trigger it via change management systems.


testbed.yml Example

testbed:
  name: vlan_validation
  devices:
    SW1:
      type: switch
      os: iosxe
      connections:
        cli:
          protocol: ssh
          ip: 192.168.1.10
      credentials:
        default:
          username: admin
          password: cisco123
    SW2:
      type: switch
      os: iosxe
      connections:
        cli:
          protocol: ssh
          ip: 192.168.1.11
      credentials:
        default:
          username: admin
          password: cisco123

Post-validation CLI Screenshots (Expected Output)

Before Changes:

SW1# show vlan brief
10   Sales   active
20   HR      active
30   IT      active

After Changes:

SW1# show vlan brief
10   Sales   active
20   HR      active
30   IT      active
40   Marketing active

Script Output:

Device: SW1
Added VLANs: {'40'}
Removed VLANs: set()

Device: SW2
Added VLANs: {'40'}
Removed VLANs: set()

This confirms VLAN 40 was successfully added to both switches.


FAQs

1. Can this script validate hundreds of VLANs at once?

Yes, pyATS handles large VLAN databases efficiently. The parser structures data in dictionaries, allowing comparisons across hundreds of VLANs without performance issues.


2. How does the script detect VLAN deletions vs. additions?

The compare_vlan() function uses set operations to compare VLAN IDs before and after changes. Added VLANs appear in the post-change set but not in the pre-change set, while removed VLANs appear only in the pre-change set.


3. Can VLAN name mismatches be detected automatically?

By default, this script focuses on VLAN IDs. However, you can extend it to compare VLAN names by parsing post_vlan['vlans'][vlan_id]['name'] and flagging mismatches.


4. Does this work with devices running different IOS versions?

Yes. pyATS parsers are version-aware, ensuring the script works with different IOS-XE releases, as long as show vlan brief is supported.


5. How can we integrate this with CI/CD for automated change approvals?

Include this script in your CI/CD pipeline (Jenkins, GitHub Actions) to run pre/post checks automatically. Results can trigger approvals or alerts if unexpected changes are detected.


6. What happens if a switch is unreachable during validation?

The script will throw a connection error. You can add exception handling to skip unreachable devices and log the failure.


7. Can I validate VLAN propagation across trunk links?

Yes. Enhance the script to parse show interfaces trunk or show spanning-tree vlan to confirm VLANs are active and propagated correctly between switches.


8. How do I generate a comprehensive report for auditors?

Use the saved JSON report and convert it into HTML or PDF using libraries like Jinja2 or Pandas for a detailed, auditor-friendly output.


YouTube Link

Watch the Complete Python for Network Engineer: VLAN Database Validation Before/After Changes Using pyATS for Cisco [Python for Network Engineer] Lab Demo & Explanation on our channel:

Master Python Network Automation, Ansible, REST API & Cisco DevNet
Master Python Network Automation, Ansible, REST API & Cisco DevNet
Master Python Network Automation, Ansible, REST API & Cisco DevNet
Why Robot Framework for Network Automation?

Join Our Training

Mastering pyATS is a critical skill for modern network engineers. Trainer Sagar Dhawan is conducting a 3-month instructor-led course covering Python, Ansible, APIs, and Cisco DevNet for Network Engineers. This program is designed to make you proficient in network automation, real-world scripts, and production-grade test validations like VLAN database checks.

Join the Training Here and elevate your career with Python for Network Engineer skills.

Enroll Now & Future‑Proof Your Career
Emailinfo@networkjourney.com
WhatsApp / Call: +91 97395 21088