CI/CD Pipelines
Automate from commit to production. Master GitHub Actions, Docker builds, Helm deployments, ArgoCD GitOps, manual approvals, and safe rollback strategies.
Lesson objective
- What it teaches
- Architecture & How It Works · Core Components · WSL Hands-On Lab · Real-World Project · Troubleshooting · Deep Dive: Enterprise Pipeline Patterns · Predict the Result: When Does a Step Fail?
- Why it matters
- A required lesson for DevOps Engineer, Cloud Engineer, Platform Engineer, DevSecOps Engineer, Release / CI-CD Engineer. Recommended for SRE, DevOps / Platform Architect. See the role paths
- What you demonstrate
-
- Simulated lab: Run the first command shown in the section “WSL Hands-On Lab”. Recorded as lab evidence.
- Predict 3 results this lesson prints. You mark each one yourself.
- Optional, real environment: 5 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
Architecture & How It Works 07.1
Classic CI/CD: Source → Build → Test → Security Scan → Package → Deploy. GitOps adds the continuous reconciliation loop where Git is the single source of truth.
Core Components 07.2
| Platform | Definition File | Core Concepts |
|---|---|---|
| GitHub Actions | .github/workflows/ci.yml | jobs, steps, actions, secrets, matrix, OIDC |
| ArgoCD | Application + ApplicationSet CR | sync, self-heal, waves, generators |
| Jenkins | Jenkinsfile | declarative, stages, agent, when |
| Registry | ECR / GHCR policies | image scanning, lifecycle, signing |
WSL Hands-On Lab 07.3
GitHub Actions + Docker + Helm + ArgoCD on kind
name: Build and Deploy
on: [push]
jobs:
build:
runs-on: ubuntu-latest
permissions: { id-token: write, contents: read }
steps:
- uses: actions/checkout@v4
- uses: docker/setup-buildx-action@v3
- name: Build and push
uses: docker/build-push-action@v5
with:
push: true
tags: ghcr.io/${{ github.repository }}:${{ github.sha }}$ kind create cluster --name gitops $ kubectl create ns argocd $ kubectl apply -n argocd -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml
- Create GitHub Actions workflow: lint → test → docker build → GHCR
- Add Helm upgrade step with image tag from commit SHA
- Run local Jenkins container and create pipeline job
- Install ArgoCD on kind and create first Application
- Practice Killercoda ArgoCD and GitHub Actions scenarios
Real-World Project 07.4
GitHub Actions free tier for Node app
CI only: lint, test, build, push.
Complete: Docker → ECR → EKS via Helm
OIDC auth, matrix strategy, Helm values per environment.
Multi-env ArgoCD + manual gates + Slack + automatic rollback on SLO breach
Troubleshooting 07.5
Workflow not triggering or secrets missing
Check branch filter, repository secrets vs environment secrets, workflow permissions.
ArgoCD OutOfSync or stuck
Inspect Application events tab, resource diffs, and sync options. Use server-side apply for CRDs.
ECR login failures in pipeline
Use OIDC with assume-role or aws-actions/configure-aws-credentials.
30-Day Roadmap 07.6
- Workflow syntax & triggers
- Secrets & variables
- Reusable workflows
- build-push-action
- Build cache
- Trivy scanning step
- Application CR
- Sync policies & waves
- ApplicationSets
- Manual approvals
- Rollback automation
- Notifications + SLO gates
Deep Dive: Enterprise Pipeline Patterns 07.7
Progressive Delivery
Use Argo Rollouts or Flagger for canary/blue-green. Gate promotions behind automated tests + manual approval. Integrate with PagerDuty or Slack for on-call sign-off.
Rollback Strategy
Always keep previous image tag in Git. Use ArgoCD automated rollback or Helm rollback. Trigger rollback automatically when SLO error budget burns too fast.
Declarative Jenkinsfile: Multi-Stage Testing, JUnit & Artifact Retention
While GitHub Actions dominates modern cloud-native projects, self-hosted enterprise infrastructure frequently relies on Jenkins. According to the official Jenkins Declarative Pipeline Syntax and Pipeline Steps Documentation (Jenkins LTS 2.479.1+, Declarative Plugin 2.2218+, JUnit Plugin 1300+), pipelines must enforce timeouts, structured test reporting, artifact finger-printing, and guaranteed workspace hygiene:
pipeline {
agent {
label 'linux-runner'
}
options {
timeout(time: 30, unit: 'MINUTES')
disableConcurrentBuilds()
buildDiscarder(logRotator(numToKeepStr: '10', artifactNumToKeepStr: '5'))
}
environment {
APP_NAME = 'payment-api'
DIST_DIR = 'dist'
}
stages {
stage('Checkout & Dependencies') {
steps {
echo 'Checking out source repository and installing npm packages...'
sh 'npm ci --prefer-offline'
}
}
stage('Unit & Integration Tests') {
options {
timeout(time: 10, unit: 'MINUTES')
}
steps {
echo 'Running test suite with JUnit XML reporter...'
sh 'npm test -- --ci --reporters=default --reporters=jest-junit'
}
post {
always {
junit testResults: 'junit.xml', allowEmptyResults: false
}
}
}
stage('Build Release Artifacts') {
steps {
echo 'Compiling production assets...'
sh 'npm run build'
sh 'tar -czf dist/release-v${BUILD_NUMBER}.tar.gz -C dist assets index.html'
}
}
stage('Retain Build Artifacts') {
steps {
echo 'Archiving built release tarball with cryptographic fingerprinting...'
archiveArtifacts artifacts: 'dist/*.tar.gz', fingerprint: true, allowEmptyArchive: false
}
}
}
post {
always {
echo 'Enforcing workspace cleanup on runner host...'
cleanWs deleteDirs: true
}
success {
echo 'Pipeline passed all stages and archived release artifacts.'
}
failure {
echo 'Pipeline failed. Check JUnit test reports and stage logs.'
}
}
}
Architectural Notes: Declarative syntax strictly separates orchestration from shell execution. Wrapping test stages in post { always { junit ... } } guarantees test reports are ingested even when individual test assertions fail, while global cleanWs prevents storage exhaustion on long-lived runner nodes.
Keyless OIDC Role Assumption & Pinned Trivy Container Security Gate
Storing static cloud access keys (e.g. AWS_ACCESS_KEY_ID) in repository secrets exposes organizations to credential leaks. Under GitHub Actions OIDC Hardening and Trivy Container Scanning Documentation (Trivy v0.58+, trivy-action@0.28.0), workflows request ephemeral cryptographic JWT tokens to assume IAM roles directly via configure-aws-credentials, coupled with a mandatory security fail gate:
name: Secure Build & Deliver
on:
push:
branches: [ main ]
permissions:
id-token: write # Required to request GitHub OIDC JWT token
contents: read # Required for checkout
security-events: write # Required for SARIF upload to GitHub Security tab
jobs:
deliver:
runs-on: ubuntu-24.04
steps:
- name: Checkout Source
uses: actions/checkout@v4.2.2
- name: Assume AWS IAM Role via OIDC
uses: aws-actions/configure-aws-credentials@v4.0.2
with:
role-to-assume: arn:aws:iam::123456789012:role/github-actions-ecr-push
aws-region: us-east-1
audience: sts.amazonaws.com
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3.7.1
- name: Build Container Image Locally
uses: docker/build-push-action@v6.9.0
with:
context: .
load: true
tags: payment-api:${{ github.sha }}
- name: Enforce Trivy Vulnerability Gate (Fail on Critical/High)
uses: aquasecurity/trivy-action@0.28.0
with:
image-ref: 'payment-api:${{ github.sha }}'
format: 'table'
exit-code: '1'
ignore-unfixed: true
vuln-type: 'os,library'
severity: 'CRITICAL,HIGH'
- name: Export Trivy Scan SARIF
uses: aquasecurity/trivy-action@0.28.0
if: always()
with:
image-ref: 'payment-api:${{ github.sha }}'
format: 'sarif'
output: 'trivy-results.sarif'
- name: Upload Scan Results to Security Tab
uses: github/codeql-action/upload-sarif@v3.28.0
if: always()
with:
sarif_file: 'trivy-results.sarif'
Fail-Closed Security Design: With exit-code: '1', any unmitigated CRITICAL or HIGH vulnerability stops pipeline delivery immediately before pushing images to the container registry. The if: always() SARIF export ensures security teams receive audit findings even when the build fails.
Argo Rollouts Canary Delivery & Offline SLO Rollback Simulation
Big-bang deployments risk total site outages. Modern delivery uses progressive canary releases verified by automated metric analysis. According to Argo Rollouts Canary Strategy and AnalysisTemplate Documentation (Kubernetes 1.29+, Argo Rollouts v1.7.2+):
apiVersion: argoproj.io/v1alpha1
kind: Rollout
metadata:
name: payment-api-rollout
namespace: production
spec:
replicas: 5
selector:
matchLabels:
app: payment-api
strategy:
canary:
analysis:
templates:
- templateName: slo-error-rate-analysis
args:
- name: service-name
value: payment-api
steps:
- setWeight: 20
- pause: { duration: 2m }
- setWeight: 50
- pause: { duration: 5m }
template:
metadata:
labels:
app: payment-api
spec:
containers:
- name: payment-api
image: payment-api:v2.4.0
ports:
- containerPort: 8080apiVersion: argoproj.io/v1alpha1
kind: AnalysisTemplate
metadata:
name: slo-error-rate-analysis
namespace: production
spec:
args:
- name: service-name
metrics:
- name: success-rate-slo
interval: 30s
failureLimit: 1
successCondition: result[0] < 0.01
provider:
prometheus:
address: http://prometheus.monitoring.svc.cluster.local:9090
query: |
sum(rate(http_requests_total{job="{{args.service-name}}",status=~"5.*"}[2m]))
/
sum(rate(http_requests_total{job="{{args.service-name}}"}[2m]))Simulated Offline SLO Rollback Drill: The following executable Node.js script simulates metric evaluations across healthy and failing canary deployments, proving that error rate spikes (≥ 1.0%) trigger immediate automated rollback signals. (Simulated offline exercise, not a live cluster rollback; simulated results are labeled and live-run limitations remain in curriculum gaps; live execution requires a running Kubernetes cluster with the Argo Rollouts controller and Prometheus metrics scraper).
// Deterministic SLO Error Rate Evaluator & Rollback Decider
// Threshold: Maximum 1.0% (0.01) 5xx error rate allowed during canary step
export function evaluateSlo(metrics) {
if (!metrics || typeof metrics.totalRequests !== 'number' || typeof metrics.errorRequests !== 'number' || metrics.totalRequests <= 0 || metrics.errorRequests < 0) {
return { status: 'BREACH', rollback: true, errorRate: 1.0, message: 'Invalid or zero traffic telemetry: fail closed' };
}
const errorRate = metrics.errorRequests / metrics.totalRequests;
if (errorRate >= 0.01) {
return { status: 'BREACH', rollback: true, errorRate, message: 'Error rate ' + (errorRate * 100).toFixed(2) + '% exceeds 1.0% SLO threshold; rollback triggered' };
}
return { status: 'PASS', rollback: false, errorRate, message: 'Error rate ' + (errorRate * 100).toFixed(2) + '% is healthy; canary step promoted' };
}
// Simulated Demonstration
const baseline = { totalRequests: 10000, errorRequests: 2 };
console.log('Baseline Check:', evaluateSlo(baseline));
const badDeploy = { totalRequests: 10000, errorRequests: 480 };
console.log('Bad Deploy Check:', evaluateSlo(badDeploy));Predict the Result: When Does a Step Fail? 07.8
Recorded from a real run of scripts/recordings/cicd.sh; every output below is pasted from scripts/recordings/cicd.out. Cover the output, predict it, then compare.
Environment: Ubuntu 24.04 container with GNU bash 5.2.21, the shell GitHub-hosted Ubuntu runners use for run: steps. A CI step passes or fails on the exit code of its shell.
# A failing build piped into tee $ bash -c 'false | tee build.log; echo "exit=$?"' exit=0 # The same pipeline with pipefail $ bash -o pipefail -c 'false | tee build.log; echo "exit=$?"' exit=1 # set -e, but the failure is part of an || list $ bash -e -c 'false || true; echo still-running' still-running # set -e and a plain failing command; what does the runner see? $ bash -e -c 'false; echo never-printed'; echo "step exit=$?" step exit=1
Without pipefail a pipeline returns the status of its last command, so false | tee passes and a broken build ships. set -e ignores failures inside || and && lists. Start shell steps with set -euo pipefail.