Automated Canary Deployment with Rollback

By: fyvo August 3, 2025 DevOps

Description

This script simulates a canary deployment strategy using a simple flag. If the canary deployment fails, it automatically rolls back to the previous version. This is a simplified example and requires adaptation for real-world scenarios.

Code Snippet

import time
import random

# Simulate application versions
version_a = {"name": "v1.0", "success_rate": 0.9}
version_b = {"name": "v1.1", "success_rate": 0.7}

def deploy(version):
    print(f"Deploying {version['name']}...")
    if random.random() < version['success_rate']:
        print(f"{version['name']} deployment successful!")
        return True
    else:
        print(f"{version['name']} deployment failed!")
        return False

def rollback():
    print("Rolling back to v1.0...")
    # Simulate rollback
    time.sleep(2)
    print("Rollback complete.")

# Canary deployment
canary_success = deploy(version_b)

if canary_success:
    print("Canary deployment successful.  Switching to new version.")
else:
    rollback()

Discussion (0)