PRACTITIONERCHAPTER 07

Infrastructure as code and delivery pipelines

Every route to production is a pipeline, designed or not: send infrastructure and config through the same reviewed, staged path as code, slice state by blast radius, and let teams own their stacks on a versioned paved road

45 MINSRE, PLATFORM AND DEVOPSUPDATED 2026-11-07
PREDICT

A team reviews a Terraform pull request, sees the plan in CI, and approves it. Where should the production change be applied from?

This chapter is about the two systems an SRE or platform engineer builds so that everyone else can change production safely: the code that defines the infrastructure, and the pipeline that carries every change, code, config and infrastructure, from a commit to running in production. The mechanisms of release sign-off are in release management and sign-off and of controlled exposure in testing in production. Kubernetes and the tools in depth belong to a planned Platform course. Here you learn the practice and the decisions.

What infrastructure as code buys you

Martin Fowler’s short definition is that infrastructure as code “is the approach to defining computing and network infrastructure through source code”. What it replaces has a name too. Fowler’s 2012 essay on the snowflake server describes a machine shaped by years of manual changes until nobody can reproduce it: “good for a ski resort, bad for a data center.” Most companies still have some snowflakes. You find them during an incident, when someone asks how the load balancer was configured and the answer is a person on holiday.

Code buys you four things:

  • Reproducibility. You can build the environment again, in another region or after a disaster, from the repository.
  • Review. A change is a diff someone else reads before it lands.
  • History. The log says who changed what, when, and why. Auditors ask for exactly this.
  • Drift detection. Because the code states what should exist, a tool can tell you when reality differs.

It does not buy you correctness. Code executes a mistaken intent faster and across more resources than a person at a console could. On 28 February 2017, an S3 team member using an established playbook ran a command meant to remove a few servers from a subsystem used by S3 billing. One input was entered wrongly, and “a larger set of servers was removed than intended”. AWS’s fix was in the tool: they “modified this tool to remove capacity more slowly and added safeguards to prevent capacity from being removed” below a minimum. That is the right instinct for infrastructure code. The guard belongs in the tooling, not in a reminder to be careful. Terraform’s prevent_destroy makes Terraform reject a plan that would destroy a protected resource, but its documentation warns that it “doesn’t prevent Terraform from destroying a resource if you remove its configuration”. Guards that live in the code can be deleted with the code. Some must live outside it, in policy checks and cloud-level controls.

The pipeline is a product you run

Jez Humble and David Farley’s Continuous Delivery (2010) is still the reference for the shape. Chapter 5, “Anatomy of the Deployment Pipeline”, lists practices that read like an SRE’s checklist. Three carry most of the weight:

  • Only build your binaries once. Build the artefact at the commit stage, store it, and promote that same artefact through every environment. A rebuild for production is a different artefact from the one you tested.
  • Deploy the same way to every environment. The book calls this essential “in order to ensure that the build and deployment process is tested effectively”. A production-only deploy script is tested once a fortnight, by the customers.
  • If any part of the pipeline fails, stop the line. A red pipeline that people work around is no longer a pipeline.

Google’s release engineering chapter in the SRE book adds the scale argument: “In order to work at scale, teams must be self-sufficient.” The pipeline is how a team ships without asking you.

That makes the pipeline itself a production system, and you run it like one. It has users (every engineer), an owner (you), an on-call rotation, and a service level you can state: the time from merge to production, the share of runs that fail for reasons unrelated to the change, the queue time at nine on a Monday. When the pipeline is down, nobody can ship a fix for anything else, so it deserves the reliability of the services it deploys. A flaky test stage that fails one run in ten teaches engineers to press retry, and then a real failure gets retried too. The same holds for any automation that changes production, as toil and automation argues. The pipeline is also where an error-budget freeze is enforced: SLOs in practice describes the pipeline refusing non-exempt deploys once the budget is spent.

The design question to start from is not “which stages?” but “what are all the routes to production?” List them. Application code. Infrastructure code. Configuration and feature flags. Database migrations. Secrets. Data fixes run by hand. The cloud console. For each, ask whether it is reviewed, whether it is staged, how it rolls back, and who owns it. Google’s SRE workbook reports that “a majority of incidents are triggered by binary or configuration pushes”, and its canarying chapter defines the canary as “a partial and time-limited deployment of a change in a service and its evaluation”. Any route without that partial step is a route where one mistake reaches everyone. Cloudflare’s response is the model: it moved rule changes onto staged rollout “in the same manner used for other software”, while “retaining the ability to do emergency global deployment for active attacks”. Fast paths are legitimate. They should be named, narrow and rare.

State, stacks and blast radius

Declarative tools keep state. Terraform’s documentation says state exists to “store bindings between objects in a remote system and resource instances declared in your configuration”. State matters to you for three reasons. It can hold secrets, so it lives in a remote backend with locking and access control, never in the repository. It is locked during an apply, so one big state is one queue. And every plan reads all of it, so its size sets how slow plans are and how far a mistake can reach.

The commonest structural mistake is one state for all of production. Plans take ten minutes, two teams’ changes block each other, and a refactor in the queue module can plan a destroy in the database module. The fix is to split, and the split is the most consequential decision in your infrastructure code. Split along three lines:

  • Rate of change. The network changes a few times a year; a service’s queues change weekly. Do not make the weekly change wait behind, or risk, the yearly one.
  • Blast radius. If a mistake in this state could take down everything, it should contain as little as possible and be changed with the most care.
  • Ownership and permissions. A state is also a permission boundary. The identity that applies a team’s service stack should not be able to rewrite the organisation’s identity policies.
Layer Typical contents Changes Owner Review
Organisation Accounts or projects, guardrail policies, audit logging Monthly Platform and security Two platform reviewers, security informed
Network VPCs, peering, DNS zones, egress Quarterly Platform Platform, with a rollback rehearsed
Shared services Clusters, shared databases, the pipeline itself Monthly Platform Platform, affected teams consulted
Service stacks A service’s queues, buckets, databases, alarms Daily The service’s team The team, with automated policy checks

The frequencies and reviewers in the table are a rule of thumb; your own will differ. Keep the dependencies between layers few and explicit, a handful of published outputs such as subnet identifiers, so that a change to the network does not need a coordinated release of every service.

Environments are a related trap. Terraform’s CLI workspaces look like a way to hold staging and production in one configuration, and the documentation warns they are “not a suitable tool for system decomposition”, nor for deployments that need separate credentials and access controls. It recommends re-usable modules and a separate small configuration per environment, each with its own backend. That is also how you make staging and production differ only where you meant them to.

Modules: a paved road with version numbers

A platform team’s module is a decision made once: every database is encrypted, backed up for 14 days, tagged with its owner, and alarmed on storage. HashiCorp’s guidance on when to write one is sound: “A good module should raise the level of abstraction by describing a new concept in your architecture,” and they advise against modules that are no more than “thin wrappers around single other resource types.” A module called bucket that passes every argument through adds a dependency and no decision. A module called service-datastore that encodes your backup and encryption policy is a paved road.

Then version it. Without a pinned reference, Terraform “clones and uses the default branch” of a git module source, which means anything the platform team merges lands in every team’s next plan. A pin makes the upgrade the consuming team’s decision:

module "orders_db" {
  source = "git::https://git.example.com/platform/modules.git//service-datastore?ref=v4.2.0"
  name   = "orders"
  size   = "medium"
}

Versioning turns the platform team into a publisher, with the obligations that come with it: a changelog, semantic versions that mean what they say, a support window (for example, the current and previous major versions), and deprecation dates announced ahead. If teams are three majors behind, the modules are not worth upgrading to, and that is feedback about the product. Running the platform this way, with adoption as the measure, is the subject of platform as a product; the investment case is in architecture governance and platform investment.

Plan, review, apply

The workflow that most mature teams converge on has five steps, whatever the tool.

  1. Plan in the pull request. CI runs the plan against the real state and posts it to the review.
  2. Check it automatically. Policy checks such as Checkov, tfsec or Open Policy Agent run against the plan and block what must never happen: public buckets, unencrypted volumes, wildcard permissions. The cloud and infrastructure security chapter covers what those guardrails should catch.
  3. Review the plan, not only the diff. A three-line diff can plan forty replacements. Reviewers look for destroys and replacements, IAM changes, a change count that does not match the description, and anything outside the stack the author meant to touch.
  4. Apply from the pipeline. Terraform’s saved-plan workflow, plan -out then apply of that file, is “primarily intended for when running Terraform in automation”. The documentation adds two cautions: re-check the final plan if anything changed since the speculative one, and treat saved plan files as sensitive because they can contain secret values.
  5. Detect drift on a schedule. A nightly plan with -detailed-exitcode returns 2 when there are changes; that exit code opens a ticket for the owning team. The fix runs in either direction: bring the code up to reality, or reality back to the code.

Credentials follow the same logic. The pipeline uses a workload identity with short-lived credentials, as identity, access and secrets describes. Humans have read-only access to production. A break-glass role exists for incidents, pages someone when used, and every use ends with a pull request that brings the code back in line with what was done by hand.

Change approval without a gate

Somebody will ask who approved a change. In a regulated company or with an enterprise customer, a contract may require a change advisory board. Treat the people asking fairly: they want evidence that production changes are controlled, and they are entitled to it. The question is what produces that evidence.

DORA’s research on change approval is direct. Heavyweight approval processes “have a negative impact on software delivery performance”, and “no evidence was found to support the hypothesis that a more formal, external review process” was associated with lower change fail rates. DORA recommends peer review “to meet the goal of segregation of duties”, recorded in the development platform, with automated testing and monitoring to catch bad changes.

In practice you negotiate. ITIL, which most change managers work from, already has the category you need: the standard change, a pre-authorised change of a known low-risk type. You propose that any change which passes the pipeline’s gates, touches only a service stack, and carries an automatic record (the plan, the reviewer, the test results, the canary verdict) is standard. Changes to identity, the network, or a migration that cannot be rolled back stay with the board. The auditor gets better evidence than a meeting minute, and the board’s time goes to the changes that deserve it. How DORA’s delivery metrics are used once you have them is covered in delivery metrics and reporting.

Choosing the tool, and the 2023 licence change

The tool matters less than the practice, but you will be asked. The real choice is between a declarative tool with its own state (Terraform, OpenTofu, Pulumi), the cloud provider’s own service (CloudFormation, and CDK on top of it), and controllers that reconcile continuously inside a cluster (Crossplane and its kin). Choose on the clouds you run, the languages your teams already read, and how much of the estate is already in one tool. Migrating state between tools is a project, not an afternoon.

The licence is part of the decision now. On 10 August 2023 HashiCorp announced it was “changing its source code license from Mozilla Public License v2.0 (MPL 2.0) to the Business Source License” for future releases, permitting use “except where providing a competitive offering to HashiCorp”. On 20 September 2023 the Linux Foundation announced OpenTofu, “an open source successor to the MPLv2-licensed Terraform”; its repository is licensed under MPL 2.0. For a company using the tool to manage its own infrastructure, the licence text targets competing vendors rather than that use. Whether your company requires an open-source licence as a matter of policy is a question for your legal team, not for this chapter. If you consider moving between the two, check compatibility for the exact versions you run rather than assuming either is a drop-in replacement for the other.

Where practitioners disagree

One infrastructure repository or many. A monorepo gives one place to search, one CI and atomic changes across stacks. Repositories per team give clear ownership and independent pipelines. Both work; what fails is one repository with one state and one team allowed to merge.

Push or pull. In a push model the pipeline applies changes. In GitOps, as the OpenGitOps project defines it, desired state is declarative, versioned and immutable, pulled automatically by agents, and continuously reconciled. Pull suits clusters and catches drift by design; push is simpler for cloud resources outside a cluster. Many companies run both.

How much abstraction. Some platform teams wrap everything in modules so product teams never see a raw resource. Others publish a few opinionated modules and let teams write the rest, with policy checks as the safety net. Heavy abstraction leaks the first time a team needs a setting the module did not expose.

Shared staging or environments per change. Ephemeral environments per pull request remove the queue for staging and cost money and setup time. Shared staging is cheap and becomes a queue as the number of teams grows.

Day to day

Daily. You look at the pipeline’s health before anyone else does: failed runs that were not the change’s fault, queue time, the slowest stage. You review infrastructure pull requests in the layers you own and answer questions in the platform channel. When a deploy causes an incident, you are often the person who knows how to stop the rollout.

Weekly. You triage the drift report and route each finding to its owner. You fix or quarantine the flakiest test stage, because flaky stages are how teams learn to ignore red. You release modules, with a changelog, and hold an hour of platform office hours where teams bring the pull requests they are unsure about.

Monthly. You read the delivery metrics per service with each team’s lead: lead time, deployment frequency, change fail rate, recovery time, rework. You review the break-glass log; every use should have a matching pull request. You meet the change manager, if there is one, to look at which changes went standard and whether any should not have.

Quarterly. You re-inventory the routes to production, because new ones appear: a new flag system, a vendor’s console, a data team’s scheduler. You rehearse a rollback for each critical service and time it. You upgrade the tool and provider versions, retire old module majors, and check that the pipeline’s own disaster recovery works: can you deploy if the CI provider is down?

The meetings that matter are the postmortem reviews, run as incident management describes, where a change was the trigger. Each one is a design review of the pipeline in disguise. Ask which gate should have caught it, and whether that gate would also have blocked a hundred good changes.

BY ORG SIZE
STARTUPunder 30 people

There is no platform team. One engineer owns the pipeline and the cloud account, and that is a named responsibility, not a hobby. Use a managed CI service and the cloud’s managed deploy targets. Put the account, network and identity into code from the first month, because they are the parts you cannot reproduce later. Do not build a module library; three services do not need one. One repository and two or three states are enough. The rule that matters most at this size is that nothing reaches production except through the pipeline, including the founder’s fixes.

SCALE-UP30 to 300

This is where the central repository becomes a queue. A platform team forms, owns every merge, and spends its week reviewing. Your work is to split state by layer, publish the first versioned modules, move applies into the pipeline and take standing write access away from humans. The first enterprise customers and a SOC 2 audit arrive and ask how changes are approved; answer with the pipeline’s records, not a new meeting. Count the routes to production now, while there are few enough to count.

ENTERPRISE300 and up

There are dozens of accounts, several pipelines inherited from acquisitions, a change advisory board with real authority, and resources nobody has codified. The work is federation and negotiation. A landing zone and organisation-wide policy set the floor; product teams own their stacks above it. You negotiate standard-change status for pipeline deploys with change management, retire old pipelines one migration at a time, and import hand-built resources into code. Module support windows and deprecation dates become commitments other teams plan against.

ARTEFACT Design the deployment pipeline ~90 MIN
YOU PRODUCEDeployment pipeline design

Template

# Deployment pipeline design: <system or company>
Author · Date · Status · Reviewers: platform, security, one product team, change management (if any)

## 1. Scope
Covered: <services and infrastructure>
Out of scope, and why: <list>

## 2. Routes to production today
| Route | What it changes | Reviewed? | Staged? | Rollback | Owner |
|---|---|---|---|---|---|
| Application code | | | | | |
| Infrastructure code | | | | | |
| Config and feature flags | | | | | |
| Database migrations | | | | | |
| Secrets | | | | | |
| Console and manual fixes | | | | | |

## 3. Stages
| Stage | What runs | Gate to pass | Time budget | On failure |
|---|---|---|---|---|
| Commit | | | | |
| Build (artefact built once, versioned, signed) | | | | |
| Test | | | | |
| Staging (same deploy mechanism as production) | | | | |
| Production canary | | | | |
| Progressive rollout | | | | |
| Verify | | | | |

## 4. Infrastructure changes
State layout: <stack — contents — owner — rate of change — blast radius>
Workflow: plan in PR → policy checks → plan reviewed → pipeline applies the saved plan
Modules: <where they live, versioning, support window, deprecation>
Credentials: <pipeline identity; human access to production; break-glass and its alert>
Drift: <schedule; who gets the ticket; which direction you reconcile>

## 5. Rollout and rollback
Canary size and duration:
Abort signals and thresholds:
Rollback mechanism and measured time:
What rollback cannot undo, and the compensating action:

## 6. Change approval
Standard (pre-approved) changes and their conditions:
Changes that need a human approval, and whose:
How the change record is produced:

## 7. The pipeline's own reliability
Owner · On-call · Target time from merge to production · Target share of runs failing for non-change reasons

## 8. Measures
| Service | Metric | Baseline | Target | By |
|---|---|---|---|---|
(change lead time, deployment frequency, change fail rate, failed deployment recovery time, deployment rework rate)

## 9. Migration plan and open questions
| # | Step or question | Owner | By |
|---|---|---|---|
WORKED EXAMPLE

Rhodonite is a fictional company that runs smart electricity meters for a utility: 500 people, 90 engineers in nine teams, 1.8 million meters sending a reading every half hour, 86.4 million readings a day. Palesa, Platform Lead for the eight-engineer platform and SRE team, wrote this design.

Scope. The head-end, data platform, billing integration and customer portal services, 34 in all, and their cloud infrastructure. Out of scope: meter firmware, which has its own over-the-air pipeline in rings.

Routes today. Application code deploys twice a month in a Tuesday-night window. Terraform is applied from laptops against three states. Service config is a parameter file edited in the console. Migrations run by hand. The 2025 audit found 41 resources changed outside code.

Stages. Commit: unit tests and lint, under 10 minutes. Build: one container image per commit, tagged with the commit hash and signed; the same image goes everywhere. Test: integration tests replay one hour of anonymised traffic, 3.6 million readings. Staging uses the production deploy tool. Canary: 5% of ingestion workers for 30 minutes; abort if ingestion lag passes 5 minutes or errors pass 0.5%. Rollout: 25%, 50%, 100%. Verify: reading completeness checked two hours later.

Infrastructure. Four layers: organisation (platform, monthly), network (platform, quarterly), data stores (platform, with the owning team reviewing), and one service stack per team (the team, daily). Modules are pinned by version; the current and previous majors are supported for six months. The pipeline uses short-lived credentials; humans are read-only; the break-glass role pages security. A nightly drift plan opens a ticket for the owning team.

Rollback. Redeploy the previous image: 6 minutes, timed in a staging rehearsal. Migrations use expand and contract. Rollback cannot recall commands already sent to meters or readings already forwarded to the utility’s billing; both have a documented correction procedure.

Change approval. Agreed with Ilse, the utility’s change manager: pipeline deploys that pass every gate and touch only service stacks are standard changes, with the record created automatically. Network, identity and irreversible migrations remain normal changes with five working days’ notice.

Measures. Deployment frequency: twice a month today, daily for the data platform by Q3. Change lead time: median 9 days today, under 2 days by Q3. Change fail rate: no reliable baseline; measure from the first pipeline deploy and set a target after one quarter.

Now you

You are a platform engineer at Quartzite, a CRM product for small businesses: 300 people, 100 engineers in 12 product teams plus platform (7), SRE (4) and security (5). Application services deploy about 25 times a day through CI. Infrastructure is different. All Terraform lives in one central repository; production is one state of about 3,900 resources and a plan takes 11 minutes. Only the platform team can merge, and applies are batched twice a week from a platform engineer’s machine. The 140 infrastructure pull requests a month wait a median of three working days. Because of the batching, an application change and the queue it needs often ship days apart, and twice this quarter the application went first and failed. The reporting team has copied a 2023 network module into its own repository. Kipchoge, the security lead, wants no human write access to production; two engineering managers want console access back. A large prospect’s security questionnaire asks how production changes are approved. Write the deployment pipeline design for application and infrastructure delivery at Quartzite.

Self-check

DECIDE

You are a platform engineer at Quartzite, a 300-person CRM company with 100 engineers: 12 product teams plus platform, SRE and security. All Terraform lives in one central repository that only the seven-person platform team can merge. The 140 infrastructure pull requests a month wait a median of three working days, and reviewing them takes nearly a fifth of the platform team's time. Abla, who manages the reporting team, now keeps a copied network module in her team's own repository. Jabari, the Head of Platform, asks you to propose how infrastructure code should be organised. What do you recommend?

READING
  1. BOOK
    Continuous Delivery Jez Humble and David Farley, 2010

    The reference for the deployment pipeline. Read chapter 5, 'Anatomy of the Deployment Pipeline', for build once, deploy the same way everywhere and stop the line, and chapter 11 on managing infrastructure and environments. Read: Addison-Wesley, 2010.

  2. BOOK
    Infrastructure as Code, third edition Kief Morris, 2025

    The practice of infrastructure code as a discipline rather than a tool: how to structure it, test it and deliver it, and how it fits a platform strategy. The author's site links to the book and his related writing. Read: O'Reilly, 2025.

  3. HANDBOOK
    Release Engineering (SRE book, chapter 8) Dinah McNutt, 2016

    Google's release engineering: hermetic builds, self-service release, access control over who can release, and configuration kept in source control under code review.

  4. HANDBOOK
    Canarying Releases (SRE Workbook, chapter 16) 2018

    What a canary is, how to pick its metrics so a change is attributable, and why configuration pushes need one as much as binaries do.

  5. POST
    Details of the Cloudflare outage on July 2, 2019 John Graham-Cumming, 2019

    A clear postmortem of a fast path around a careful pipeline, with the changes Cloudflare made afterwards. Read it while listing your own routes to production.

  6. DOC
    Creating modules HashiCorp

    When a module earns its place and when it is a thin wrapper. The same test applies whatever infrastructure tool you use.

  7. DOC
    Streamlining change approval DORA

    The research on change advisory boards and what to do instead. Take it to your first meeting with change management.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Capacity and cost →