Skip to content

deploy

Full deployment pipeline with CI/CD integration.

Overview

The deploy command creates a complete deployment pipeline for your Cloudflare Workers application, including continuous integration, automated testing, staging environments, and production deployment with rollback capabilities.

Usage

bash
/template deploy [options]

Options

  • --ci - CI/CD platform: github, gitlab, bitbucket (default: github)
  • --environments - Environments to create (default: preview,staging,production)
  • --auto-deploy - Enable automatic deployments
  • --branch-protection - Set up branch protection rules

Examples

Basic Deployment Setup

bash
/template deploy

GitHub Actions with Auto-deploy

bash
/template deploy --ci github --auto-deploy

Full Pipeline with Protection

bash
/template deploy --environments "dev,staging,prod" --branch-protection

What It Creates

Complete Pipeline Structure

├── .github/
│   ├── workflows/
│   │   ├── ci.yml          # Continuous Integration
│   │   ├── deploy.yml      # Deployment workflow
│   │   ├── preview.yml     # PR preview deployments
│   │   └── release.yml     # Release automation
│   └── dependabot.yml      # Dependency updates
├── deploy/
│   ├── environments/       # Environment configs
│   ├── scripts/           # Deployment scripts
│   └── terraform/         # Infrastructure as Code
├── .env.example           # Environment template
└── DEPLOYMENT.md          # Deployment guide

CI/CD Workflow

yaml
# .github/workflows/ci.yml
name: CI

on:
  push:
    branches: [main, develop]
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  lint:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
      - run: npm ci
      - run: npm run lint

  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
      - run: npm ci
      - run: npm test -- --coverage
      - uses: codecov/codecov-action@v3

  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
      - run: npm ci
      - run: npm run build
      - uses: actions/upload-artifact@v3
        with:
          name: build
          path: dist/

Preview Deployments

yaml
# .github/workflows/preview.yml
name: Preview Deployment

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  deploy-preview:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Deploy Preview
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          command: deploy --env preview-${{ github.event.number }}
          
      - name: Comment PR
        uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `Preview deployed to: https://preview-${context.issue.number}.myapp.workers.dev`
            })

Environment Management

Environment Configuration

toml
# deploy/environments/staging.toml
name = "myapp-staging"
main = "src/index.ts"
compatibility_date = "2024-01-01"

[env.staging.vars]
ENVIRONMENT = "staging"
API_URL = "https://api-staging.myapp.com"
LOG_LEVEL = "debug"

[[env.staging.kv_namespaces]]
binding = "CACHE"
id = "staging-cache-id"

[[env.staging.d1_databases]]
binding = "DB"
database_id = "staging-db-id"

Environment Promotion

bash
#!/bin/bash
# deploy/scripts/promote.sh

FROM_ENV=$1
TO_ENV=$2

echo "Promoting $FROM_ENV to $TO_ENV..."

# Get current deployment
DEPLOYMENT=$(wrangler deployments list --env $FROM_ENV | head -1)

# Deploy to target environment
wrangler deploy --env $TO_ENV --compatibility-date $DEPLOYMENT_DATE

# Run smoke tests
npm run test:smoke -- --env $TO_ENV

Release Management

Semantic Versioning

yaml
# .github/workflows/release.yml
name: Release

on:
  push:
    tags:
      - 'v*'

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - name: Create Release
        uses: softprops/action-gh-release@v1
        with:
          generate_release_notes: true
          
      - name: Deploy to Production
        uses: cloudflare/wrangler-action@v3
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          environment: production

Automated Changelog

javascript
// deploy/scripts/changelog.js
const conventional = require('conventional-changelog');

async function generateChangelog() {
  const changelog = await conventional({
    preset: 'angular',
    releaseCount: 1,
  });
  
  return changelog;
}

Infrastructure as Code

Terraform Configuration

hcl
# deploy/terraform/main.tf
terraform {
  required_providers {
    cloudflare = {
      source = "cloudflare/cloudflare"
      version = "~> 4.0"
    }
  }
}

resource "cloudflare_workers_kv_namespace" "cache" {
  account_id = var.cloudflare_account_id
  title      = "${var.app_name}-cache-${var.environment}"
}

resource "cloudflare_d1_database" "db" {
  account_id = var.cloudflare_account_id
  name       = "${var.app_name}-db-${var.environment}"
}

resource "cloudflare_worker_script" "app" {
  account_id = var.cloudflare_account_id
  name       = "${var.app_name}-${var.environment}"
  content    = file("${path.module}/../../dist/index.js")

  kv_namespace_binding {
    name         = "CACHE"
    namespace_id = cloudflare_workers_kv_namespace.cache.id
  }

  d1_database_binding {
    name        = "DB"
    database_id = cloudflare_d1_database.db.id
  }
}

Monitoring & Alerts

Deployment Monitoring

typescript
// deploy/monitoring/alerts.ts
export async function setupAlerts() {
  // CPU usage alert
  await createAlert({
    name: 'high-cpu-usage',
    condition: 'cpu > 80',
    duration: '5m',
    action: 'email',
  });
  
  // Error rate alert
  await createAlert({
    name: 'high-error-rate',
    condition: 'error_rate > 0.05',
    duration: '2m',
    action: 'slack',
  });
}

Health Checks

typescript
// Deployment health endpoint
app.get('/deploy/health', async (c) => {
  const checks = await runHealthChecks(c.env);
  
  return c.json({
    status: checks.every(c => c.passed) ? 'healthy' : 'unhealthy',
    checks,
    deployment: {
      version: c.env.VERSION,
      environment: c.env.ENVIRONMENT,
      timestamp: c.env.DEPLOY_TIME,
    },
  });
});

Rollback Strategy

Automated Rollback

yaml
# Part of deploy workflow
- name: Deploy and Monitor
  run: |
    # Deploy
    wrangler deploy --env production
    
    # Monitor for 5 minutes
    npm run monitor:deployment -- --duration 5m
    
    # Rollback if errors detected
    if [ $? -ne 0 ]; then
      wrangler rollback --env production
      exit 1
    fi

Manual Rollback Process

  1. Identify the issue
  2. Check deployment history
  3. Rollback to last known good
  4. Investigate and fix
  5. Re-deploy when ready

Security Best Practices

Secret Management

bash
# Never commit secrets
# Use GitHub Secrets for CI/CD
# Use wrangler secrets for runtime

# Set secrets
wrangler secret put API_KEY --env production
wrangler secret put DATABASE_URL --env production

Branch Protection

json
{
  "protection_rules": {
    "main": {
      "required_reviews": 2,
      "dismiss_stale_reviews": true,
      "require_code_owner_reviews": true,
      "required_status_checks": ["ci", "test"],
      "enforce_admins": false,
      "restrictions": {
        "teams": ["maintainers"]
      }
    }
  }
}

Performance Testing

Load Testing

bash
# deploy/scripts/load-test.sh
#!/bin/bash

ENV=$1
URL="https://$ENV.myapp.workers.dev"

# Run load test
k6 run \
  --vus 100 \
  --duration 30s \
  --env BASE_URL=$URL \
  deploy/tests/load.js

Performance Budget

javascript
// deploy/performance-budget.js
module.exports = {
  timings: {
    firstByte: 100,
    firstPaint: 200,
    interactive: 500,
  },
  sizes: {
    javascript: 500 * 1024, // 500KB
    total: 1024 * 1024,     // 1MB
  },
};

Deployment Checklist

Pre-deployment

  • [ ] All tests passing
  • [ ] Code reviewed and approved
  • [ ] Database migrations ready
  • [ ] Secrets configured
  • [ ] Performance budget met

Post-deployment

  • [ ] Health checks passing
  • [ ] No error spike
  • [ ] Performance metrics normal
  • [ ] User reports monitored
  • [ ] Rollback plan ready

Built with ❤️ for the AI Coding community, by Praney Behl