[Day #33 PyATS Series] VRF Configuration Consistency Check Using pyATS for Cisco [Python for Network Engineer]

[Day #33 PyATS Series] VRF Configuration Consistency Check Using pyATS for Cisco [Python for Network Engineer]

Introduction

Maintaining Virtual Routing and Forwarding (VRF) configuration consistency is critical in multi-tenant or service provider networks. Misaligned VRF configurations can lead to routing leaks, traffic blackholing, and connectivity issues between VRF instances. Traditionally, network engineers manually log into each device to verify VRF names, route targets, and route distinguishers, which is both time-consuming and error-prone.

In this article, part of our 101 Days of pyATS (Vendor-Agnostic) series, Trainer Sagar Dhawan demonstrates how to automate VRF configuration consistency checks using pyATS. This guide is tailored for Python for Network Engineer students aiming to:

  • Validate VRF presence and configuration across multiple Cisco devices
  • Detect mismatched route targets or route distinguishers
  • Generate automated reports for VRF validation
  • Scale the process across large networks effortlessly

By the end, you’ll have a reusable pyATS solution for proactive VRF audits in production environments.


Topology Overview

Our lab topology includes three Cisco routers configured with VRFs:

  • R1 connected to R2, and R2 connected to R3
  • Expected VRFs: Customer_A, Customer_B
  • Each VRF should have consistent Route Distinguishers (RDs) and Route Targets (RTs)

Topology & Communications

  • Protocol: MPLS Layer 3 VPN (using BGP for RT import/export)
  • Connection: CLI-based SSH sessions via pyATS testbed
  • Process:
    1. Connect to each router.
    2. Execute show vrf and show running-config | section vrf.
    3. Parse VRF configurations.
    4. Compare VRF attributes (names, RDs, RTs) for consistency.

Workflow Script

from genie.testbed import load
import json

def get_vrf_config(device):
    device.connect(log_stdout=False)
    vrf_output = device.parse('show vrf')
    device.disconnect()

    vrf_data = {}
    for vrf_name, details in vrf_output['vrfs'].items():
        rd = details.get('rd', 'N/A')
        rt_import = details.get('route_import', [])
        rt_export = details.get('route_export', [])
        vrf_data[vrf_name] = {
            'rd': rd,
            'rt_import': rt_import,
            'rt_export': rt_export
        }
    return vrf_data

def compare_vrfs(vrf_configs):
    mismatches = []
    devices = list(vrf_configs.keys())
    reference = vrf_configs[devices[0]]

    for dev in devices[1:]:
        for vrf, config in reference.items():
            if vrf not in vrf_configs[dev]:
                mismatches.append(f"VRF {vrf} missing on {dev}")
                continue
            if config['rd'] != vrf_configs[dev][vrf]['rd']:
                mismatches.append(f"RD mismatch for VRF {vrf} between {devices[0]} and {dev}")
            if config['rt_import'] != vrf_configs[dev][vrf]['rt_import']:
                mismatches.append(f"Import RT mismatch for VRF {vrf} between {devices[0]} and {dev}")
            if config['rt_export'] != vrf_configs[dev][vrf]['rt_export']:
                mismatches.append(f"Export RT mismatch for VRF {vrf} between {devices[0]} and {dev}")
    return mismatches

if __name__ == "__main__":
    testbed = load('testbed.yml')
    devices = testbed.devices

    vrf_configs = {}
    for name, device in devices.items():
        print(f"Collecting VRF config from {name}...")
        vrf_configs[name] = get_vrf_config(device)

    mismatches = compare_vrfs(vrf_configs)

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

    print(json.dumps(mismatches, indent=4))

Explanation by Line

  • get_vrf_config: Retrieves VRF details (RD, RTs) from each router.
  • compare_vrfs: Compares each device’s VRF config against a reference device.
  • Output: Generates a JSON report highlighting VRF mismatches.

testbed.yml Example

testbed:
  name: vrf_consistency_test
  devices:
    R1:
      os: iosxe
      type: router
      connections:
        cli:
          protocol: ssh
          ip: 192.168.101.11
      credentials:
        default:
          username: admin
          password: cisco123

    R2:
      os: iosxe
      type: router
      connections:
        cli:
          protocol: ssh
          ip: 192.168.101.12
      credentials:
        default:
          username: admin
          password: cisco123

    R3:
      os: iosxe
      type: router
      connections:
        cli:
          protocol: ssh
          ip: 192.168.101.13
      credentials:
        default:
          username: admin
          password: cisco123

Post-validation CLI Screenshots (Expected Output)

R1:

R1# show vrf
VRF              RD            Interfaces
Customer_A       100:1         Gi0/1
Customer_B       100:2         Gi0/2

Script Output:

[
  "RD mismatch for VRF Customer_A between R1 and R2",
  "Export RT mismatch for VRF Customer_B between R1 and R3"
]

FAQs

1. Can this script detect missing VRFs across devices?

Yes. If a VRF is configured on one device but missing on others, the script flags it as a mismatch, ensuring no VRF is overlooked.


2. Does this solution handle multiple route targets for each VRF?

Yes. The script compares lists of import and export route targets, identifying any inconsistencies in multi-target VRF setups.


3. Is it safe to run the VRF consistency check in production?

Absolutely. The script only runs read-only commands (show vrf) and does not modify any running configurations.


4. Can this script validate VRF-specific BGP or OSPF configurations?

Currently, it focuses on VRF definitions, RDs, and RTs. You can extend it with additional parsers to validate routing protocols within each VRF.


5. How scalable is the VRF consistency check for large networks?

pyATS supports parallel connections, allowing you to run VRF consistency checks across dozens or hundreds of devices efficiently.


6. Will this solution work for both Cisco IOS and IOS-XR platforms?

Yes. With the correct Genie parsers, the script can handle VRF outputs from IOS, IOS-XE, and IOS-XR devices.


7. Can I integrate this validation into my CI/CD pipeline?

Yes. The JSON output from the script can be consumed by CI/CD tools to enforce VRF consistency during network changes or new deployments.


8. Does the script generate a report for future auditing?

Yes. The results are stored in a JSON file (vrf_mismatch_report.json), making it easy to archive or integrate with reporting dashboards.


YouTube Link

Watch the Complete Python for Network Engineer: VRF Configuration Consistency Check 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

Automating VRF consistency checks ensures stable multi-tenant networking. Trainer Sagar Dhawan offers a 3-month instructor-led program teaching Python, Ansible, APIs, and Cisco DevNet for Network Engineers. Master pyATS and automate VRF validation and more.

Join Our Training to enhance your career with advanced Python for Network Engineer skills.

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