BG Deployer

Automated blue-green deployment for zero-downtime AWS releases

Updated Jan 15, 2024
8 min read
Intermediate
tools

BG Deployer

BG Deployer is an automated blue-green deployment solution designed for zero-downtime AWS releases. This tool streamlines the deployment process by automatically managing the switching between production and staging environments, ensuring your applications remain available during updates.

Overview

Blue-green deployment is a technique that reduces downtime and risk by running two identical production environments called Blue and Green. At any time, only one of the environments is live, with the other serving as a staging environment for the next version.

Key Features

  • Zero-Downtime Deployments: Switch traffic between environments instantly
  • AWS Integration: Native support for EC2, ECS, Lambda, and RDS
  • Automated Rollback: Quick revert to previous version if issues arise
  • Health Checks: Comprehensive monitoring before traffic switch
  • Cost Optimization: Automatic cleanup of unused environments

Architecture

graph TB
    A[Developer Push] --> B[CI/CD Pipeline]
    B --> C[Build & Test]
    C --> D[Deploy to Green]
    D --> E[Health Checks]
    E --> F{Health OK?}
    F -->|Yes| G[Switch Traffic to Green]
    F -->|No| H[Rollback & Alert]
    G --> I[Monitor Green Environment]
    I --> J[Cleanup Blue Environment]
    H --> K[Investigate Issues]

Installation

Prerequisites

  • AWS CLI configured with appropriate permissions
  • Python 3.8 or higher
  • Docker (for containerized deployments)

Quick Start

# Clone the repository
git clone https://github.com/HarryTheDevOpsGuy/bg-deployer.git
cd bg-deployer

# Install dependencies
pip install -r requirements.txt

# Configure AWS credentials
aws configure

# Run initial setup
python bg_deployer.py setup

Configuration

Environment Variables

# AWS Configuration
export AWS_REGION=us-west-2
export AWS_PROFILE=production

# Application Configuration
export APP_NAME=my-application
export ENVIRONMENT=production
export HEALTH_CHECK_PATH=/health
export HEALTH_CHECK_TIMEOUT=300

Configuration File

Create a bg-deployer.yml configuration file:

application:
  name: "my-application"
  version: "1.2.3"
  
aws:
  region: "us-west-2"
  vpc_id: "vpc-12345678"
  subnet_ids:
    - "subnet-12345678"
    - "subnet-87654321"
  
deployment:
  strategy: "blue-green"
  health_check:
    path: "/health"
    timeout: 300
    interval: 30
    retries: 3
  
  rollback:
    enabled: true
    threshold: 5  # minutes
  
monitoring:
  cloudwatch:
    enabled: true
    log_group: "/aws/bg-deployer"
  
  notifications:
    slack:
      webhook_url: "${SLACK_WEBHOOK_URL}"
    email:
      recipients:
        - "devops@company.com"

Usage

Basic Deployment

# Deploy new version
python bg_deployer.py deploy --version 1.2.3

# Deploy with specific configuration
python bg_deployer.py deploy --config production.yml --version 1.2.3

# Deploy with custom health check
python bg_deployer.py deploy --health-check-path /api/health --timeout 600

Advanced Operations

# Switch traffic manually
python bg_deployer.py switch --environment green

# Rollback to previous version
python bg_deployer.py rollback

# Check deployment status
python bg_deployer.py status

# Cleanup old environments
python bg_deployer.py cleanup --keep-versions 3

Health Checks

BG Deployer performs comprehensive health checks before switching traffic:

HTTP Health Checks

def check_http_health(url, timeout=30):
    """Perform HTTP health check"""
    try:
        response = requests.get(url, timeout=timeout)
        return response.status_code == 200
    except requests.RequestException:
        return False

Database Health Checks

def check_database_health(connection_string):
    """Verify database connectivity"""
    try:
        conn = psycopg2.connect(connection_string)
        cursor = conn.cursor()
        cursor.execute("SELECT 1")
        return True
    except psycopg2.Error:
        return False
    finally:
        if 'conn' in locals():
            conn.close()

Monitoring and Alerting

CloudWatch Integration

BG Deployer automatically creates CloudWatch dashboards and alarms:

cloudwatch:
  metrics:
    - name: "DeploymentSuccess"
      namespace: "BGDeployer"
      unit: "Count"
    
    - name: "DeploymentDuration"
      namespace: "BGDeployer"
      unit: "Seconds"
  
  alarms:
    - name: "DeploymentFailure"
      metric: "DeploymentSuccess"
      threshold: 0
      comparison: "LessThanThreshold"

Slack Notifications

def send_slack_notification(message, webhook_url):
    """Send deployment notification to Slack"""
    payload = {
        "text": f"🚀 BG Deployer: {message}",
        "username": "BG Deployer",
        "icon_emoji": ":rocket:"
    }
    
    response = requests.post(webhook_url, json=payload)
    return response.status_code == 200

Best Practices

1. Environment Preparation

  • Database Migrations: Run migrations before switching traffic
  • Feature Flags: Use feature toggles for gradual rollouts
  • Load Testing: Validate performance in staging environment

2. Monitoring Strategy

  • Key Metrics: Response time, error rate, throughput
  • Alerting: Set up alerts for deployment failures
  • Logging: Centralized logging for troubleshooting

3. Rollback Planning

  • Automated Rollback: Configure automatic rollback triggers
  • Manual Override: Quick manual rollback capabilities
  • Data Consistency: Ensure data integrity during rollbacks

Troubleshooting

Common Issues

Deployment Stuck in Health Check

# Check health check endpoint manually
curl -f http://green-environment/health

# View detailed logs
python bg_deployer.py logs --environment green --tail 100

Traffic Switch Fails

# Check load balancer configuration
aws elbv2 describe-target-groups --target-group-arns $(cat .bg-deployer/target-groups.json)

# Verify security groups
aws ec2 describe-security-groups --group-ids $(cat .bg-deployer/security-groups.json)

Database Connection Issues

# Test database connectivity
python bg_deployer.py test-db --environment green

# Check RDS status
aws rds describe-db-instances --db-instance-identifier my-app-db

Debug Mode

Enable debug mode for detailed logging:

export BG_DEPLOYER_DEBUG=true
python bg_deployer.py deploy --version 1.2.3

API Reference

Command Line Interface

Command Description Options
deploy Deploy new version --version, --config, --dry-run
switch Switch traffic --environment, --force
rollback Rollback deployment --version, --force
status Check status --environment, --verbose
cleanup Cleanup environments --keep-versions, --dry-run

Python API

from bg_deployer import BGDeployer

# Initialize deployer
deployer = BGDeployer(config_file='production.yml')

# Deploy new version
result = deployer.deploy(version='1.2.3')

# Check deployment status
status = deployer.get_status()

# Rollback if needed
if status['health_check_failed']:
    deployer.rollback()

Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Development Setup

# Fork and clone the repository
git clone https://github.com/your-username/bg-deployer.git
cd bg-deployer

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install development dependencies
pip install -r requirements-dev.txt

# Run tests
pytest tests/

# Run linting
flake8 bg_deployer/

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support


**Need Help?** Check out our [FAQ section](https://github.com/HarryTheDevOpsGuy/bg-deployer/wiki/FAQ) or join our community discussions for support and best practices.

Found this helpful?

Help us improve this documentation by sharing your feedback or suggesting improvements.