Target Audience: Likely a DevOps Engineer, Platform Engineer, or Software Developer looking for best practices and implementation details. The tone should be professional, technical, and structured.
Structure of the Response:
High-Level Overview: Briefly explain the goal (automation, reliability).
Branching Strategy: Compare GitFlow vs. Trunk-Based (recommend Trunk-Based for modern CI/CD).
Pipeline Architecture: Visualizing the stages (Source -> Build -> Test -> Deploy).
Detailed Sections:
Build & Test: What happens here.
Artifacts: Handling outputs.
Environments: Promotion logic.
Deployment Strategies: Explain Blue/Green vs. Canary.
Rollbacks & Approvals: Safety nets.
Example Configuration: I need to choose a popular tool. GitHub Actions is very common and readable. I'll also provide a conceptual Jenkinsfile or ArgoCD reference for the GitOps part, but focusing on one complete example is usually better for clarity. Let's stick to a GitHub Actions workflow that mimics a robust enterprise pipeline, perhaps referencing Helm/Kubernetes for the deployment part since that's standard for Blue/Green/Canary.
Drafting Content - Specific Points:
Branching:
Trunk-Based: Main is always deployable. Short-lived feature branches.
GitFlow: Good for versioned releases, slower.
Recommendation: Trunk-based with feature flags.
Build/Test:
Build: Compile code, create Docker image.
Test: Unit (fast), Integration (slower), SAST (security).
Artifacts:
Immutable tags (SHA, not latest).
Registry (ECR, Docker Hub, Artifactory).
Deployment Strategies:
Blue/Green: Two identical environments. Switch traffic instantly (DNS/Load Balancer). Zero downtime, easy rollback.
Canary: Release to 1% -> 10% -> 100%. Monitor metrics. Good for risk mitigation.
Rollback:
Automated (if tests fail).
Manual (if prod metrics spike).
GitOps approach: git revert triggers pipeline.
Approvals:
Prod gates.
Example Config Construction (GitHub Actions):
I will create a single comprehensive YAML file or a logical sequence of them.
Refining the Deployment Strategy:
Since Blue/Green and Canary depend heavily on the infrastructure (K8s, AWS, VMs), I should explain the logic in the pipeline and provide a snippet that represents the command to trigger it (e.g., updating a Helm value or running a script), rather than trying to write the Terraform/K8s manifest itself (too complex/broad). I will assume Kubernetes/Helm as the target environment as it's the standard for advanced deployment patterns.
Self-Correction/Review:
Did I include Approvals? Yes, environment with protection rules in GitHub Actions.
Did I cover Artifacts? Yes, actions/upload-artifact and Docker push.
Is the distinction between Blue/Green and Canary clear? I need to make sure I define them clearly.
Let's write the response. I will organize it logically:
Strategy & Workflow Diagram.
Component Deep Dive.
The "How-To" (Implementation details).
The Code (Example).
Branching: Recommend Trunk Based Development (TBD).
Let's create a GitHub Actions example. It's the most widely accessible for readers.
For the deployment strategy implementation, I will describe the workflow steps (e.g., "Deploy new version", "Run health check", "Switch traffic").
Final Polish: Ensure formatting (bolding, code blocks) makes it readable.
(Self-Correction during drafting): The user asked for "Design". I shouldn't just dump code. I need to explain the design decisions.
Why tag with SHA? (Immutability).
Why approvals? (Compliance/Safety).
Why Canary? (Risk reduction).
Let's go.
This guide outlines a robust, enterprise-grade CI/CD architecture. It focuses on Trunk-Based Development (for high velocity) combined with GitOps (for reliability).
1. High-Level Architecture
Branching Strategy: Trunk-Based Development
For modern CI/CD, long-lived branches (like develop or release/*) create "merge hell."
Main (master/main): Always deployable. Branches are short-lived (< 1 day).
Feature Branches: Created from main, merged back via Pull Request (PR).
Releases: Cut from main tags.
The Pipeline Flow
CI (Continuous Integration): Build -> Unit Test -> Static Analysis -> Artifact Build -> Push to Registry.
CD (Continuous Deployment): Deploy Dev -> Auto/Manual Promote Staging -> Manual Approval -> Deploy Prod (Canary/Blue-Green).
Artifact Generation: Build a Docker image. Tag with the Git Commit SHA (immutable tags) rather than latest.
B. Artifacts & Versioning
Immutable Artifacts: The artifact built in CI is the exact same binary promoted through environments. Do not rebuild for Prod.
Tagging Strategy:my-app:<git-sha>.
Storage: Docker Registry (ECR/Hub) or Generic Binary Repository (Artifactory/Nexus).
C. Environment Promotion
Dev: Auto-deploy on merge to main.
Staging: Auto-deploy after Dev succeeds. Must match Prod infra (data masking).
Prod: Manual trigger or "Push Button" deployment.
D. Deployment Strategies (Prod)
Blue/Green (Zero Downtime):
Blue: Current live traffic.
Green: New version with no traffic.
Action: Deploy to Green -> Run Smoke Tests -> Switch Load Balancer to Green -> Tear down Blue.
Canary (Risk Mitigation):
Deploy new version to a subset of pods/infrastructure.
Route 5% of traffic.
Monitor Error Rate / Latency for 10 mins.
If healthy -> Scale to 100%. If not -> Rollback.
E. Rollbacks
Automated: If a Canary deployment detects a spike in 5xx errors (>5% threshold), the pipeline automatically triggers a rollback.
Manual:kubectl rollout undo or re-running the pipeline with the previous Git SHA.
3. Example Configuration (GitHub Actions)
This example demonstrates a complete workflow: CI, artifact tagging, manual approval, and a Blue/Green deployment simulation.
File:.github/workflows/main.yml
yaml
name: CI/CD Pipeline
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
# Use the Git SHA for immutable versioning
TAG: ${{ github.sha }}
jobs:
# --- STAGE 1: BUILD & TEST ---
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v3
- name: Run Unit Tests
run: |
echo "Running Unit Tests..."
# npm test || go test ./... || mvn test
- name: Run Linting (Static Analysis)
run: |
echo "Running Linter..."
# npm run lint
- name: Build Docker Image
run: docker build -t $REGISTRY/$IMAGE_NAME:$TAG .
- name: Login to Registry
uses: docker/login-action@v2
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Push Artifact
run: docker push $REGISTRY/$IMAGE_NAME:$TAG
# --- STAGE 2: DEV DEPLOYMENT (Automatic) ---
deploy_dev:
needs: build
runs-on: ubuntu-latest
environment: Development
steps:
- name: Deploy to Dev Cluster
run: |
echo "Deploying $TAG to Dev Environment..."
# kubectl set image deployment/my-app my-app=$REGISTRY/$IMAGE_NAME:$TAG
# --- STAGE 3: PROD DEPLOYMENT (Manual Approval + Strategy) ---
deploy_prod:
needs: deploy_dev
runs-on: ubuntu-latest
# This creates the "Approve" button in the GitHub UI
environment: Production
steps:
- name: Checkout Code
uses: actions/checkout@v3
- name: Configure Kubernetes Context
uses: azure/k8s-set-context@v3
with:
kubeconfig: ${{ secrets.KUBE_CONFIG }}
- name: Blue/Green Deployment Logic
run: |
echo "Starting Blue/Green Deployment..."
# 1. Deploy to 'Green' (Inactive) environment
kubectl apply -f k8s/green-deployment.yaml --record
# 2. Wait for Green to be Ready
kubectl rollout status deployment/my-app-green -n prod
# 3. Run Smoke Tests against the Green service internally
echo "Running Smoke Tests..."
# ./scripts/run-smoke-tests.sh service-green-internal-ip
# 4. Switch Service Selector to Green
# This effectively cuts over traffic immediately
kubectl patch service my-app-service -n prod -p '{"spec":{"selector":{"version":"green"}}}'
echo "Traffic switched to Green version."
# --- STAGE 4: ROLLBACK (Simulated logic) ---
# Note: Rollbacks are usually manual or part of the deployment script logic
rollback_prod:
needs: deploy_prod
runs-on: ubuntu-latest
if: failure() # This runs if the previous step fails (simplified)
steps:
- name: Rollback Production
run: |
echo "ALERT: Deployment failed or health checks failed."
kubectl rollout undo deployment/my-app -n prod
4. Detailed Strategy Breakdown
Handling Approvals
In the example above, the environment: Production line in GitHub Actions triggers a protection rule.
How it works: You configure the "Production" environment in the repository settings to require a review from specific teams (e.g., "DevOps Leads").
Result: The pipeline pauses at deploy_prod until a human clicks "Approve."
Implementing Canary (Advanced)
If using a Service Mesh (Istio/Linkerd) or AWS App Mesh, the deployment script changes slightly. You don't just switch 100% traffic. You modify the routing rules.
Pseudo-code for Canary script:
bash
# 1. Deploy Canary Pods (New Version)
kubectl scale deployment my-app-canary --replicas=2
# 2. Route 10% traffic to Canary via Istio VirtualService
istioctl apply -f routing-10-percent.yaml
# 3. Monitor Metrics (Look for HTTP 500s)
# This requires integration with Prometheus/Datadog
METRICS_OK=$(curl -X GET "https://api.datadog.com/metrics?from=10m_ago&query=avg:system.cpu.idle{version:canary}")
if [ "$METRICS_OK" -gt 95 ]; then
echo "Canary Healthy -> Routing 100%"
kubectl patch service my-app ...
else
echo "Canary Unhealthy -> Rollback"
kubectl delete deployment my-app-canary
exit 1
fi
The Rollback Mechanism
There are two ways to handle rollbacks:
kubectl rollout undo: Quick fix. It tells Kubernetes to switch the ReplicaSet back to the previous version. It uses the old image tag.
GitOps Revert: You revert the commit in Git. The GitOps operator (ArgoCD/Flux) sees the state drift and applies the old manifest. This is preferred as it ensures Git remains the source of truth.
Summary Checklist
Branching: Trunk-based (Feature -> Main).
Artifacts: Docker images tagged with Git SHA.
Dev: Auto-deploy on merge.
Prod: Manual approval gate.
Strategy: Blue/Green for zero downtime; Canary for risk analysis.
Observability: Integrate Prometheus/DataDog checks during the deployment stage to automate rollback decisions.