DELIVERY, DEPLOYMENT
& OPERATIONS
Table of Contents
Strategies
Picking up from Delivery, where the approval gate opened — we now choose how the new version meets real traffic.
01 / Five Shapes
| Strategy | Downtime | Rollback |
|---|---|---|
| Recreate | Yes | Slow (redeploy) |
| Rolling | No | Gradual |
| Blue/Green | No | Instant flip-back |
| Canary | No | Fast drain |
| Feature Flags | No | Instant toggle |
Mechanics
02 / How Each Moves Traffic
03 / Failure Modes
- Rolling without probes → bad version reaches 100% "successfully".
- Blue/Green sharing mutable state → Green writes what Blue can't read; keep schemas backward-compatible.
- Canary without version labels → blended metrics lie.
- Flag sprawl → untestable combinations; every flag gets an owner + expiry.
Check & Handoff
04 / Interview Check
Rolling replaces capacity; canary tests a hypothesis on a subset with explicit success criteria.
Traffic shapes can't fix data: migrations must be expand-contract and backward-compatible first.
05 / Handoff
Strategy chosen — but canary is blind without signals. Continue in Observability & Feedback, whose golden signals gate every progressive rollout.
Part 1: Continuous Delivery
Part 1: Continuous Delivery
Continuous Delivery: every change that passes CI is releasable — deployment to staging is automatic, to production is a decision (approval). Continuous Deployment removes even that gate.
1. What Is It?
Picking up from Artifact Management, where the digest was frozen — we now move that exact artifact through staging to production.
- Continuous Delivery: pipeline auto-deploys to staging; production needs an approval/policy gate.
- Continuous Deployment: pipeline auto-deploys to production too.
- Environment: a runtime context — staging (prod-like rehearsal) vs production (real users).
- Release: a version made available; Deployment: installing it somewhere; Promotion: approving the same artifact for the next environment.
Delivery vs Deployment
One gate of difference:
| Continuous Delivery | Continuous Deployment | |
|---|---|---|
| After CI passes | Releasable, auto-staged | Shipped to production |
| Production deploy | A human/policy decision | Automatic |
| Motto | "We could ship anytime" | "We do ship every time" |
| Risk control | Approval gate | Progressive delivery + fast rollback |
2. Why Does It Exist?
Part 1: Continuous Delivery · continued
Merging is not shipping. Delivery closes the gap: staging proves the artifact in prod-like conditions, approvals control risk, and releases become routine instead of events.
3. Where Does It Fit?
flowchart LR
R[Registry: app:sha-9f3a] --> S[Staging<br/>auto + smoke tests]
S --> G{Approval}
G -->|approved| P[Production]
G -->|rejected| F[Feedback → fix]4. How It Works
- Post-merge pipeline pushes artifact; CD auto-deploys its digest to staging.
- Automated smoke tests + (optional) manual QA run in staging.
- Approval gate: human click, or policy gate that auto-approves when all checks are green, the deploy lands inside the allowed time window (change window — e.g. business hours, never Friday night), and the code owner has signed off.
- CD deploys the same digest to production using per-environment config (env vars, secrets, scaling).
- Post-deploy verification (health checks, error budget — the allowable failure quota; if it burns too fast, releases halt) confirms success.
5. Example
Helm (the package manager for Kubernetes) installs the chart with the tested image tag — same digest, environment-specific values:
## Part 1: Conceptual CD flow (platform syntax varies)
deploy-staging:
environment: staging # auto on main
script: helm upgrade app ./chart --set image.tag=$SHA
deploy-production:
environment: production # manual approval gate
needs: [deploy-staging, smoke-tests]
when: manual
script: helm upgrade app ./chart --set image.tag=$SHA6. Staging vs Production
6. Staging vs Production
| Staging | Production | |
|---|---|---|
| Purpose | Rehearse, catch env issues | Serve users |
| Data | Sanitized/anonymized | Real |
| Deploys | Automatic | Gated |
| Scale | Smaller but representative | Full |
7. Failure Modes
- Config drift (staging ≠ prod) → env-specific bugs; fix with same chart/manifests, env-only values.
- Approval bottleneck (every typo needs a manager); fix with policy gates for low-risk paths.
- Deploying a rebuild instead of the tested digest; fix by pinning digests end-to-end.
8. Best Practices
- Same artifact digest from staging to production, always.
- Separate config from code (env vars/secrets per environment).
- Small batches + feature flags (toggles switching code paths at runtime without redeploying) so approvals stay fast and safe.
- Every production deploy must be observable and reversible (see next doc).
9. Common Misconceptions
- "Delivery = Deployment." Delivery keeps the decision; Deployment automates it.
- "Staging guarantees prod success." It reduces risk; traffic, data, and scale still differ — hence deployment strategies (canary, blue-green).
10. Interview / Exam Notes
- Delivery vs Deployment in one sentence each.
- Design an approval gate: who/what approves, on what signal.
- Why staging must mirror production's topology but never its data.
6. Staging vs Production · continued
The release is live — now it must be watched. Continue in Observability & Feedback, where production signals close the loop back to the developer.
Related Topics
- Artifact Management
- Observability & Feedback
Part 2: Continuous Deployment
Continuous Deployment removes the last human gate: every change passing all automated checks reaches production by itself. Freedom bought with automation rigor most teams haven't built yet.
1. What Is It?
Picking up from Continuous Delivery, where a human approved production — here the pipeline approves itself. Delivery asks "could we ship?"; Deployment ships.
2. Prerequisites (All Non-Negotiable)
- Full automation: build, test, scan, staging deploy, smoke, promotion — zero manual steps. Any human errand becomes the bottleneck that breaks the model.
- Progressive delivery: canary or flags on every release (see Deployment Strategies) — automation needs a small blast radius to be safe.
- Kill criteria: automated halt conditions (error-budget burn, p99 regression, business KPI drop) that stop and roll back without asking.
- Observability: version-labeled everything, SLOs with burn alerts, on-call that trusts the automation (see Observability).
- Trunk discipline + flags: unfinished work hides behind flags; branches live hours-to-days, never weeks — main is always shippable.
3. Failure Modes
3. Failure Modes
- Automating a flaky pipeline → auto-shipping bugs at machine speed; fix gates first, automate second.
- No kill criteria → bad release reaches 100% "successfully"; every auto-promotion needs an automated halt.
- Database migrations without expand-contract → auto-deploy corrupts state; migrations must be backward-compatible across versions.
- On-call distrusts automation → humans re-add manual gates; fix with practiced, boring rollbacks that build confidence.
4. Delivery vs Deployment: When Each
- Delivery (human gate): regulated industries, data migrations, marketing-coordinated launches, teams still building gate maturity.
- Deployment (no gate): SaaS with progressive delivery, strong SLOs, practiced rollback, and trunk discipline. Start with low-risk services, expand the blast radius as confidence compounds.
5. Interview Notes
- Five prerequisites from memory, and how to verify each exists.
- Why automating a bad pipeline multiplies harm.
- Expand-contract migrations: why they're the price of auto-deploy.
Related Topics
- Continuous Delivery
- Deployment Strategies
- Observability & Feedback
Auto-shipping needs somewhere to land safely. Continue in Environments & Release.
3. Failure Modes · continued
Part 3: Environments & Release
Environments are runtime contexts with different data, scale, and risk; release is the discipline of moving one artifact across them safely — same binary, different config, explicit promotion paths.
1. What Is It?
Picking up from Continuous Deployment, where automation needed safe landing zones — here is how those zones are built and governed.
2. Environment Topology
| Env | Purpose | Data | Deploys |
|---|---|---|---|
| Dev | Individual velocity | Fake/local | Continuous, anything |
| Preview (per-PR) | Review the actual change | Sanitized snapshot | Auto per PR, destroyed on merge |
| Staging | Prod rehearsal | Sanitized/anonymized prod-like | Auto on main |
| Production | Real users | Real | Gated (delivery) or automated (deployment) |
Preview environments are the highest-leverage addition: reviewers click the change instead of imagining it.
3. Config vs Code
The artifact never changes between environments; everything else does via config: env vars for simple values, secret stores for credentials, config maps/files for structured settings. Inject each setting at the latest safe point — build-time injection forces per-environment artifacts and voids test-what-you-ship; deploy- or runtime injection keeps one binary everywhere. Twelve-factor discipline: a diff between staging and production behavior must be explainable by config diff alone — never by "we built it differently."
4. Release Trains & Promotion Paths
4. Release Trains & Promotion Paths
- Release train: scheduled departures (e.g. Tuesdays/Thursdays); whatever is green and approved rides, the rest waits for the next train. Predictable for stakeholders, calming for on-call.
- Promotion path: dev → preview → staging → production, each gate explicit (checks + approvals + signals). Skipping environments is the process smell that precedes incidents.
- Hotfix lane: a documented fast path (fewer approvals, same checks) for production fires — used rarely, reviewed always.
- Release readiness checklist: owners named, config externalized, environments IaC-built, approvals + monitors + data migration + back-out plan + support handoff. No checklist, no release.
5. Failure Modes
- Snowflake environments (hand-configured staging) → "works in staging" lies; environments are code (IaC), rebuilt identically.
- Real prod data in staging → breach waiting to happen; sanitize/anonymize with production-like shape.
- Config in code (URLs baked into images) → rebuild per env, voiding artifact immutability; externalize everything.
6. Interview Notes
- Why preview environments beat screenshots for review quality.
- Config-vs-code: what breaks when the artifact differs per env.
- Design a hotfix lane that stays safe under pressure.
Related Topics
- Continuous Delivery
- Continuous Deployment
- Deployment Strategies
Zones built and governed — now lock down the supply chain running through them. Continue in CI/CD Security.
4. Release Trains & Promotion Paths · continued
Part 4: IaC for Environments
Environments are too important to be clicked into existence: Terraform (or equivalent) declares every environment's infrastructure so staging and production differ only by config — never by history.
1. What Is It?
Picking up from ArgoCD & GitOps, where app state became declarative — IaC does the same for everything underneath: VPCs, clusters, databases, DNS, IAM. Same modules, different inputs per environment.
2. Structure That Scales
envs/
├── modules/ # vpc, cluster, db — written once
├── dev/ # small sizes, short retention
├── staging/ # prod-shaped, sanitized data
└── prod/ # real sizes, real data, approvals- State per environment (never shared): one blast radius per state file; remote backend with locking.
- Modules pinned by version — floating module sources are
:latestwith extra steps. - Env diff = input diff: instance sizes, counts, secrets references. A behavioral difference not explainable by inputs is a bug.
3. IaC in the Pipeline
terraform planon every PR touchingenvs/— the plan is the review.applygated like any production deployment (approvals on prod, auto on dev).- Drift detection on schedule:
plannightly, alert on unexpected diffs — the IaC equivalent of ArgoCD's self-heal. - Jenkins controller itself can be code too (JCasC — see Jenkins Advanced).
4. Preview Environments, Automated
4. Preview Environments, Automated
Combine the pieces: PR → pipeline runs a Terraform workspace (or ArgoCD ApplicationSet) → ephemeral env with sanitized data → destroy on merge. The highest-leverage environment pattern, fully automated, zero snowflakes.
5. Failure Modes
- Shared state across envs → dev
applydeletes prod tables; separate states, separate credentials. - Unreviewed
applyon prod → treat IaC changes like code: PR, plan output, approval. - Secrets in state files → state holds secrets in plaintext; encrypt backends, restrict access, prefer external secret stores.
- ClickOps drift → someone "fixes" prod in the console; drift alerts + periodic
applyreconciliation.
6. Interview Notes
- Why state-per-environment (blast radius).
- Plan-as-review: what makes IaC changes safe to approve.
- Where JCasC fits (controller config as code, same discipline).
Related Topics
- Environments & Release
- ArgoCD & GitOps
- Jenkins Advanced
Infrastructure declared — the library's platform arc is complete. Return to the Topic Index.
Continuous Deployment
Continuous Deployment removes the last human gate: every change passing all automated checks reaches production by itself. Freedom bought with automation rigor most teams haven't built yet.
1. What Is It?
Picking up from Continuous Delivery, where a human approved production — here the pipeline approves itself. Delivery asks "could we ship?"; Deployment ships.
2. Prerequisites (All Non-Negotiable)
- Full automation: build, test, scan, staging deploy, smoke, promotion — zero manual steps. Any human errand becomes the bottleneck that breaks the model.
- Progressive delivery: canary or flags on every release (see Deployment Strategies) — automation needs a small blast radius to be safe.
- Kill criteria: automated halt conditions (error-budget burn, p99 regression, business KPI drop) that stop and roll back without asking.
- Observability: version-labeled everything, SLOs with burn alerts, on-call that trusts the automation (see Observability).
- Trunk discipline + flags: unfinished work hides behind flags; branches live hours-to-days, never weeks — main is always shippable.
3. Failure Modes
- Automating a flaky pipeline → auto-shipping bugs at machine speed; fix gates first, automate second.
- No kill criteria → bad release reaches 100% "successfully"; every auto-promotion needs an automated halt.
- Database migrations without expand-contract → auto-deploy corrupts state; migrations must be backward-compatible across versions.
- On-call distrusts automation → humans re-add manual gates; fix with practiced, boring rollbacks that build confidence.
4. Delivery vs Deployment: When Each
- Delivery (human gate): regulated industries, data migrations, marketing-coordinated launches, teams still building gate maturity.
- Deployment (no gate): SaaS with progressive delivery, strong SLOs, practiced rollback, and trunk discipline. Start with low-risk services, expand the blast radius as confidence compounds.
5. Interview Notes
- Five prerequisites from memory, and how to verify each exists.
- Why automating a bad pipeline multiplies harm.
- Expand-contract migrations: why they're the price of auto-deploy.
Related Topics
- Continuous Delivery
- Deployment Strategies
- Observability & Feedback
Auto-shipping needs somewhere to land safely. Continue in Environments & Release.
Environments & Release
Environments are runtime contexts with different data, scale, and risk; release is the discipline of moving one artifact across them safely — same binary, different config, explicit promotion paths.
1. What Is It?
Picking up from Continuous Deployment, where automation needed safe landing zones — here is how those zones are built and governed.
2. Environment Topology
| Env | Purpose | Data | Deploys |
|---|---|---|---|
| Dev | Individual velocity | Fake/local | Continuous, anything |
| Preview (per-PR) | Review the actual change | Sanitized snapshot | Auto per PR, destroyed on merge |
| Staging | Prod rehearsal | Sanitized/anonymized prod-like | Auto on main |
| Production | Real users | Real | Gated (delivery) or automated (deployment) |
Preview environments are the highest-leverage addition: reviewers click the change instead of imagining it.
3. Config vs Code
The artifact never changes between environments; everything else does via config: env vars for simple values, secret stores for credentials, config maps/files for structured settings. Inject each setting at the latest safe point — build-time injection forces per-environment artifacts and voids test-what-you-ship; deploy- or runtime injection keeps one binary everywhere. Twelve-factor discipline: a diff between staging and production behavior must be explainable by config diff alone — never by "we built it differently."
4. Release Trains & Promotion Paths
Environments & Release · continued
- Release train: scheduled departures (e.g. Tuesdays/Thursdays); whatever is green and approved rides, the rest waits for the next train. Predictable for stakeholders, calming for on-call.
- Promotion path: dev → preview → staging → production, each gate explicit (checks + approvals + signals). Skipping environments is the process smell that precedes incidents.
- Hotfix lane: a documented fast path (fewer approvals, same checks) for production fires — used rarely, reviewed always.
- Release readiness checklist: owners named, config externalized, environments IaC-built, approvals + monitors + data migration + back-out plan + support handoff. No checklist, no release.
5. Failure Modes
- Snowflake environments (hand-configured staging) → "works in staging" lies; environments are code (IaC), rebuilt identically.
- Real prod data in staging → breach waiting to happen; sanitize/anonymize with production-like shape.
- Config in code (URLs baked into images) → rebuild per env, voiding artifact immutability; externalize everything.
6. Interview Notes
- Why preview environments beat screenshots for review quality.
- Config-vs-code: what breaks when the artifact differs per env.
- Design a hotfix lane that stays safe under pressure.
Related Topics
- Continuous Delivery
- Continuous Deployment
- Deployment Strategies
Zones built and governed — now lock down the supply chain running through them. Continue in CI/CD Security.
IaC for Environments
Environments are too important to be clicked into existence: Terraform (or equivalent) declares every environment's infrastructure so staging and production differ only by config — never by history.
1. What Is It?
Picking up from ArgoCD & GitOps, where app state became declarative — IaC does the same for everything underneath: VPCs, clusters, databases, DNS, IAM. Same modules, different inputs per environment.
2. Structure That Scales
envs/
├── modules/ # vpc, cluster, db — written once
├── dev/ # small sizes, short retention
├── staging/ # prod-shaped, sanitized data
└── prod/ # real sizes, real data, approvals- State per environment (never shared): one blast radius per state file; remote backend with locking.
- Modules pinned by version — floating module sources are
:latestwith extra steps. - Env diff = input diff: instance sizes, counts, secrets references. A behavioral difference not explainable by inputs is a bug.
3. IaC in the Pipeline
terraform planon every PR touchingenvs/— the plan is the review.applygated like any production deployment (approvals on prod, auto on dev).- Drift detection on schedule:
plannightly, alert on unexpected diffs — the IaC equivalent of ArgoCD's self-heal. - Jenkins controller itself can be code too (JCasC — see Jenkins Advanced).
4. Preview Environments, Automated
IaC for Environments · continued
Combine the pieces: PR → pipeline runs a Terraform workspace (or ArgoCD ApplicationSet) → ephemeral env with sanitized data → destroy on merge. The highest-leverage environment pattern, fully automated, zero snowflakes.
5. Failure Modes
- Shared state across envs → dev
applydeletes prod tables; separate states, separate credentials. - Unreviewed
applyon prod → treat IaC changes like code: PR, plan output, approval. - Secrets in state files → state holds secrets in plaintext; encrypt backends, restrict access, prefer external secret stores.
- ClickOps drift → someone "fixes" prod in the console; drift alerts + periodic
applyreconciliation.
6. Interview Notes
- Why state-per-environment (blast radius).
- Plan-as-review: what makes IaC changes safe to approve.
- Where JCasC fits (controller config as code, same discipline).
Related Topics
- Environments & Release
- ArgoCD & GitOps
- Jenkins Advanced
Infrastructure declared — the library's platform arc is complete. Return to the Topic Index.
Part 1: Observability & Feedback
Part 1: Observability & Feedback
Observability (logs, metrics, traces) reveals what a deployment actually did; feedback routes that signal back to the developer so the loop — commit → production → learning — closes.
1. What Is It?
Picking up from Continuous Delivery, where the digest reached production — we now watch what it does there and feed the lessons back.
- Observability: logs (events), metrics (numbers over time), traces (request paths) answering "what is production doing?"
- Feedback: every signal returned to the author: PR check results, staging smoke verdicts, prod alerts, DORA trends (DORA = DevOps Research & Assessment; its four delivery signals are listed in Section 7).
2. Why Does It Exist?
Without feedback, deployment is a cliff — code leaves the pipeline and nobody learns. The loop deploy → observe → learn → fix is what makes CI/CD self-improving instead of merely automated.
3. Where Does It Fit?
flowchart LR
P[Production] --> O[Observability<br/>logs · metrics · traces]
O --> F[Feedback]
F --> D[Developer]
D --> G[Git → next fix]Part 1: Observability & Feedback · continued
| Signal | Consumer | Action |
|---|---|---|
| PR checks | Developer | Fix before merge |
| Staging smoke | Team | Block promotion |
| Error-rate/latency alert | On-call | Roll back or forward-fix |
| Deploy frequency, MTTR (mean time to recovery) trends | Leads | Improve pipeline |
4. How It Works
- Every deploy is labeled (version/SHA) so logs/metrics correlate with the change.
- Dashboards track golden signals — the four user-visible health metrics: latency, traffic, errors, saturation — plus business KPIs.
- Alerts fire on symptom (error budget burn — failures consuming the allowed quota too fast; p99 spike — the slowest 1% of requests degrading), not on every deploy.
- Incident → revert or forward-fix → postmortem feeds back into pipeline gates (new test, new scan, tighter approval).
5. Example
v1.4.2 deploys to production (SHA-labeled)
→ error rate 0.2% → 3.1% in 10 min (alert fires)
→ on-call rolls back to v1.4.1 (4 min, MTTR clock stops)
→ postmortem: missing integration test for null avatar
→ new test added to PR pipeline so the class of bug can't recur6. Failure Modes
- Alert fatigue (noisy thresholds) → alerts ignored; fix with SLO-based alerts (SLO = Service Level Objective, e.g. 99.9% successful requests; alert when the error budget burns, not on every blip).
- Unlabeled deploys (can't tell which version broke prod); fix with version annotations everywhere.
- Postmortems without pipeline changes → repeat incidents; every action item should land as a test, check, or runbook.
SLI / SLO / Alerting
- SLI (indicator): what you measure — success ratio, p99 latency. SLO (objective): the promise — 99.9% success over 30 days. Error budget: 100% − SLO; the failures you're allowed.
- Alert on budget burn rate, not raw errors: fast burn (2% budget/hour) pages a human; slow burn (week-long drift) files a ticket. Every alert names its runbook.
- Keep SLOs few (3–5 per service); each SLO without an owner and a consequence is decoration.
7. Best Practices
7. Best Practices
- Standardize structured logs (machine-parseable
key=valuelines, not free text) + trace IDs (one ID following a single request across every service it touches) + version labels from day one. - Track the four DORA signals: deploy frequency, lead time, change-fail rate, MTTR.
- Make feedback fast: PR results in minutes, prod anomalies in minutes, trends weekly.
DORA Metrics (What Good Looks Like)
| Signal | Elite hint | Moves it |
|---|---|---|
| Deploy frequency | On demand, multiple/day | Small batches, trunk discipline, fast PR pipeline |
| Lead time (commit→prod) | < 1 day | Same, plus approval automation |
| Change-fail rate | < 15% | Better PR gates, canary, flags |
| MTTR | < 1 hour | Version labels, practiced rollback, clear on-call |
Measure monthly, review with leads, improve one signal at a time. DORA classifies; it doesn't fix — the pipeline changes in Section 4 do.
8. Interview / Exam Notes
- Logs vs metrics vs traces, one use each.
- Design the rollback decision: which signal, who decides, how fast.
- How a production incident improves the CI pipeline (concrete example above).
The loop is closed conceptually — now see it implemented. Continue in the Jenkins Domain, where these generic concepts become controllers, agents, and Jenkinsfiles.
Related Topics
- CI/CD Overview
- Continuous Delivery
- CI/CD Pipelines
7. Best Practices · continued
Part 2: Rollback & Recovery
Rollback is a feature, not an apology: a practiced, boring path from bad production back to good — decided by signals, executed in minutes, reviewed afterward.
1. What Is It?
Picking up from CI/CD Security, where defenses were hardened — defenses still fail, so recovery must be engineered with the same rigor as release.
2. Rollback per Strategy
| Strategy | Rollback move | Time |
|---|---|---|
| Rolling | Roll back batch by batch (or rollout undo) | Minutes |
| Blue/Green | Flip router back to Blue | Seconds |
| Canary | Drain canary, 100% to stable | Seconds–minutes |
| Feature flag | Toggle off | Instant |
| Recreate | Redeploy previous digest | Slowest — avoid where recovery matters |
Rollback deploys a previous known-good digest (Artifact Management) — never a fresh build. Fresh builds during incidents add untested variables to a fire.
3. Rollback vs Forward-Fix Decision
- Rollback when: cause unknown, blast radius growing, error budget burning fast, or the fix is uncertain. Default for Sev1.
- Forward-fix when: cause known, fix tiny and verified, rollback itself risky (migrations already applied — data can't "roll back," only migrate forward).
- Decider: on-call with pre-agreed thresholds, not a committee. Decide in minutes; review in the postmortem.
4. Recovery Drills (MTTR Practice)
4. Recovery Drills (MTTR Practice)
- Game days: inject failure in staging (kill pods, expire certs, break the pipeline), time the recovery, fix the gaps found.
- Rollback rehearsal: each service rolls back on staging quarterly until MTTR is measured, not guessed.
- Jenkins/server recovery: restore
JENKINS_HOMEbackup to fresh infra, replay smoke pipeline (see Jenkins Advanced).
5. Postmortems That Prevent Recurrence
Blameless, owner-assigned, pipeline-linked: every action item becomes a test, check, alert, or runbook — or it will recur. Track repeat-incident rate; a postmortem without a merged pipeline change is a diary entry.
6. Data Migration Practice
Data outlives code and can't be discarded on deploy — migrations move forward, never back:
- Version every migration: ordered, reversible scripts run by a migration runner (not hand-applied SQL); each deploy maps to exact schema versions.
- Expand-contract sequencing: add (nullable) → migrate data → enforce; ship app code compatible with both schemas before migrating.
- Risky upgrades: deploy dual-compatible app on the old schema, observe, back up, migrate, then ship schema-dependent code.
- Verify restore, not just backup: rehearse production migration and rollback paths on staging with production-scale data.
- Test data: construct minimal data per test; never depend on full production dumps (slow, privacy-risky, unreproducible).
7. Failure Modes
- No practiced rollback → improvisation during incidents; rehearse until boring.
- Rolling forward into a migration → data corruption; expand-contract migrations make both directions safe.
- Rollback untested because "we never need it" → the one time it's needed, it doesn't work. Test the path you pray you never take.
4. Recovery Drills (MTTR Practice) · continued
8. Interview Notes
- Rollback vs forward-fix: decision criteria in 60 seconds.
- Why rollback uses old digests, never fresh builds.
- Design a game day for a canary-deployed service.
- Rollback vs forward-fix after a migration already applied.
Related Topics
- Deployment Strategies
- Artifact Management
- Observability & Feedback
- Jenkins Advanced
Recovery engineered — the library's concept arc is complete. Return to the Topic Index for labs and reference.
Part 3: CI/CD Security
The pipeline is production infrastructure with production secrets and the power to ship code — attack it like one: least privilege, signed artifacts, verified supply chain.
1. What Is It?
Picking up from Environments & Release, whose zones carry real credentials — the pipeline itself is the highest-value target in the estate: it holds deploy keys, signs releases, and runs attacker-influenced PR code.
2. Secrets Discipline
2. Secrets Discipline
- Store in managers (Vault, cloud KMS, Jenkins credentials store, GitHub environments) — never in repos, images, logs, or chat.
- Scope narrowly (per-env, per-job), rotate on schedule and on any leak, audit every access.
- PR builds from forks get zero production secrets — credential-free sandboxes only (see Jenkins Agents trust boundary).
3. Signing, SBOM & Provenance
Build once, then: sign the digest (cosign), generate the SBOM (Syft/Trivy), attest provenance (SLSA: who built, from which commit, in which pipeline). Deploy policies admit only signed, attested images — see Artifact Management. When the next CVE lands, query SBOMs to find affected digests in minutes.
4. Least Privilege Everywhere
- CI tokens: per-repo, minimal scopes, short TTL (OIDC federation beats long-lived keys — workloads mint credentials, nobody stores them).
- Pipeline permissions:
GITHUB_TOKENminimal scopes; Jenkins agents can't read other jobs' secrets (agent→controller deny). - Humans: matrix authorization, SSO + MFA, no shared admin accounts, no standing prod access without review.
5. Supply-Chain Gates
Pin everything: action SHAs (not @v4 tags), base image digests (not :latest), plugin versions, lockfiles. Verify checksums on download. Each PR that bumps a dependency re-runs the full gate — Dependabot PRs are untrusted code until proven otherwise.
6. Governance & Change Evidence
2. Secrets Discipline · continued
Regulated or not, every team answers "who shipped what, approved by whom, proven how" — the pipeline is the evidence:
- Maturity ladder: manual releases → versioned + automated → gated + attested → measured + continuously improved. Assess per area, fix the most painful gap first.
- Pipeline as audit trail: every production change maps to a commit, a built digest, stage results, approver identity, and target environment — automation beats paper because scripts must actually work to pass.
- Change control that scales: ticketed approvals for production, access-controlled environments, remediation plan + success criteria on every privileged change; low-risk paths auto-approve via policy gates.
- Risk in one line: severity ≈ impact × likelihood; compare against mitigation cost before adding ceremony.
- Value-stream mapping: when delivery feels slow, map commit-to-production steps with wait times — fix the longest wait first, not the loudest complaint.
7. Failure Modes
- Secret in git history → rotate immediately; history rewrites don't unsee it (it's cloned everywhere).
- Floating tags (
:latest,@v4) → silent supply-chain swaps; pin digests/SHAs. - Over-permissioned CI token → one compromised workflow owns the org; scope to the repo, expire fast.
- Unsigned images admitted → provenance theater; enforce admission, don't just generate attestations.
8. Interview Notes
- OIDC federation vs long-lived keys for CI auth.
- Design fork-PR isolation for a public repo with deploy secrets.
- SBOM in incident response: CVE lands at 2am, what do you query first?
- Prove a production deploy was authorized: which five pipeline records do you pull?
Related Topics
- Artifact Management
- Jenkins Security
- GitHub Actions
Locked down — now plan for when things break anyway. Continue in Rollback & Recovery.
Rollback & Recovery
Rollback is a feature, not an apology: a practiced, boring path from bad production back to good — decided by signals, executed in minutes, reviewed afterward.
1. What Is It?
Picking up from CI/CD Security, where defenses were hardened — defenses still fail, so recovery must be engineered with the same rigor as release.
2. Rollback per Strategy
| Strategy | Rollback move | Time |
|---|---|---|
| Rolling | Roll back batch by batch (or rollout undo) | Minutes |
| Blue/Green | Flip router back to Blue | Seconds |
| Canary | Drain canary, 100% to stable | Seconds–minutes |
| Feature flag | Toggle off | Instant |
| Recreate | Redeploy previous digest | Slowest — avoid where recovery matters |
Rollback deploys a previous known-good digest (Artifact Management) — never a fresh build. Fresh builds during incidents add untested variables to a fire.
3. Rollback vs Forward-Fix Decision
- Rollback when: cause unknown, blast radius growing, error budget burning fast, or the fix is uncertain. Default for Sev1.
- Forward-fix when: cause known, fix tiny and verified, rollback itself risky (migrations already applied — data can't "roll back," only migrate forward).
- Decider: on-call with pre-agreed thresholds, not a committee. Decide in minutes; review in the postmortem.
4. Recovery Drills (MTTR Practice)
- Game days: inject failure in staging (kill pods, expire certs, break the pipeline), time the recovery, fix the gaps found.
- Rollback rehearsal: each service rolls back on staging quarterly until MTTR is measured, not guessed.
- Jenkins/server recovery: restore
JENKINS_HOMEbackup to fresh infra, replay smoke pipeline (see Jenkins Advanced).
Rollback & Recovery · continued
5. Postmortems That Prevent Recurrence
Blameless, owner-assigned, pipeline-linked: every action item becomes a test, check, alert, or runbook — or it will recur. Track repeat-incident rate; a postmortem without a merged pipeline change is a diary entry.
6. Data Migration Practice
Data outlives code and can't be discarded on deploy — migrations move forward, never back:
- Version every migration: ordered, reversible scripts run by a migration runner (not hand-applied SQL); each deploy maps to exact schema versions.
- Expand-contract sequencing: add (nullable) → migrate data → enforce; ship app code compatible with both schemas before migrating.
- Risky upgrades: deploy dual-compatible app on the old schema, observe, back up, migrate, then ship schema-dependent code.
- Verify restore, not just backup: rehearse production migration and rollback paths on staging with production-scale data.
- Test data: construct minimal data per test; never depend on full production dumps (slow, privacy-risky, unreproducible).
7. Failure Modes
- No practiced rollback → improvisation during incidents; rehearse until boring.
- Rolling forward into a migration → data corruption; expand-contract migrations make both directions safe.
- Rollback untested because "we never need it" → the one time it's needed, it doesn't work. Test the path you pray you never take.
8. Interview Notes
- Rollback vs forward-fix: decision criteria in 60 seconds.
- Why rollback uses old digests, never fresh builds.
- Design a game day for a canary-deployed service.
- Rollback vs forward-fix after a migration already applied.
Related Topics
Related Topics
- Deployment Strategies
- Artifact Management
- Observability & Feedback
- Jenkins Advanced
Recovery engineered — the library's concept arc is complete. Return to the Topic Index for labs and reference.
CI/CD Security
The pipeline is production infrastructure with production secrets and the power to ship code — attack it like one: least privilege, signed artifacts, verified supply chain.
1. What Is It?
Picking up from Environments & Release, whose zones carry real credentials — the pipeline itself is the highest-value target in the estate: it holds deploy keys, signs releases, and runs attacker-influenced PR code.
2. Secrets Discipline
- Store in managers (Vault, cloud KMS, Jenkins credentials store, GitHub environments) — never in repos, images, logs, or chat.
- Scope narrowly (per-env, per-job), rotate on schedule and on any leak, audit every access.
- PR builds from forks get zero production secrets — credential-free sandboxes only (see Jenkins Agents trust boundary).
3. Signing, SBOM & Provenance
Build once, then: sign the digest (cosign), generate the SBOM (Syft/Trivy), attest provenance (SLSA: who built, from which commit, in which pipeline). Deploy policies admit only signed, attested images — see Artifact Management. When the next CVE lands, query SBOMs to find affected digests in minutes.
4. Least Privilege Everywhere
- CI tokens: per-repo, minimal scopes, short TTL (OIDC federation beats long-lived keys — workloads mint credentials, nobody stores them).
- Pipeline permissions:
GITHUB_TOKENminimal scopes; Jenkins agents can't read other jobs' secrets (agent→controller deny). - Humans: matrix authorization, SSO + MFA, no shared admin accounts, no standing prod access without review.
5. Supply-Chain Gates
Pin everything: action SHAs (not @v4 tags), base image digests (not :latest), plugin versions, lockfiles. Verify checksums on download. Each PR that bumps a dependency re-runs the full gate — Dependabot PRs are untrusted code until proven otherwise.
CI/CD Security · continued
6. Governance & Change Evidence
Regulated or not, every team answers "who shipped what, approved by whom, proven how" — the pipeline is the evidence:
- Maturity ladder: manual releases → versioned + automated → gated + attested → measured + continuously improved. Assess per area, fix the most painful gap first.
- Pipeline as audit trail: every production change maps to a commit, a built digest, stage results, approver identity, and target environment — automation beats paper because scripts must actually work to pass.
- Change control that scales: ticketed approvals for production, access-controlled environments, remediation plan + success criteria on every privileged change; low-risk paths auto-approve via policy gates.
- Risk in one line: severity ≈ impact × likelihood; compare against mitigation cost before adding ceremony.
- Value-stream mapping: when delivery feels slow, map commit-to-production steps with wait times — fix the longest wait first, not the loudest complaint.
7. Failure Modes
- Secret in git history → rotate immediately; history rewrites don't unsee it (it's cloned everywhere).
- Floating tags (
:latest,@v4) → silent supply-chain swaps; pin digests/SHAs. - Over-permissioned CI token → one compromised workflow owns the org; scope to the repo, expire fast.
- Unsigned images admitted → provenance theater; enforce admission, don't just generate attestations.
8. Interview Notes
- OIDC federation vs long-lived keys for CI auth.
- Design fork-PR isolation for a public repo with deploy secrets.
- SBOM in incident response: CVE lands at 2am, what do you query first?
- Prove a production deploy was authorized: which five pipeline records do you pull?
Related Topics
- Artifact Management
- Jenkins Security
- GitHub Actions
Locked down — now plan for when things break anyway. Continue in Rollback & Recovery.
📇 Quick Revision — Terms Table
| Recreate | Stop-all then deploy; downtime, slowest rollback. |
| Rolling | Batch-by-batch replacement gated by probes. |
| Blue/Green | Validate Green, flip router, keep Blue warm; instant flip-back. |
| Canary | Subset rollout 5 to 100 percent decided by golden signals. |
| Feature flag | Runtime toggle switching code paths; instant kill-switch. |
| Continuous Delivery | Every change releasable; production is a decision. |
| Continuous Deployment | Every passing change ships automatically. |
| Approval gate | Human click or policy gate releasing production. |
| Change window | Allowed deploy hours; never Friday night. |
| Staging | Prod-like rehearsal; automatic deploys, sanitized data. |
| Promotion path | dev to preview to staging to production, each gate explicit. |
| Release train | Scheduled departures; green and approved rides. |
| Hotfix lane | Documented fast path for fires; same checks, fewer approvals. |
| Preview environment | Ephemeral per-PR env; destroyed on merge. |
| Config vs code | Artifact constant; env vars and secrets inject per environment. |
| Drift detection | Nightly plan surfacing unexpected infra diffs. |
| Golden signals | Latency, traffic, errors, saturation. |
| SLI / SLO | Measured indicator vs promised objective (99.9 percent). |
| Error budget | Allowed failures; burn rate pages, blips do not. |
| MTTR | Mean time to recovery; measured by drills, not guessed. |
🎤 Concept Questions — Distilled Answers
Delivery: releasable behind a decision. Deployment: shipped automatically.
Rolling replaces capacity; canary tests a hypothesis on a subset with success criteria.
A rebuild voids verification — you would ship what you never tested.
Traffic shapes cannot fix data; expand-contract migrations come first.
Roll back by default on unknown cause or fast burn; forward-fix only for known tiny fixes over applied migrations.
Indicator measured, objective promised, budget allowed — alert on burn rate.
Reviewers click the actual change instead of imagining it.
Halt the burn via rollback of the known-good digest, stop the MTTR clock, then postmortem the class of bug into a pipeline gate.
📌 Command Cheat Sheet
helm upgrade app ./chart --set image.tag=$SHA | same digest, env-specific values |
helm upgrade app ./chart --set image.tag=$SHA (production) | same command behind approval gate |
terraform plan (per PR on envs/) | the plan is the review |
terraform apply (gated on prod) | deploys infra like code |
plan nightly | drift detection while you sleep |
rollout undo (rolling) | batch-by-batch retreat |
flip router to Blue | instant blue/green rollback |
toggle flag off | instant kill-switch |
deploy-staging: # auto on main script: helm upgrade app ./chart --set image.tag=$SHA deploy-production: # manual approval gate needs: [deploy-staging, smoke-tests] when: manual
🧪 Self-Quiz + Answer Key
- Blue/green flip-back or a feature-flag toggle.
- One gate: a human or policy decision before production.
- Per PR; destroyed on merge.
- Same artifact everywhere; env diff must equal config diff.
- On error-budget burn rate, not on every blip.
- Roll back the known-good digest; Sev1 defaults to rollback.
- In managers per env and job — never repos, images, logs, or chat.
- A landed pipeline change: test, check, alert, or runbook.