Module 6: CI/CD — The Complete Guide
Goal
CI/CD is the beating heart of DevOps — the automated pipeline that takes a commit and safely turns it into running software. This module covers GitHub Actions, code quality gates, deployment strategies, rollbacks, Jenkins, Ansible, and the security practices that keep pipelines from becoming attack vectors.
1. What CI/CD Is and Why It Exists
Before CI/CD (the bad old days): developers merge weeks of work at once ("integration hell"), a human FTPs files to a server on Friday evening, something breaks, nobody knows which of the 400 changed files did it, rollback = panic.
- CI — Continuous Integration: every push is automatically built and tested. Broken code is caught in minutes, on a branch, before it hurts anyone.
- CD — Continuous Delivery: every merge to main produces a deployable artifact; releasing is a button press.
- CD — Continuous Deployment: no button — every green merge goes to production automatically.
The end-to-end flow (memorize this shape)
any failure = red PR, no merge
canary/rolling
Small, frequent, boring deployments are safer than big scary ones: less change per deploy = smaller blast radius = trivial rollbacks. Elite teams deploy dozens of times a day precisely because each deploy is tiny.
Analogy
A CI/CD pipeline is a factory assembly line: every commit rides the conveyor belt through a row of inspection stations, and any station that spots a defect lights up red and stops the line before the product reaches the loading dock. The bad old days were building a year's worth of product by hand in one weekend and shipping it all in a single truck — if a customer complains, which of the thousand parts was faulty? Small batches down a well-instrumented line make every defect easy to find and every recall tiny.
2. GitHub Actions — Fundamentals
GitHub Actions runs workflows defined in .github/workflows/*.yml in response to events.
Vocabulary: workflow (the file) → contains jobs (run in parallel on fresh VMs called runners) → each job has steps (commands or reusable actions from the marketplace).
# .github/workflows/ci.yml
name: CI
on:
pull_request: # run on every PR
push:
branches: [main] # and on merges to main
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4 # marketplace action: clone the repo
- uses: actions/setup-python@v5
with: { python-version: "3.12" }
- run: pip install -r requirements.txt
- name: Lint
run: ruff check .
- name: Unit tests
run: pytest --cov=app --cov-fail-under=80Every PR now shows ✔/✘. With branch protection requiring this check, untested code physically cannot reach main. That's CI in one file.
Analogy
The workflow file is the blueprint pinned to the factory wall; each job is a separate workstation that gets a brand-new, spotless workbench (a fresh runner) for every shift; each step is one motion the worker performs at that bench. Branch protection is the quality gate at the end of the line: no green stamp from inspection, and the crate physically cannot leave the floor.
Concepts you'll use constantly
# Secrets — never hardcode credentials; set in repo Settings → Secrets
env:
API_KEY: ${{ secrets.API_KEY }}
# Matrix — test across versions in parallel
strategy:
matrix:
python: ["3.10", "3.11", "3.12"]
# Caching — don't re-download dependencies every run
- uses: actions/cache@v4
with:
path: ~/.cache/pip
key: pip-${{ hashFiles('requirements.txt') }}
# Job dependencies & artifact passing
deploy:
needs: test # runs only if 'test' succeeded
if: github.ref == 'refs/heads/main'Context variables: ${{ github.sha }} (commit hash — perfect image tag), ${{ github.ref_name }} (branch/tag name), ${{ github.actor }} (who triggered).
3. CI Checks — The Quality Gate Stack
A mature pipeline layers cheap-and-fast checks before slow ones (fail fast!):
- Linting (seconds) — style + obvious bugs:
ruff/flake8(Python),eslint(JS),hadolint(Dockerfiles),shellcheck(bash — Module 3!). - Unit tests (seconds–minutes) — with a coverage threshold so untested code trends down, not up.
- Static code quality — SonarQube: analyzes code smells, duplication, complexity, and hotspots. Teams enforce a Quality Gate — e.g., "no new critical issues, coverage on new code ≥ 80%" — and the PR fails otherwise. Real value: it stops quality erosion gradually, on new code, instead of demanding a heroic cleanup.
- Security static analysis (SAST) — CodeQL: GitHub's semantic scanner that finds injectable SQL, path traversal, hardcoded secrets, etc., and annotates the PR:
codeql:
runs-on: ubuntu-latest
permissions: { security-events: write }
steps:
- uses: actions/checkout@v4
- uses: github/codeql-action/init@v3
with: { languages: python }
- uses: github/codeql-action/analyze@v3- Dependency & image scanning:
pip-audit/npm audit/Dependabot for libraries; Trivy for Docker images (trivy image myapp:v2.3.1) — catches vulnerable base images before they ship. - Build + docker build — proves the artifact is producible.
Real-world scenario: a developer opens a PR adding a raw SQL string concatenation. Lint passes, tests pass — CodeQL flags SQL injection and blocks the merge. That's a production breach prevented by YAML.
Analogy
Inspection stations are ordered cheapest first: a ten-second glance for a cracked casing happens before the part ever reaches the expensive X-ray machine. Lint is the glance, tests are the fit check, SonarQube and CodeQL are the X-ray and metallurgy lab — and a red light at any station halts the belt, so a flawed part never wastes the costly stations downstream, let alone reaches a customer.
4. CD with GitHub Actions — Deploying to a VM
The simplest real deployment: SSH to a server, pull the new image, restart. (This is your Module 2+3+5 knowledge composed together.)
# .github/workflows/deploy.yml
name: Deploy
on:
push:
tags: ["v*"] # deploying = pushing a git tag
jobs:
build-push:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: docker/login-action@v3
with:
username: ${{ secrets.DOCKERHUB_USER }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- uses: docker/build-push-action@v6
with:
push: true
tags: myorg/myapp:${{ github.ref_name }}
deploy:
needs: build-push
runs-on: ubuntu-latest
environment: production # gates: required reviewers, env secrets
steps:
- name: Deploy over SSH
uses: appleboy/ssh-action@v1
with:
host: ${{ secrets.PROD_HOST }}
username: deploy
key: ${{ secrets.SSH_PRIVATE_KEY }}
script: |
set -e
docker pull myorg/myapp:${{ github.ref_name }}
docker stop myapp || true && docker rm myapp || true
docker run -d --name myapp --restart unless-stopped \
-p 8080:8080 --env-file /opt/myapp/.env \
myorg/myapp:${{ github.ref_name }}
sleep 5
curl -fsS localhost:8080/healthGitHub Environments add professional guardrails: the production environment can require a human approval click, restrict which branches/tags may deploy, and hold production-only secrets.
Analogy
Deploying is the loading dock at the end of the line: the finished, stamped crate is picked up from the warehouse (the registry) and driven to the store. A protected environment is the shift supervisor standing at the dock door — for the flagship store, no truck leaves without their signature, and only crates from the approved production run are allowed on the trailer.
Rollback strategies (know all three)
- Redeploy previous version — run the same pipeline with the last good tag (
v2.3.0). This is why pinned tags matter: rollback = deploy, nothing special. - Blue/green switch-back — flip the router/symlink back (instant, see §5).
git revert+ roll forward — undo the commit, let the pipeline ship the revert. Cleanest history; slightly slower.
What does NOT work: SSH-ing in and hand-editing files. Now prod differs from Git — configuration drift — and the next deploy stomps your hotfix. Everything goes through the pipeline, always.
Analogy
Rollback is pulling the previous pallet back off the warehouse shelf: because every shipped batch is labeled and kept, swapping v2.3.1 for v2.3.0 is just another routine delivery. Hand-editing production is a mechanic filing down a part after it left the factory — the fix exists on one unit only, the blueprints know nothing about it, and the next batch off the line erases it.
5. Deployment Strategies, Load Balancing, Scaling
Strategies
| Strategy | How | Trade-off |
|---|---|---|
| Recreate | stop old, start new | downtime — dev only |
| Rolling | replace instances one by one behind LB | zero downtime; two versions live briefly |
| Blue/Green | full new environment (green), switch LB, keep blue | instant rollback; double cost during switch |
| Canary | send 5% of traffic to new version, watch metrics, ramp up | safest; needs good monitoring (Module 10) |
Rule of thumb: rolling for routine deploys; canary for risky changes; blue/green when instant rollback is worth the cost.
Analogy
Think of releasing a new product model from the factory. Rolling is restocking shelves one store at a time; blue/green is building a second, fully stocked shop next door and simply moving the entrance sign — if customers hate it, swing the sign back in one second. Canary is putting the new model in front of five percent of shoppers and watching the returns counter before committing the whole chain.
Load balancers & DNS
A load balancer distributes traffic across N app servers and health-checks them — an unhealthy server is pulled out of rotation automatically (this is what makes rolling deploys zero-downtime). Quick nginx LB to build intuition:
upstream app {
server 10.0.11.5:8080;
server 10.0.11.6:8080;
}
server {
listen 80;
location / { proxy_pass http://app; }
}DNS ties it together: myapp.com → A/ALIAS record → load balancer. You point DNS at the LB once; servers behind it churn freely.
Analogy
A load balancer is the greeter at a busy supermarket directing each shopper to an open checkout lane, and quietly roping off any lane whose till has jammed. Shoppers only ever know the store's front door — lanes can open, close, or be replaced all day without a single customer noticing.
Benchmarking & scaling
Before scaling, measure:
ab -n 5000 -c 100 https://staging.myapp.com/ # ApacheBench: 5000 reqs, 100 concurrent
# watch: requests/sec, p95/p99 latency, failed requests(also: wrk, hey, k6 for scripted load tests.)
- Vertical scaling — bigger machine. Simple; has a ceiling; resize = restart.
- Horizontal scaling — more machines behind the LB. Near-limitless; requires the app to be stateless (sessions in Redis, files in S3 — never on local disk).
Real capacity story: ab shows one instance saturates at 300 req/s at 80% CPU. Expected peak: 1000 req/s → run 4–5 instances behind the LB, and set autoscaling on CPU. Numbers, not vibes.
6. Jenkins — The Self-Hosted Workhorse
GitHub Actions is SaaS; Jenkins is the self-hosted CI/CD server you'll meet in most enterprises (banks, telecoms — anywhere code can't leave the building). Same concepts, different engine.
Setup essentials: install (Docker: docker run -p 8080:8080 jenkins/jenkins:lts), unlock with the initial admin password, install plugins — at minimum Git/GitHub (webhooks trigger builds on push) and SSH (deploy over SSH, credentials stored in Jenkins' encrypted credential store, referenced by ID — never plaintext in jobs).
Pipeline as code — the Jenkinsfile
Lives in the repo (versioned, reviewed — same philosophy as workflows):
pipeline {
agent any
environment {
IMAGE = "myorg/myapp:${env.BUILD_NUMBER}"
}
stages {
stage('Test') { steps { sh 'pytest' } }
stage('Build') { steps { sh 'docker build -t $IMAGE .' } }
stage('Push') {
steps {
withCredentials([usernamePassword(credentialsId: 'dockerhub',
usernameVariable: 'U', passwordVariable: 'P')]) {
sh 'echo $P | docker login -u $U --password-stdin && docker push $IMAGE'
}
}
}
stage('Deploy') {
when { branch 'main' }
steps { sshagent(['prod-key']) {
sh 'ssh deploy@prod "docker pull $IMAGE && ./restart.sh $IMAGE"'
}}
}
}
post {
failure {
slackSend channel: '#deploys', color: 'danger',
message: " ${env.JOB_NAME} #${env.BUILD_NUMBER} failed: ${env.BUILD_URL}"
}
success {
slackSend channel: '#deploys', color: 'good',
message: " ${env.JOB_NAME} #${env.BUILD_NUMBER} deployed"
}
}
}The post { failure { ... } } block is your deployment alerting — a failed deploy that nobody notices is how outages last hours. Email/Slack/Teams notifications on failure are non-negotiable in real teams.
Master/Worker (Controller/Agent) architecture
The controller schedules and stores config; agents (workers) execute builds. Why: isolation (builds can't wreck the controller), scale (add agents as teams grow), and specialization (a Linux agent, a Windows agent, a GPU agent — jobs target them with agent { label 'linux-docker' }). Organize the growing job list with Views (folders/tabs per team: "backend", "infra", "nightly").
Analogy
The controller is the plant foreman's office: it holds the schedules and the blueprints but no heavy machinery runs inside it. Agents are the workshops on the floor — a metal shop, a paint shop, a clean room — and each work order is routed to the shop with the right equipment. If a workshop catches fire, the foreman's office and every other shop keep running, and when orders pile up you simply open another shop.
GitHub Actions vs Jenkins: Actions = zero maintenance, tight GitHub integration, pay-per-minute at scale. Jenkins = your servers, your rules, infinite plugins, but you patch and babysit it. Most careers involve both.
7. Ansible — Configuration Management
CI/CD deploys your app — but who configures the servers? Installing Docker, hardening SSH, deploying nginx configs across 50 machines? Doing it by hand doesn't scale and drifts. Ansible automates it:
- Agentless — needs only SSH + Python on targets (which you already have).
- Declarative & idempotent — you describe desired state; running the playbook twice changes nothing the second time. Safe to re-run always.
Inventory — your servers
# inventory.ini
[web]
web1.example.com
web2.example.com
[db]
db1.example.com
[all:vars]
ansible_user=deployPlaybook — desired state as YAML
# site.yml
- name: Configure web servers
hosts: web
become: true # sudo
vars:
app_port: 8080
tasks:
- name: Install packages
apt:
name: [docker.io, nginx]
state: present
update_cache: true
- name: Deploy nginx config from template
template:
src: templates/app.conf.j2 # Jinja2: uses {{ app_port }}, {{ inventory_hostname }}
dest: /etc/nginx/sites-available/app.conf
notify: reload nginx # only fires if the file CHANGED
- name: Ensure services running and enabled
service: { name: "{{ item }}", state: started, enabled: true }
loop: [docker, nginx]
handlers:
- name: reload nginx
service: { name: nginx, state: reloaded }ansible all -i inventory.ini -m ping # ad-hoc: can I reach everyone?
ansible-playbook -i inventory.ini site.yml --check # DRY RUN — see what would change
ansible-playbook -i inventory.ini site.yml # applyKiller features in practice: --check (diff before applying), handlers (restart services only when their config actually changed), templates (one config file, per-host values), roles (reusable bundles — roles/nginx/, roles/docker/ — shareable via Ansible Galaxy), and ansible-vault for encrypting secrets in the repo.
Analogy
A playbook is the safety inspector's checklist for every workshop in the chain: fire extinguisher by the door, exits clear, machine guards fitted. The inspector does not blindly redo everything — they fix only what deviates from the checklist, so walking the same floor twice changes nothing the second time. Handlers are the note at the bottom: only if you had to move the sprinkler, call the plumber.
Where each tool sits (common interview question):
- Terraform (Module 9) creates infrastructure — VMs, networks, load balancers.
- Ansible configures what's on the machines — packages, files, services.
- CI/CD deploys the app — often by running Ansible/Terraform.
Real scenario: security demands a new SSH hardening baseline on 40 servers. Without Ansible: two days of error-prone SSH sessions. With Ansible: edit the role, --check, apply, done in 10 minutes — and every future server gets it automatically.
8. Pipeline Security Best Practices
Pipelines hold the keys to production — attackers know it (SolarWinds was a pipeline compromise). Rules:
- Secrets in secret stores (GitHub Secrets, Jenkins Credentials, Vault) — never in YAML, never in images, never echoed to logs.
- Least privilege: the CI deploy key can deploy one app to one place — it is not an org admin token. Prefer short-lived OIDC credentials (GitHub Actions → AWS role assumption) over long-lived static keys sitting in secrets.
- Pin third-party actions (
uses: some/action@<full-sha>) — a hijacked action tag can exfiltrate your secrets. - Protect the pipeline definition: workflows change through reviewed PRs; forked-PR runs get no secrets (GitHub does this by default — don't disable it).
- Protect main: required checks + required review + no force-push.
- Scan everything: CodeQL (code), Trivy (images), Dependabot (deps), secret-scanning/gitleaks (leaked keys).
- Private network access for developers: DBs and staging live in private subnets (Module 4); humans reach them via VPN/bastion/SSM — never by opening ports to the internet "temporarily."
Analogy
Whoever controls the assembly line controls what goes inside every box that ships — which is why a saboteur targets the factory, not the individual products. So you guard the line like a vault: keys that open only one door, sign-off before any blueprint change, sealed and serial-numbered toolboxes from outside vendors, and a metal detector at every exit checking that no keys leave in a crate.
9. Hands-On Project (Do This) — Your Portfolio Centerpiece
Take your Module 5 app (API + Postgres + Redis) and wrap the full lifecycle around it:
- CI workflow: lint (ruff + hadolint + shellcheck) → pytest with coverage gate → docker build. Enable branch protection requiring it.
- Add CodeQL and a Trivy image scan; introduce a deliberate SQL-injection line and watch CodeQL block the PR, then fix it.
- Add SonarQube (free SonarCloud tier) with a quality gate on new code.
- CD workflow: on tag
v*→ build+push image → SSH-deploy to a VM (EC2 free tier) → curl/health→ Slack webhook notification on success/failure. - Practice rollback: deploy
v0.2.0with a broken health endpoint, watch the pipeline fail, redeployv0.1.0. - Jenkins: run Jenkins in Docker, recreate the same pipeline as a Jenkinsfile with a webhook trigger. Feel the difference between the two tools.
- Ansible: playbook that provisions a fresh Ubuntu VM from zero — deploy user, SSH hardening, Docker install, nginx reverse proxy from template. Run it twice; confirm the second run reports
changed=0(idempotency proven). - Load test with
ab; record req/s before and after adding a second app container behind nginx.
10. Self-Check Questions
- What's the difference between continuous delivery and continuous deployment?
- Why do checks run in order lint → tests → scans → build? What's "fail fast"?
- What does a SonarQube quality gate on new code achieve that a global rule doesn't?
- Name the four deployment strategies and pick one for: routine deploy, risky migration, "we must be able to roll back in 1 second."
- Why is hand-editing files on prod ("hotfixing") harmful even when it works?
- Jenkins controller vs agent — why separate them?
- What makes Ansible idempotent, and why do handlers exist?
- Why pin GitHub Actions to a SHA?
Next → Module 7: Kubernetes
