Skip to content

Implement

Implement Solutionsยถ

Stage 3 of the PRIME Frameworkยถ

"Code is a liability, not an asset. The Implement stage focuses on building just enough automationโ€”maintainable, documented, and built to last."

Stage Outcome

Deliverable: Production-ready Python scripts with line-by-line documentation, comprehensive error handling, and pre/post-flight validation.

Typical Result: Hardened automation that runs reliably in production, with complete audit trails and the ability for your team to modify and extend it independently.

graph LR
    A[๐Ÿ› ๏ธ Setup] --> B[๐Ÿ“ Code]
    B --> C[โœ… Test]
    C --> D[๐Ÿ“ฆ Deploy]

    style A fill:#50C878
    style B fill:#60D388
    style C fill:#70DE98
    style D fill:#80E9A8

Prime Terminology Used: Prime Agents development, PRIME Philosophy principles, Prime Efficiency Stack


๐ŸŽฏ Objectiveยถ

Transform designs from the Re-engineer stage into production-ready automation that aligns with the PRIME Philosophy.


Between the Lines

Precision shooting rewards the same discipline good automation code does: control your breathing, follow the same sequence every time, and the outcome stops being a surprise.

Neither one is about being fast. Both are about being repeatable enough that fast becomes possible later, safely.

โš™๏ธ What Happens During Implementยถ

1. Development Environment Setupยถ

Before writing code, we establish consistent tooling:

Local Development Standardsยถ

Python Environment:

```text
Python 3.9+ (avoid cutting edge, prefer stability)
Virtual environment (venv or conda)
requirements.txt with pinned versions
```

Essential Libraries:

```python
netmiko==4.1.2      # SSH connections
textfsm==1.1.3      # Output parsing
jinja2==3.1.2       # Config templating
pandas==2.0.3       # Data manipulation
openpyxl==3.1.2     # Excel reporting
pyyaml==6.0.1       # Config files
python-dotenv==1.0.0 # Environment variables
```

Code Quality Tools:

```text
black                # Code formatting
pylint               # Linting
pytest               # Testing
```

Source Controlยถ

All automation projects use Git from day one:

```text
automation-project/
โ”œโ”€โ”€ .gitignore       # Exclude credentials, outputs
โ”œโ”€โ”€ README.md        # Project documentation
โ”œโ”€โ”€ requirements.txt # Dependencies
โ”œโ”€โ”€ config/          # YAML configs (NOT in git)
โ”œโ”€โ”€ templates/       # Jinja2 templates
โ”œโ”€โ”€ scripts/         # Python scripts
โ”œโ”€โ”€ tests/           # Unit tests
โ””โ”€โ”€ outputs/         # Generated reports (NOT in git)
```

2. Implementation Guided by PRIME Philosophyยถ

Every line of code reflects our five core principles. Here are key implementation patterns:

Production Safety is Non-Negotiable

Most scripts fail in production because they were written for happy-path scenarios. We build every script assuming:

  • Connection timeouts will happen
  • Authentication will fail on some devices
  • Config tasks will raise exceptions
  • Partially-completed operations must be detected
  • Human visibility into failures is essential

These aren't edge casesโ€”they're baseline requirements.

๐Ÿ” Principle 1: Transparency Over Obscurityยถ

What This Means in Practice:

โŒ Avoid: Over-engineering

```python
# DON'T: Abstract factory pattern for 2 device types
class DeviceFactory:
    @staticmethod
    def create_device(device_type):
        if device_type == "cisco_ios":
            return CiscoIOSDevice()
        elif device_type == "cisco_nxos":
            return CiscoNXOSDevice()
```

โœ… Prefer: Simple, direct solutions

```python
# DO: Simple conditional logic
device_type = "cisco_ios" if "IOS" in version else "cisco_nxos"
connection = ConnectHandler(device_type=device_type, **device)
```

When to Choose Pragmatic:

  • You're solving a single use case (don't abstract prematurely)
  • The "perfect" solution adds 40% complexity for 5% benefit
  • The simpler approach will work for 12-24 months

When to Add Complexity:

  • You're solving the same problem the 3rd time (DRY principle)
  • Complexity reduction elsewhere outweighs local increase
  • Scalability requirements are certain, not speculative

๏ฟฝ๏ธ Principle 2: Safety Over Speedยถ

What This Means in Practice:

โœ… Verbose Logging:

```python
# Track progress for multi-device operations
logger.info(f"Starting VLAN provisioning for {len(devices)} devices")

for device in devices:
    logger.info(f"Connecting to {device['hostname']} ({device['ip']})")
    try:
        connection = ConnectHandler(**device)
        logger.info(f"โœ“ Connected to {device['hostname']}")

        output = connection.send_config_set(config_commands)
        logger.info(f"โœ“ Config applied to {device['hostname']}")

        # Validation
        verify = connection.send_command("show vlan brief")
        if new_vlan_id in verify:
            logger.info(f"โœ“ VLAN {new_vlan_id} verified on {device['hostname']}")
        else:
            logger.warning(f"โœ— VLAN {new_vlan_id} NOT found on {device['hostname']}")

    except NetmikoTimeoutException:
        logger.error(f"โœ— Timeout connecting to {device['hostname']}")
        failed_devices.append(device['hostname'])
    except NetmikoAuthenticationException:
        logger.error(f"โœ— Authentication failed for {device['hostname']}")
        failed_devices.append(device['hostname'])

logger.info(f"Completed: {len(devices) - len(failed_devices)}/{len(devices)} successful")
```

Output Example:

```text
2024-01-15 10:30:22 INFO Starting VLAN provisioning for 12 devices
2024-01-15 10:30:23 INFO Connecting to SW-ACCESS-01 (192.168.1.10)
2024-01-15 10:30:24 INFO โœ“ Connected to SW-ACCESS-01
2024-01-15 10:30:26 INFO โœ“ Config applied to SW-ACCESS-01
2024-01-15 10:30:27 INFO โœ“ VLAN 150 verified on SW-ACCESS-01
2024-01-15 10:30:27 INFO Connecting to SW-ACCESS-02 (192.168.1.11)
...
2024-01-15 10:31:45 INFO Completed: 11/12 successful
```

โœ… Human-Readable Output:

```python
# Generate Excel reports, not just terminal output
df = pd.DataFrame(results)
df.to_excel("vlan_provisioning_report.xlsx", index=False)

# Include summary statistics
summary = {
    "Total Devices": len(devices),
    "Successful": len(success_devices),
    "Failed": len(failed_devices),
    "Duration": f"{duration:.1f} seconds"
}
```

๏ฟฝ Principle 3: Empowerment Through Documentationยถ

What This Means in Practice:

โœ… Validate Before Changing:

```python
# PRE-FLIGHT CHECKS
def pre_flight_checks(device):
    """
    Verify device is safe to modify.
    Returns (bool, str): (is_safe, failure_reason)
    """
    # Check reachability
    if not ping_device(device['ip']):
        return False, "Device unreachable"

    # Verify no existing config session
    output = send_command("show configuration sessions")
    if "Session" in output:
        return False, "Active config session detected"

    # Check VLAN ID isn't already used
    vlans = send_command("show vlan brief")
    if new_vlan_id in parse_vlans(vlans):
        return False, f"VLAN {new_vlan_id} already exists"

    return True, "All checks passed"

# Only proceed if safe
is_safe, reason = pre_flight_checks(device)
if not is_safe:
    logger.warning(f"Skipping {device['hostname']}: {reason}")
    continue
```

โœ… Verify After Changing:

```python
# POST-FLIGHT VALIDATION
def verify_vlan_creation(connection, vlan_id, vlan_name):
    """
    Confirm VLAN was actually created.
    """
    output = connection.send_command("show vlan brief")

    if str(vlan_id) in output and vlan_name in output:
        return True
    else:
        # VLAN creation failed - trigger rollback
        logger.error(f"VLAN {vlan_id} not found after creation")
        rollback_vlan(connection, vlan_id)
        return False
```

โœ… Automatic Rollback:

```python
# CHECKPOINT BEFORE CHANGE
checkpoint_name = f"before_vlan_{vlan_id}_{timestamp}"
connection.send_command(f"archive config")

try:
    # Apply change
    connection.send_config_set(config_commands)

    # Verify
    if not verify_vlan_creation(connection, vlan_id, vlan_name):
        raise ValidationError("VLAN verification failed")

except Exception as e:
    logger.error(f"Change failed: {e}. Rolling back...")
    connection.send_command(f"configure replace flash:checkpoint")
    raise
```

3. Code Structure Standardsยถ

All implemented automation follows a consistent structure:

Main Script Templateยถ

```python
#!/usr/bin/env python3
"""
VLAN Provisioning Automation

Description:
    Provisions VLANs across multiple access switches with validation.

Usage:
    python provision_vlan.py --vlan 150 --name "Guest_WiFi"

Author: Nautomation Prime
Created: 2024-01-15
"""

import logging
from netmiko import ConnectHandler, NetmikoTimeoutException
import pandas as pd
from datetime import datetime

# ============================================================================
# CONFIGURATION
# ============================================================================

# Logging setup
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('vlan_provisioning.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

# ============================================================================
# CORE FUNCTIONS
# ============================================================================

def load_device_inventory(csv_file):
    """Load device list from CSV file."""
    pass

def pre_flight_checks(connection, vlan_id):
    """Validate device is safe to modify."""
    pass

def apply_vlan_config(connection, vlan_id, vlan_name):
    """Apply VLAN configuration to device."""
    pass

def verify_vlan_creation(connection, vlan_id):
    """Verify VLAN was successfully created."""
    pass

def generate_report(results, output_file):
    """Create Excel report of provisioning results."""
    pass

# ============================================================================
# MAIN EXECUTION
# ============================================================================

def main():
    """Main automation workflow."""
    logger.info("=== VLAN Provisioning Started ===")

    # Load devices
    devices = load_device_inventory("inventory.csv")
    logger.info(f"Loaded {len(devices)} devices from inventory")

    # Results tracking
    results = []

    # Process each device
    for device in devices:
        result = process_device(device)
        results.append(result)

    # Generate report
    generate_report(results, "vlan_report.xlsx")

    logger.info("=== VLAN Provisioning Completed ===")

if __name__ == "__main__":
    main()
```

4. Testing Strategyยถ

All automation is tested before production deployment:

Lab Testingยถ

Requirements:
Minimum 3 lab devices matching production platforms

Test Cases:

  • โœ… Normal operation (happy path)
  • โœ… Device unreachable
  • โœ… Invalid credentials
  • โœ… Config rejected (syntax error)
  • โœ… Partial failure (some devices succeed, others fail)
  • โœ… Network interruption mid-execution

Staging Environmentยถ

For high-risk changes:

  1. Dry-run mode โ€” Validate without applying
  2. Pilot group โ€” 2-3 production devices, off-hours
  3. Phased rollout โ€” 25% โ†’ 50% โ†’ 100% over days

5. Documentation Standardsยถ

Every script includes:

README.mdยถ

```markdown
# VLAN Provisioning Automation

## Purpose
Provisions VLANs to access switches with pre-flight validation.

## Prerequisites

- Python 3.9+
- Network connectivity to devices
- Credentials in `.env` file

## Installation
```bash
pip install -r requirements.txt
```

Usageยถ

```bash
python provision_vlan.py --vlan 150 --name "Guest_WiFi"
```

Configurationยถ

Edit inventory.csv with target devices.

Troubleshootingยถ

  • "Device unreachable" โ€” Verify ICMP/SSH connectivity
  • "Authentication failed" โ€” Check credentials in .env

Inline Commentsยถ

Focus on why, not what:

```python
# DON'T: State the obvious
x = x + 1  # Increment x

# DO: Explain the reasoning
x = x + 1  # Account for 1-based VLAN IDs in UI vs 0-based array
```

๐Ÿ“Š Deliverable: Production-Ready Automationยถ

At the end of the Implement stage, you receive:

1. Tested Python Scriptsยถ

  • Fully functional automation
  • Error handling for all failure modes
  • Logging throughout execution
  • Command-line arguments or config files

2. Supporting Filesยถ

  • requirements.txt โ€” Pinned dependencies
  • inventory.csv โ€” Device list template
  • config_templates/ โ€” Jinja2 templates
  • .env.example โ€” Environment variable template

3. Documentationยถ

  • README.md โ€” Installation, usage, troubleshooting
  • CHANGELOG.md โ€” Version history
  • Inline comments โ€” Explaining complex logic

4. Test Resultsยถ

  • Lab test report
  • Pilot deployment summary (if applicable)
  • Known limitations documented

๐Ÿ’ก Why Implement with PRIME Philosophy Mattersยถ

Long-Term Maintainabilityยถ

Code written with Pragmatic/Transparent/Reliable principles:

  • 6 months later: You (or teammate) can understand and modify
  • 12 months later: Still works without updates (stable dependencies)
  • 24 months later: Easy to extend for new use cases

Operational Confidenceยถ

When automation runs in production:

  • Transparency: Logs show exactly what happened
  • Reliability: Pre/post-flight checks catch issues early
  • Pragmatic: Simple code means faster troubleshooting

๐Ÿš€ What Happens Nextยถ

After implementation, proceed to Stage 4: Measure to track performance and ROI.


๐Ÿ“‹ Implement Checklistยถ

Before deploying to production:

  • Code follows PRIME Philosophy principles
  • All error conditions handled gracefully
  • Logging provides visibility into execution
  • Pre-flight and post-flight validation implemented
  • Rollback mechanism tested
  • Lab testing completed for all scenarios
  • Documentation complete (README + inline comments)
  • Credentials secured (not hardcoded)
  • Pilot deployment successful (if high-risk)
  • Handoff training scheduled (if external development)

๐Ÿ’ผ Engagement Optionsยถ

Implementation as Part of Full PRIME Engagementยถ

Included as Stage 3 when you engage for the complete framework. Typically 2-6 weeks per automation (depending on complexity from Re-engineer phase).

Standalone Implementation Serviceยถ

For organisations with designs but need development help:

Fixed Fee: ยฃ8,000 - ยฃ20,000+, quoted against the Re-engineer specification

Includes:

  • Production-ready Python scripts
  • Comprehensive testing
  • Full documentation
  • Knowledge transfer session

๐ŸŽ“ Learn Moreยถ


Mission: To empower network engineers through the PRIME Frameworkโ€”delivering automation with measurable ROI, production-grade quality, and sustainable team capability built on the PRIME Philosophy of transparency, measurability, ownership, safety, and empowerment.


โ† Previous: Re-engineer | Back to PRIME Framework | Next: Measure โ†’