We are going to design a CI/CD pipeline for a typical microservice or application. We'll cover:
- Branching strategy (GitFlow, GitHub Flow, etc.)
- Build and test stages (unit tests, integration tests, etc.)
- Artifacts (what we store and how)
- Environment promotion (from dev to prod)
- Deployment strategies (canary, blue-green)
- Rollback procedures
- Approvals (manual gates, automated checks)
We'll assume we are using a Git-based version control (like Git) and a CI/CD tool that can support pipelines (like Jenkins, GitLab CI, GitHub Actions, etc.).
For example configs, we'll use a generic YAML format that can be adapted to various tools.
Let's break it down:
-
Branching Strategy:
We'll use a simplified GitFlow:
main branch: production-ready code.
develop branch: integration branch for features.
feature/* branches: for new features, branched from develop and merged back to develop.
release/* branches: for preparing a release, branched from develop and merged into main and develop.
hotfix/* branches: for emergency fixes on production, branched from main and merged into main and develop.
Alternatively, for faster release cycles, we might use GitHub Flow (only main and feature branches) but with more automation.
-
Build and Test Stages:
Typically:
- Checkout code
- Set up environment (dependencies, etc.)
- Run static code analysis (linter, security scan)
- Run unit tests
- Build the application (create an artifact, e.g., Docker image, JAR, etc.)
- Run integration tests (if any, might require a test environment)
- Run end-to-end tests (optional, might be in a separate pipeline)
We can split into multiple jobs for parallelization.
-
Artifacts:
We'll store build artifacts in an artifact repository (like Nexus, Artifactory) or container registry (Docker Hub, ECR, GCR, etc.).
For each successful build, we tag the artifact with:
- Git commit SHA
- Branch name (for non-main branches, might not be stored long-term)
- Version (from project version, e.g., from pom.xml or package.json)
We'll keep a record of which artifact is deployed in which environment.
-
Environment Promotion:
We'll have multiple environments:
- Development (dev): automatically deployed from
develop branch (or feature branches if we want to preview).
- Staging (staging): deployed from
release/* branches or from main after manual approval.
- Production (prod): deployed from
main branch, with manual approval and possibly canary/blue-green.
Promotion can be done by:
- Building the artifact once and then promoting the same artifact to higher environments (to ensure consistency).
- Alternatively, building in each environment (but then we risk having different binaries).
-
Deployment Strategies:
- Blue-Green: Deploy the new version to a new environment (green) while the old (blue) is running, then switch traffic.
- Canary: Gradually roll out the new version to a subset of users, then increase.
We can use:
- Kubernetes: with Ingress for canary (using service mesh like Istio) or blue-green (using two deployments and switching service).
- Cloud provider load balancers: for blue-green (swap IPs) or canary (weighted target groups).
-
Rollback:
In case of failure, we can:
- For blue-green: switch back to the old environment (blue).
- For canary: stop the rollout and revert traffic to the old version.
- In Kubernetes: we can roll back the deployment to the previous revision (if using deployments).
We should also have automated health checks to trigger rollback.
-
Approvals:
- Manual approval before deploying to production (and maybe staging).
- Automated checks: all tests pass, security scans passed, etc.
Example Config:
We'll write a pipeline in a generic YAML that can be adapted. Let's assume we are building a Docker image and deploying to Kubernetes.
Steps:
a. On push to develop branch:
- Build and test, then push the Docker image with a tag develop-<commit-sha>.
- Deploy to dev environment (automatically).
b. On push to main branch (or when merging a release branch):
- Build and test, then push the Docker image with a tag v<version> (from tags) or main-<commit-sha>.
- Wait for manual approval to deploy to staging.
- Then, after approval, deploy to staging with blue-green (or canary) strategy.
- After staging validation, wait for manual approval to deploy to prod.
- Deploy to prod with blue-green (or canary) and monitor.
c. On push to hotfix/* branches:
- Similar to main but for emergency fix.
However, note: we want to build once and promote the same artifact. So we might have:
- A pipeline that builds and publishes the artifact (on
develop and main).
- Then, separate pipelines for promotion that just deploy the already built artifact.
Alternatively, we can have a single pipeline that does:
Stage 1: Build and Test (runs on both develop and main but doesn't deploy on main immediately)
Stage 2: Deploy to Dev (only for develop)
Stage 3: Deploy to Staging (only for main with approval)
Stage 4: Deploy to Prod (only for main with approval)
But note: we want the same artifact for staging and prod? Then we must build only once for the commit that is on main and use that same image for staging and prod.
So let's adjust:
We can have:
- On
develop: build, test, and deploy to dev.
- On
main: build, test, and then wait for approval to deploy to staging. Then after staging approval, deploy to prod (using the same artifact).
But what about release branches? We can build on the release branch and then deploy that artifact to staging and prod.
Alternatively, we can use tags to mark releases. Then we build on tag creation and then promote that tag.
Let's design with tags:
- We merge
release/x.y into main and then create a tag vx.y.z (with z being build number or Commit SHA). Then we build the tag and deploy to staging and prod.
But to keep it simple, let's assume we are using main branch for production releases and we want to build once and promote.
Proposed flow:
-
Developer works on feature branch, merges to develop.
-
develop branch triggers:
- Build and test.
- Push Docker image with tag
develop-<commit-sha>.
- Deploy to
dev environment.
-
When ready for release, create a release branch from develop (or merge develop to main and tag). Let's say we merge to main and then tag.
-
On main branch (or on tag creation), we build and test, then:
- Push Docker image with tag
v<version> (from tag) or main-<commit-sha>.
- Then we have two manual approvals: one for staging and one for prod.
-
For each environment (staging and prod), we deploy using the same image tag that was built in step 4.
However, note: if we build on main and then wait for approvals, the artifact might become stale? But we are using the same commit, so it's the same code.
But what if we need to rebuild for a different environment? We don't want that. So we build once and then use that same image.
So we need to store the image tag from the build and then use it for deployment.
How to do that? We can have:
- The build job on
main produces the artifact and records the image tag in a file or as a pipeline variable that is then used by the deployment jobs.
But since the deployment jobs are separate and might be triggered manually, we need to know which image to deploy.
Alternatively, we can have:
- The build on
main also deploys to staging and prod (with approvals in between). Then we don't need to store the image tag because we are in the same pipeline.
However, if we want to promote the same image from staging to prod later (without rebuilding), we need to store the image tag.
Let's consider two approaches:
Approach 1: Single pipeline for release (from build to prod) with approvals in between.
Approach 2: Separate pipelines: one for building (and storing the artifact) and then separate pipelines for promotion that use the stored artifact.
We'll go with Approach 1 for simplicity in the example, but note that in practice you might want to separate build and deployment for security and traceability.
Example pipeline for main branch:
stages:
- build
- test
- deploy_staging (manual)
- deploy_prod (manual, after deploy_staging)
But then the same pipeline would run for every commit on main? That might be too frequent for production.
Alternatively, we only run the pipeline on tags for production? Then:
- On
develop: build and deploy to dev.
- On tag (e.g.,
v1.0.0): build, test, and then deploy to staging (manual) and then to prod (manual).
Let's do:
Branch/Tag Pipeline
develop build -> test -> deploy to dev (auto)
tag (v*) build -> test -> deploy to staging (manual) -> deploy to prod (manual)
But then we are building twice for the same code? Once on develop and once on tag? We don't want that.
So we can:
- Only build on
develop and then when we create a tag, we use the same artifact from develop? But the tag might be on a different commit (if we did hotfixes on main).
Alternatively, we can build only on main (and develop for dev) and then for production we build on tag and then promote.
Given the complexity, let's stick to:
develop branch: builds and deploys to dev (with its own image tag develop-<commit-sha>).
main branch: builds and produces an image with main-<commit-sha>. Then we have a manual step to create a tag? Or we create a tag and then build on tag?
Actually, we want to build the exact code that goes to production, so we should build on the tag.
So:
Step 1: Merge develop to main (without tag) -> we don't build for prod yet.
Step 2: Create a tag v1.0.0 on main -> this triggers the production pipeline.
But then how do we get the code to staging? We want to test the tag in staging before prod.
So:
-
On tag creation (say v1.0.0), we build the image with tag v1.0.0 and then:
Stage 1: Build and test (using the tag)
Stage 2: Deploy to staging (manual approval)
Stage 3: After staging approval, deploy to prod (manual approval)
But then we are building the same code that is on main at the tag point.
However, what about the develop branch? We are building there too, but with a different tag.
So we have two different images: one for dev (from develop) and one for staging/prod (from tag).
This is acceptable because dev and prod are different environments and might have different configurations.
But note: we want to test the same artifact in staging and prod. So we build once (on tag) and then use that same image for staging and prod.
Now, how about hotfixes?
Hotfix: we branch from main (which is the production code) to hotfix/xxx, fix, then merge to main and tag. Then we build the tag and deploy to staging and prod (with approvals). Also merge the hotfix to develop.
So the pipeline for tags is the same.
Let's write an example for a tag pipeline:
We assume the CI/CD tool supports manual approvals and environment variables.
Example using a generic YAML:
We'll have:
.gitlab-ci.yml example (for GitLab CI) or we can write in a generic way.
But note: the question asks for example configs. We can write in a way that is similar to GitLab CI or GitHub Actions.
Let's use GitLab CI as an example because it has built-in environments and manual jobs.
However, to be generic, I'll write a high-level YAML and then note how it might be implemented.
Alternatively, I'll write for GitHub Actions because it's popular.
Let's do GitHub Actions:
We'll have:
- A workflow for
develop branch: build and deploy to dev.
- A workflow for tags: build and then manual deployments to staging and prod.
But note: GitHub Actions doesn't have built-in environment promotion with manual approvals? We can use environment with url and protection rules for approvals.
Alternatively, we can use workflow_run or workflow_call to chain.
Given the complexity, let me outline:
Workflow 1: Develop
on:
push:
branches: [ develop ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- checkout
- build
- test
- build docker image and push to registry with tag: develop-${{ github.sha }}
deploy-dev:
needs: build
runs-on: ubuntu-latest
environment: dev
steps:
- deploy to dev (using the image from build)
Workflow 2: Production (on tag)
on:
push:
tags:
- 'v*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- checkout
- build
- test
- build docker image and push to registry with tag: ${{ github.ref_name }}
deploy-staging:
needs: build
runs-on: ubuntu-latest
environment: staging
# This job will require manual approval if we set the environment to require approval.
steps:
- deploy to staging (using the image from build, with tag ${{ github.ref_name }})
deploy-prod:
needs: deploy-staging
runs-on: ubuntu-latest
environment: production
# This job will require manual approval after deploy-staging is done.
steps:
- deploy to prod (using the same image tag)
However, note: the build job in the tag workflow will build the code at the tag. But what if we want to use the same image for staging and prod? We are using the same tag (the tag name) so that's the same image.
But wait: what if we build in the build job and then in deploy-staging and deploy-prod we use the same tag? Yes, that's the same image.
Now, for rollback:
We can have a separate workflow or job to rollback to a previous image. We would need to know the previous image tag.
How to handle rollback?
Option 1: Keep a record of the last deployed image for each environment. Then have a rollback job that uses that previous image.
Option 2: Use the version control tag: we can rollback by deploying the previous tag.
But note: we might not have a tag for every deployment? We only tag releases.
So for rollback, we might want to use the commit SHA of the previous deployment.
We can store the deployed image tag in a database or in a file in a repository (like a manifest repo) or in the CI/CD tool's environment variables.
Alternatively, in Kubernetes, we can rollback by revising the deployment (which uses the same image tag? Actually, if we change the image tag, we can't rollback by revising because the deployment spec is changed. We need to update the deployment to the previous image tag).
So we need to keep track of the previous image tag.
How about:
- When we deploy, we record the image tag in a file (like
deployments/prod/current or in a config map) and then for rollback we read that and deploy the previous one? But we need to store the previous one too.
Alternatively, we can have a history of deployments in the CI/CD tool (like GitHub Actions doesn't store that by default).
Given the complexity, let's assume we have a way to get the previous image tag (maybe from a parameter or from a stored state).
For simplicity in the example, we'll skip the rollback job and assume we have a manual process or we use the platform's rollback (like kubectl rollout undo).
Now, for blue-green or canary:
We can implement these in the deployment script.
Example for blue-green in Kubernetes:
We have two deployments: app-blue and app-green. We deploy the new version to the inactive one, then switch the service to point to the new one.
But we can also use a single deployment and use the Kubernetes rolling update (which is not exactly blue-green but can be set to have 0 downtime). However, blue-green requires two complete sets.
Alternatively, we can use a service mesh for canary.
Given the complexity of writing the actual deployment script for blue-green, we'll assume we have a script that does:
- For staging and prod, we use a blue-green deployment strategy.
We'll leave the deployment script as a placeholder.
Now, let's write the example for GitHub Actions:
We'll have two workflows: one for develop and one for tags.
But note: we want to build the same artifact for staging and prod? Yes, from the tag.
However, the develop workflow builds a different artifact (develop-). That's okay.
Let's write:
.github/workflows/develop.yml:
name: Develop
on:
push:
branches: [ develop ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build
run: echo "Building..."
- name: Test
run: echo "Testing..."
- name: Build and push Docker image
run: |
docker build -t myapp:develop-github.sha.echo{{ secrets.DOCKER_PASSWORD }} | docker login -u {{ github.sha }}
deploy-dev:
needs: build
runs-on: ubuntu-latest
environment: dev
steps:
- name: Deploy to dev
run: |
echo "Deploying myapp:develop-${{ github.sha }} to dev"
# Use kubectl or other tool to deploy
.github/workflows/release.yml:
name: Release
on:
push:
tags:
- 'v*'
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Build
run: echo "Building..."
- name: Test
run: echo "Testing..."
- name: Build and push Docker image
run: |
docker build -t myapp:github.refname.echo{{ secrets.DOCKER_PASSWORD }} | docker login -u {{ github.ref_name }}
deploy-staging:
needs: build
runs-on: ubuntu-latest
environment: staging
# This environment can be set to require manual approval in GitHub repository settings.
steps:
- name: Deploy to staging
run: |
echo "Deploying myapp:${{ github.ref_name }} to staging"
# Deploy with blue-green or canary strategy
deploy-prod:
needs: deploy-staging
runs-on: ubuntu-latest
environment: production
steps:
- name: Deploy to production
run: |
echo "Deploying myapp:${{ github.ref_name }} to production"
# Deploy with blue-green or canary strategy
Now, for rollback, we can have a separate workflow that is triggered manually and takes the previous image tag as input.
Example:
.github/workflows/rollback.yml:
name: Rollback
on:
workflow_dispatch:
inputs:
environment:
description: 'Environment to rollback (staging or prod)'
required: true
previous_image_tag:
description: 'The image tag to rollback to'
required: true
jobs:
rollback:
runs-on: ubuntu-latest
steps:
- name: Rollback
run: |
echo "Rolling back github.event.inputs.environmenttoimag{{ github.event.inputs.previous_image_tag }}"
# Use the previous_image_tag to deploy
But how do we get the previous_image_tag? We have to store it somewhere.
We can store the current and previous image tags in a file in a separate repository or in a database.
Alternatively, we can use the GitHub API to get the last successful deployment for the environment and then use that image tag? But GitHub Actions doesn't track deployments by image tag.
Given the complexity, we might need a custom solution.
Another idea: when we deploy, we record the image tag in a file in the same repository (like in a deployments directory) and then for rollback we read the previous one.
But then we have to update that file on every deployment, which requires write access to the repository.
Alternatively, we can use the GitHub environment's URL or description to store the current image tag? Not ideal.
Given the scope, we'll leave the rollback as an exercise.
Now, for blue-green deployment in Kubernetes, we might do:
We have two deployments: app-blue and app-green and a service that points to one of them.
Steps for blue-green:
- Determine which one is active (by checking the service selector or by a label).
- Deploy the new version to the inactive deployment (with a new image tag).
- Wait for the new deployment to be ready.
- Switch the service to point to the new deployment (by changing the selector label).
- Optionally, keep the old deployment for a while and then delete it.
We can write a script that does that.
But note: we are using the same image tag for staging and prod? Yes, but we are deploying to different clusters/environments.
So the blue-green script would be environment-specific.
We can have a directory with k8s manifests for each environment and then use kubectl apply with the appropriate context.
Given the complexity, we'll not write the full script here.
In summary, we have:
- Branching: GitFlow with develop and main, and tags for releases.
- Build and test: on develop and on tags.
- Artifacts: Docker images tagged with commit SHA for develop and tag name for release.
- Environments: dev (auto from develop), staging and prod (manual from tag).
- Deployment strategy: blue-green (or canary) for staging and prod.
- Rollback: manual workflow that requires previous image tag.
- Approvals: manual jobs in GitHub Actions for staging and prod (via environment protection rules).
This is a solid starting point.
Let me know if you need more details on a specific part.
I'll design a comprehensive CI/CD pipeline strategy with practical configurations. Here's a complete solution:
1. Branching Strategy (GitFlow with Trunk-Based Elements)
main/master - Production-ready code (protected)
├── release/* - Release branches (from main, merge back to main + develop)
├── develop - Integration branch (optional, can be skipped)
├── feature/* - Feature branches (from develop, PR to develop)
└── hotfix/* - Hotfix branches (from main, PR to main + develop)
Alternative - Trunk-Based with Feature Flags:
main - always deployable
- Short-lived feature branches (1-2 days max)
- Feature flags for incomplete features
- Environment-specific configurations
2. Pipeline Architecture
# Example: GitHub Actions / GitLab CI / Jenkinsfile (generic)
stages:
- validate
- build
- test
- security
- deploy-dev
- deploy-staging
- deploy-prod
- rollback
3. Example Configuration Files
GitHub Actions Workflow (.github/workflows/ci-cd.yml)
name: CI/CD Pipeline
on:
push:
branches: [ main, develop, release/* ]
tags: ['v*']
pull_request:
branches: [ main, develop ]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
# Validate stage
validate:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Lint Code
uses: github/super-linter@v5
env:
DEFAULT_BRANCH: main
VALIDATE_ALL_CODEBASE: false
VALIDATE_JAVASCRIPT_ES: true
VALIDATE_PYTHON_FLAKE8: true
- name: Check Secret Scanning
uses: trufflesecurity/trufflehog@main
with:
path: ./
base: ${{ github.event.pull_request.base.sha }}
head: ${{ github.event.pull_request.head.sha }}
# Build and Test
build-test:
needs: validate
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.9, 3.10]
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Cache dependencies
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install pytest pytest-cov
- name: Run unit tests
run: |
pytest --cov=src --cov-report=xml --junitxml=test-results.xml
- name: Upload test results
uses: actions/upload-artifact@v3
with:
name: test-results-${{ matrix.python-version }}
path: test-results.xml
- name: Build Docker image
run: |
docker build -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }} .
docker build -t ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest .
- name: Push to Registry
if: github.ref == 'refs/heads/main'
run: |
echo ${{ secrets.GITHUB_TOKEN }} | docker login ${{ env.REGISTRY }} -u ${{ github.actor }} --password-stdin
docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
docker push ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
# Security Scanning
security:
needs: build-test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@master
with:
image-ref: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ github.sha }}
format: sarif
output: trivy-results.sarif
- name: Upload Trivy scan results
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: trivy-results.sarif
# Deploy to Dev (auto)
deploy-dev:
needs: [build-test, security]
if: github.ref == 'refs/heads/develop' || github.ref_type == 'tag'
runs-on: ubuntu-latest
environment: development
steps:
- name: Deploy to Dev
run: |
echo "Deploying ${{ github.sha }} to Development"
# kubectl apply -f k8s/dev/
# OR use Helm: helm upgrade --install app ./helm --namespace dev --set image.tag=${{ github.sha }}
- name: Run integration tests
run: |
echo "Running integration tests against Dev"
# pytest tests/integration/ --env=dev
# Deploy to Staging (manual approval)
deploy-staging:
needs: deploy-dev
if: github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
environment:
name: staging
url: https://staging.example.com
steps:
- name: Deploy to Staging (Blue-Green)
run: |
echo "Deploying ${{ github.sha }} to Staging with Blue-Green"
# Blue-Green deployment script
# 1. Deploy to green environment
# 2. Run smoke tests
# 3. Switch traffic
# 4. Keep blue for rollback
- name: Run staging tests
run: |
echo "Running staging validation tests"
# pytest tests/staging/ --env=staging
# Deploy to Production (manual approval)
deploy-prod:
needs: deploy-staging
if: github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
environment:
name: production
url: https://example.com
# Require approval in GitHub repo settings
steps:
- name: Deploy to Production (Canary)
run: |
echo "Deploying ${{ github.sha }} to Production with Canary (10% traffic)"
# Canary deployment:
# 1. Deploy to canary namespace with 10% traffic
# 2. Monitor metrics for 5 minutes
# 3. Gradual rollout if healthy
# 4. Full rollout
- name: Post-deployment validation
run: |
echo "Running production smoke tests"
# pytest tests/prod/smoke/
# Rollback workflow (manual trigger)
rollback:
needs: []
runs-on: ubuntu-latest
if: github.event_name == 'workflow_dispatch'
environment: production
steps:
- uses: actions/checkout@v4
- name: Get previous version
id: previous
run: |
# Fetch previous successful deployment tag
PREVIOUS_TAG=$(git describe --tags --abbrev=0 HEAD^)
echo "previous_tag=$PREVIOUS_TAG" >> $GITHUB_OUTPUT
- name: Rollback to previous version
run: |
echo "Rolling back to ${{ steps.previous.outputs.previous_tag }}"
# kubectl set image deployment/app app=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.previous.outputs.previous_tag }}
# OR helm rollback app 1
4. Environment Promotion Strategy
Promotion Flow:
Dev → Staging → Production
↓
Feature Preview (optional)
Promotion Rules:
- Dev: Auto-deploy from
develop branch or feature branches
- Staging:
- Only from
main or release/* branches
- Requires 2+ approvals
- Must pass all automated tests
- Security scan clean
- Production:
- Only from
main after staging validation
- Requires 4+ approvals (Dev, QA, Sec, Ops)
- Canary deployment mandatory
- Business hours only (configurable)
5. Deployment Strategies
Blue-Green (Staging):
#!/bin/bash
# blue-green-deploy.sh
set -e
APP_NAME="myapp"
NAMESPACE="staging"
NEW_TAG=$1
BLUE="${APP_NAME}-blue"
GREEN="${APP_NAME}-green"
# Determine current active
ACTIVE=$(kubectl get svc ${APP_NAME} -n ${NAMESPACE} -o jsonpath='{.spec.selector.version}')
if [ "$ACTIVE" == "blue" ]; then
TARGET="$GREEN"
INACTIVE="$BLUE"
else
TARGET="$BLUE"
INACTIVE="$GREEN"
fi
# Deploy to inactive
kubectl set image deployment/${TARGET} \
${APP_NAME}=myregistry/${APP_NAME}:${NEW_TAG} \
-n ${NAMESPACE} --record
# Wait for rollout
kubectl rollout status deployment/${TARGET} -n ${NAMESPACE} --timeout=300s
# Switch service
kubectl patch svc ${APP_NAME} -n ${NAMESPACE} -p "{\"spec\":{\"selector\":{\"version\":\"${TARGET##*-}\"}}}"
# Keep inactive for rollback window (30min)
echo "Deployment successful. Inactive: ${INACTIVE} (keep for rollback)"
Canary (Production):
# istio-gateway.yaml for canary traffic splitting
apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
name: app-vs
spec:
hosts:
- app.example.com
http:
- route:
- destination:
host: app
subset: v1
weight: 90 # 90% to stable
- destination:
host: app
subset: v2
weight: 10 # 10% to canary
6. Artifact Management
Artifact Storage:
Registry: Docker Registry / ECR / GCR / ACR
├── myapp:develop-<commit-sha> # Dev builds
├── myapp:release-<version> # Staging builds
├── myapp:v1.2.3 # Production (semver)
└── myapp:latest # Latest stable
Artifact Promotion:
- Never rebuild for different environments
- Use same artifact from Dev → Staging → Prod
- Tag with:
- Git commit SHA for dev
- Release version for prod (semver)
- Build number for traceability
7. Rollback Procedures
Automated Rollback Triggers:
# In deployment script
monitor() {
# Check error rate, latency, etc.
ERROR_RATE=$(kubectl get metrics --query='rate(http_requests_total{status=~"5.."}[5m])')
if (( $(echo "$ERROR_RATE > 0.05" | bc -l) )); then
trigger_rollback
fi
}
trigger_rollback() {
PREVIOUS_TAG=$(get_previous_successful_deployment)
echo "🚨 Auto-rollback to $PREVIOUS_TAG"
# Execute blue-green rollback or kubectl rollout undo
kubectl rollout undo deployment/app -n production
send_alert "Rollback triggered to $PREVIOUS_TAG"
}
Manual Rollback Process:
- Identify bad deployment (
kubectl get rs --sort-by=.metadata.creationTimestamp)
- Get previous image tag from deployment history
- Execute:
kubectl set image deployment/app app=registry/app:previous-tag
- Verify health checks
- Document reason in changelog
8. Approval Gates
Approval Matrix:
| Environment | Required Approvals | Conditions | Time Window |
|---|
| Staging | 2 (Tech Lead + QA) | All tests pass, security scan clean | Any time |
| Production | 4 (Dev, QA, Sec, Ops) | Staging validated 24h, canary successful | Business hours (9-17) |
GitHub Protected Branches:
# .github/branch-protection.yml (via API)
required_pull_request_reviews:
required_approving_review_count: 2
dismiss_stale_reviews: true
require_code_owner_reviews: true
restriction: true
required_status_checks:
contexts:
- validate
- build-test
- security
- deploy-staging
enforce_admins: false
restrictions: null
9. Complete Example: GitLab CI/CD
# .gitlab-ci.yml
variables:
DOCKER_IMAGE: $CI_REGISTRY/$CI_PROJECT_PATH
APP_NAME: myapp
stages:
- validate
- build
- test
- security
- deploy
- production
# Cache Docker layers
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- .docker/
validate:
stage: validate
script:
- echo "Running linters and static analysis"
- npm run lint
- trivy fs --exit-code 1 --severity HIGH,CRITICAL .
build:
stage: build
script:
- docker build -t $DOCKER_IMAGE:$CI_COMMIT_SHORT_SHA .
- docker push $DOCKER_IMAGE:$CI_COMMIT_SHORT_SHA
only:
- merge_requests
- main
- develop
- tags
test:
stage: test
script:
- docker run $DOCKER_IMAGE:$CI_COMMIT_SHORT_SHA npm test
artifacts:
reports:
junit: test-results.xml
deploy:dev:
stage: deploy
script:
- kubectl apply -f k8s/dev/
- ./scripts/health-check.sh dev
environment:
name: development
url: https://dev.example.com
only:
- develop
deploy:staging:
stage: deploy
script:
- ./scripts/blue-green-deploy.sh $CI_COMMIT_SHORT_SHA staging
environment:
name: staging
url: https://staging.example.com
# Manual approval via GitLab environment
on_stop: stop_staging
only:
- main
- tags
when: manual
deploy:production:
stage: production
script:
- ./scripts/canary-deploy.sh $CI_COMMIT_TAG production
environment:
name: production
url: https://example.com
only:
- tags
when: manual
# Rollback job
rollback:production:
stage: production
script:
- ./scripts/rollback.sh production
environment:
name: production
only:
- main
when: manual
# Stop environment (cleanup)
stop_staging:
stage: deploy
script:
- kubectl delete namespace staging || true
when: manual
environment:
name: staging
10. Monitoring & Observability Integration
# Post-deployment monitoring
post-deploy-monitor:
stage: production
script:
- |
# Wait for canary to receive traffic
sleep 300
# Check metrics
ERROR_RATE=$(prometheus query 'sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m]))')
if (( $(echo "$ERROR_RATE > 0.01" | bc -l) )); then
echo "Error rate too high: $ERROR_RATE"
exit 1
fi
# Check latency
P99_LATENCY=$(prometheus query 'histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le)')
if (( $(echo "$P99_LATENCY > 1.0" | bc -l) )); then
echo "Latency too high: ${P99_LATENCY}s"
exit 1
fi
rules:
- if: $CI_COMMIT_TAG
11. Key Best Practices
- Infrastructure as Code: All environments in Git (k8s manifests, Terraform)
- Secret Management: Use vault/HashiCorp Vault or cloud secrets manager
- Immutable Artifacts: Never modify artifacts after build
- Pipeline as Code: Store CI/CD configs in repository
- Complete Traceability: Build number → Git commit → Artifact → Deployment
- Automated Rollbacks: Trigger on health check failures
- Feature Flags: Decouple deployment from release
- Chaos Engineering: Regular failure testing in staging
12. Checklist for Each Deployment
✅ Build reproducibility verified
✅ All tests passing (unit, integration, e2e)
✅ Security scan clean (no critical vulnerabilities)
✅ Performance benchmarks met
✅ Documentation updated
✅ Rollback plan documented
✅ Monitoring alerts configured
✅ Stakeholders notified (for prod)
✅ Post-deployment validation plan ready
This comprehensive pipeline provides:
- Safety through multiple approval gates and automated checks
- Speed with parallel execution and auto-dev deployments
- Reliability with blue-green/canary and automatic rollback
- Traceability from code to production with full audit trail
- Flexibility to adapt to different application types
Would you like me to elaborate on any specific component or provide configurations for a particular tech stack (Kubernetes, serverless, VMs, etc.)?