[Day #72 Pyats Series] Multi-vendor pre-change snapshot automation using pyATS for Cisco [Python for Network Engineer]

[Day #72 Pyats Series] Multi-vendor pre-change snapshot automation using pyATS for Cisco [Python for Network Engineer]

Introduction on the Key Points

In modern network operations, change management is not just about pushing configs—it’s about ensuring that changes do not unintentionally break existing services.
One of the most powerful strategies to achieve this is pre-change snapshot automation, where you capture the current network state before implementing any changes.

With pyATS (Python Automated Test System) and Genie parsers, network engineers can automate baseline snapshots across multiple vendors—Cisco, Arista, Palo Alto, Fortinet—within minutes. This lets you compare the before and after state to quickly detect anomalies.

If you’re a Python for Network Engineer enthusiast, this workflow is gold—it takes away manual pre-checks and replaces them with automated, repeatable, vendor-agnostic snapshots.

By the end of this guide, you’ll learn:

  • How to use pyATS to take multi-vendor snapshots before changes.
  • How to parse device outputs using Genie for structured data.
  • How to store snapshots in a version-controlled folder for easy comparison.
  • How to make this part of your daily change management process.

Topology Overview

For this example, we’ll use a lab with multiple vendor devices:

Device types:

  • Cisco IOS-XE Router – Routing snapshot (routes, interfaces, OSPF)
  • Arista EOS Switch – VLANs, interfaces, spanning-tree
  • Palo Alto Firewall – Security rules, NAT policies
  • FortiGate Firewall – Routing, security policies

Topology & Communications

The workflow:

  1. Engineer schedules a change – New VLANs, routing updates, ACL changes, etc.
  2. pyATS connects to devices – Over SSH/API (multi-vendor compatible).
  3. Collects baseline data – Commands are vendor-specific but output is normalized via Genie parsers.
  4. Stores structured JSON/YAML snapshots – In a snapshots/pre_change/ folder with a timestamp.
  5. Post-change comparison – After the change, run post-change snapshot and use pyats diff to detect changes.

This ensures that if something breaks, you can quickly identify what exactly changed in the network.


Workflow Script

Here’s a sample Python script to take multi-vendor snapshots:

from genie.testbed import load
import os
import datetime

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

# Create snapshot folder
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
snapshot_dir = f"snapshots/pre_change_{timestamp}"
os.makedirs(snapshot_dir, exist_ok=True)

# Commands to run per device
commands = {
    'iosxe': ['show ip route', 'show ip interface brief', 'show ospf neighbor'],
    'eos': ['show vlan', 'show interfaces status', 'show spanning-tree'],
    'panos': ['show system info', 'show running security-policy'],
    'fortinet': ['get router info routing-table all', 'show firewall policy']
}

# Connect to each device and take snapshot
for device_name, device in testbed.devices.items():
    print(f"Connecting to {device_name}...")
    device.connect(log_stdout=False)
    os.makedirs(f"{snapshot_dir}/{device_name}", exist_ok=True)

    # Get vendor OS
    os_type = device.os.lower()
    if os_type in commands:
        for cmd in commands[os_type]:
            output = device.execute(cmd)
            with open(f"{snapshot_dir}/{device_name}/{cmd.replace(' ', '_')}.txt", "w") as f:
                f.write(output)

    device.disconnect()

print(f"Snapshots saved in {snapshot_dir}")

Explanation by Line

  • from genie.testbed import load – Loads pyATS testbed for multi-vendor connections.
  • timestamp – Ensures each run has a unique folder for traceability.
  • commands dict – Vendor-specific commands for baseline capture.
  • device.connect() – pyATS establishes SSH/API sessions.
  • device.execute(cmd) – Executes the CLI/API command.
  • Output storage – Saves raw outputs for audit and comparison.
  • device.disconnect() – Closes the session after snapshot completion.

testbed.yml Example

testbed:
  name: multi_vendor_lab
  credentials:
    default:
      username: admin
      password: Cisco123

devices:
  cisco_r1:
    os: iosxe
    type: router
    connections:
      cli:
        protocol: ssh
        ip: 192.168.100.1

  arista_sw1:
    os: eos
    type: switch
    connections:
      cli:
        protocol: ssh
        ip: 192.168.100.2

  palo_fw1:
    os: panos
    type: firewall
    connections:
      cli:
        protocol: ssh
        ip: 192.168.100.3

  forti_fw1:
    os: fortinet
    type: firewall
    connections:
      cli:
        protocol: ssh
        ip: 192.168.100.4

Post-validation CLI (Real Expected Output)

Example from Cisco Router:

R1# show ip route
Gateway of last resort is 192.168.1.254 to network 0.0.0.0

     10.0.0.0/24 is subnetted, 1 subnets
C       10.0.0.0 is directly connected, GigabitEthernet0/0
O       192.168.50.0/24 [110/2] via 192.168.1.2, 00:00:22, GigabitEthernet0/1

Example from Arista Switch:

sw1> show vlan
VLAN  Name                             Status    Ports
1     default                          active    Et1, Et2
100   MGMT                             active    Et3

FAQs

1. What is the role of Jenkins and GitLab in a pyATS CI/CD pipeline?

  • GitLab: Stores and versions network automation code (pyATS scripts, testbed files, YAML configs).
  • Jenkins: Executes pyATS tests automatically when code changes are pushed or merged in GitLab.
    Together, they bring continuous integration (run tests on every commit) and continuous delivery (automatically deploy or validate configs).

2. How does the pipeline flow work end-to-end?

  1. Developer pushes code (test script or network config) to GitLab.
  2. GitLab webhook triggers Jenkins job.
  3. Jenkins pulls the latest code from the repository.
  4. Jenkins runs pyATS tests (connects to network devices or virtual lab).
  5. pyATS generates results in HTML/XML formats.
  6. Jenkins publishes results and optionally sends notifications.

3. Can this pipeline run pyATS tests on multiple devices in parallel?
Yes.

  • Jenkins can run parallel stages, and pyATS supports running multiple test scripts concurrently.
  • This reduces overall execution time, especially in large testbeds.

4. How should credentials and sensitive data be handled in this setup?

  • Store device credentials in Jenkins Credentials Manager or GitLab CI/CD variables (encrypted).
  • Reference them in pipeline scripts using environment variables.
  • Never hardcode passwords in pyATS scripts or YAML files in GitLab.

5. How are test results integrated into Jenkins?

  • pyATS can export JUnit XML results that Jenkins natively understands.
  • Jenkins can display pass/fail counts, and HTML logs can be published for detailed troubleshooting.
  • You can create trend graphs in Jenkins to track test success rates over time.

6. Can this CI/CD pipeline be used for both lab and production testing?
Yes, but with caution.

  • Lab: Safe for pre-deployment testing.
  • Production: Only run read-only pyATS jobs (e.g., show commands, health checks) to avoid service impact.

7. What happens if a pyATS test fails in the pipeline?

  • Jenkins marks the job as FAILED.
  • GitLab Merge Request can be blocked until tests pass.
  • Notifications can be sent via Slack, Teams, or email to the network team.

8. Is this setup Cisco-only?
No. While Cisco devices are a common use case, pyATS is vendor-agnostic.
You can extend the same Jenkins + GitLab pipeline to Arista, Juniper, Palo Alto, Fortinet, etc., simply by updating the testbed YAML and parser logic.


YouTube Link

Watch the Complete Python for Network Engineer: Create CI/CD pipeline with pyATS (Jenkins + GitLab) 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

Ready to take your Python for Network Engineer skills to the next level?
Trainer Sagar Dhawan (14+ years industry experience) is running a 3-Month Instructor-Led Training where you’ll master automation from zero to advanced, including:

  • Python for Network Engineers
  • Ansible Automation
  • pyATS & Genie Deep Dive
  • Cisco DevNet APIs
  • Multi-vendor Automation (Cisco, Arista, Palo Alto, Fortinet)
  • CI/CD Pipelines for Networking

Next Batch: Check Course Page
Limited Seats Available – Reserve yours today and future-proof your networking career.

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