Application Releases and Infrastructure Changes Have Different Lifecycles
Two pipelines lived in the same repository and looked interchangeable.
The application pipeline built an image on every merge, published it by digest, deployed it behind a health check, and could restore the previous digest in under four minutes. On a normal Tuesday it ran eleven times before lunch. The infrastructure pipeline ran whenever someone edited a .tf file: most weeks, never twice in an afternoon.
The platform team copied the first pipeline's shape into the second. Merge to main, run plan, run apply. Six days later a cleanup that looked routine removed a subnet a managed database was still using, at 02:14. The plan had been correct. Nobody had read it, because the pipeline had been designed for a change nobody needed to read.
The difference is the object being changed. An application release swaps a cartridge while the machine runs; the previous cartridge is on a shelf. An infrastructure change rewires the distribution board behind the machine. Both are changes. Only one can be undone by putting the old part back.
Five properties separate them.
| Property | Application release | Infrastructure change |
|---|---|---|
| Unit of change | One image digest, built once | A plan computed against live state, new every run |
| Blast radius | One pod or one service | A network, IAM policy or route table can be an outage |
| Reversibility | Redeploy the previous digest | A deleted database comes back empty |
| Ownership | Service team owns the image and health | Platform team owns account, network and state |
| Cadence | Eleven deploys a day builds muscle memory | One change a week builds no intuition |
Rollback belongs to the resource, not the pipeline
Redeploying an image is a supported operation with a known duration. Recreating a deleted database is not a rollback; it is a new database with no data. Read the rollback story from the plan and the provider schema, never from the application pipeline.
That explains most failed adoptions. Teams copy the application pipeline because it is the one they know, and the copy inherits its assumption that frequency provides safety. Figure 1 shows where the lifecycles diverge: at the review, not at the tool.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
C["Change proposed in a pull request"] --> Q{"What is being changed?"}
Q -->|"service code or image"| A1["Build once
immutable image digest"]
Q -->|"infrastructure graph"| I1["Plan against live state
a new result every run"]
A1 --> A2["Deploy many times a day
health gate, previous digest ready"]
A2 --> A3["Rollback: redeploy
the digest that worked"]
I1 --> I2["Review the plan
blast radius is in the diff"]
I2 --> I3["Approve one artifact
commit, versions, hash"]
I3 --> I4["Apply once per state
serialized and logged"]
I4 --> I5["Rollback: reconcile
a new plan, not a rewind"]
A3 --> E1["Evidence: digest plus
deploy timeline"]
I5 --> E2["Evidence: plan identity
plus apply record"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class C,Q primary;
class A1,I1,I2,I3 secondary;
class A2,A3,I4,E1 ok;
class I5,E2 warn;
Nothing in the lower branch is unusual Terraform. The unusual part is the object between plan and apply: a decision that belongs to a named person and is recorded against a specific plan. Figure 2 places that decision on the boundary between the deliveries.
Adoption works in stages, each with its own failure mode. Plan on every pull request first, read-only and advisory; the failure is noise. Then make it a required check; the failure is a slow queue. Then gate the apply; the failure is an approval given without reading. Then, only for sandbox roots, remove the gate. Skipping a stage moves the cost to an incident.
The rest of this article is the pipeline that survives the third stage.
Build the Pull Request Plan Workflow
A plan on a pull request is the cheapest control in the system. It runs before anything is approved, produces a document a reviewer can read, and fails closed when the configuration is wrong. It is also where teams accidentally execute untrusted code.
A plan is only evidence if the tool that produced it is fixed. Pin every layer, then run the checks that need no credentials.
| Control | Pin to | Failure it prevents |
|---|---|---|
| Terraform CLI | Exact version in required_version and in the workflow | Runner and laptop disagree about semantics |
| Providers | Committed .terraform.lock.hcl, init -lockfile=readonly | A later init silently upgrades a provider |
| Third-party actions | Full commit SHA, never a tag | A moved tag runs different code with your token |
| Modules | Tag or commit, never a branch | A branch moves after review |
| Static checks | fmt, validate, lint and policy with pinned tool versions | Style drift and unsupported arguments reach review |
Pinning is necessary but not sufficient. validate proves the configuration is well formed against the provider schemas; it cannot prove the API will accept the result, or that the result is the change you wanted.
The credential question is where the workflow either has a boundary or does not. A plan needs to read state and read the cloud objects it manages, which is a real credential even though it cannot write. Give the plan job its own role: read the one state key, read and write the lock object, read-only on the target resources, no IAM changes.
Forks are untrusted by default. A pull_request workflow from a fork runs code the contributor controls, with a read-only GITHUB_TOKEN and no secrets. GitHub withholds OIDC write tokens from that event unless the repository or organisation has opted in, and that setting is one switch from being wrong. Make the fork path explicit.
pull_request_target is not the fork-safe trigger
The trap is the trigger, not the checkout. It runs the base repository's workflow with secrets and a write token, which is why labelling uses it. But it is one actions/checkout away from executing the fork head, and a plan executes code: provider plugins start, external data sources evaluate, and module logic can run at init. Untrusted configuration is not data you can "just plan".
Forks get static checks, not credentials
A pull request from a fork runs code the contributor controls. Give it fmt, validate and policy checks with no cloud identity and no state access. The authoritative plan must come from a branch in this repository, reviewed by a maintainer, on a commit that can enter the protected branch.
The workflow that survives looks like Figure 3.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
PR["Pull request opened"] --> F{"Head branch in this repository?"}
F -->|"no, from a fork"| S1["Static checks only
fmt, validate, policy"]
S1 --> S2["No cloud token, no state read
no plan artifact published"]
S2 --> S3["Maintainer re-runs the plan
from a branch in this repository"]
S3 --> P1
F -->|"yes"| P1["Plan job
read-only identity"]
P1 --> P2["init -lockfile=readonly
pinned CLI, providers, actions"]
P2 --> P3["plan -out=tfplan
-detailed-exitcode"]
P3 --> D{"Exit code"}
D -->|"1"| X1["Plan error
merge blocked"]
D -->|"0"| X2["No changes
record and stop"]
D -->|"2"| R1["Publish the summary
counts, replacements, risky types"]
R1 --> R2["Reviewer reads the diff
not the raw logs"]
R2 --> M1["Merge to the protected branch"]
M1 --> M2["Authoritative plan
on the merge commit"]
M2 --> G1["Environment gate
required reviewers"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class PR,F,D,M1 primary;
class P1,P2,P3,S3,R1 secondary;
class M2,G1,X2 ok;
class X1 danger;
class S1,S2,R2 warn;
Three details carry most of the safety.
The fork branch never reaches the plan job. It runs formatting, validation and policy checks with no cloud identity and no state access, and the authoritative plan comes from a branch here, by a maintainer, on a reviewable commit. The contributor still gets syntax feedback in minutes.
The merge commit produces the authoritative plan. A pull request plan describes the branch head, which can change after review or after another merge. The plan attached to the merge commit is the one whose source enters the protected branch.
The summary is published, not the plan file. Counts, replacements, data-bearing resources, IAM and tag changes, and the addresses being destroyed. The binary artifact goes to the protected store described next. A plan file pasted into a comment is a secret-bearing document with no retention policy.
Protect the Saved Plan and Record Its Inputs
terraform plan -out=tfplan writes an archive, not a screenshot. It contains the full configuration, every planned value, every input variable in cleartext, and the state snapshot the plan was computed from. That is what lets apply run without re-asking for variables, and why the artifact deserves the same handling as state. The credentials part of this series covered the copies; this section covers the identity.
A plan is only reviewable if you can say which plan it is. Record six things and store them beside the artifact, not in someone's memory:
| Field | What it proves |
|---|---|
| Commit and tree | the configuration that was evaluated |
| CLI version | the semantics used to evaluate it |
| Lock file digest | the provider packages that were installed |
| Workspace and state key | the object the plan was computed against |
| Plan digest | the artifact approved is the artifact that runs |
| Variable source digest | which inputs moved, without recording values |
Add the account placeholder, a created-at, an expiry and the approver.
The first five are checkable by the pipeline. The sixth explains most surprises: a plan can change because a variable moved, not because the code did.
Terraform checks two things at apply time. It refuses a plan produced by an incompatible CLI version, and it refuses a plan whose prior state no longer matches the current state's lineage and serial, with Saved plan is stale. That is a real safety property: it is what stops two pipelines from applying one plan against two different worlds.
It is narrower than assumed. The check compares Terraform's record, not the cloud. A resource deleted in the console does not move the serial. A commit merged after the plan does not move it either, and apply does not read the configuration again. The pipeline has to assert the rest: the commit at apply time is the commit in the record, the lock digest is unchanged, the artifact digest matches the approved one, the approval is younger than the window, and a fresh refresh does not contradict the plan.
That last item is the re-plan decision: re-plan when the branch moves, the lock file changes, a provider or module reference changes, a variable feeding a planned value rotates, drift appears, or the approval expires. Set the window from the change, not convenience: an hour for a network change in business hours, a day for a low-risk root, never a week.
There is a second pattern, which hosted systems use. Re-plan at apply time and compare resource_changes against the reviewed JSON. An empty diff means the fresh plan is semantically identical and can be applied; anything else means the approval was for a different document. That links review to execution without shipping a binary artifact, at the cost of two plans per change and a comparison tool you have to trust.
Either way, the artifact is time-boxed and access-controlled. Days, not the platform default of ninety; a named reader list, not the whole organisation; a digest in the record, not a filename.
Separate Approval from the Apply Identity
An approval is only real if it changes what the machine may do. A comment does not. A required reviewer on a protected environment does, because the gate is checked before the job runs and the OIDC token is minted only after it passes.
Approval is not a comment
An approval is real only if it changes what the machine may do. A required reviewer on a protected environment gates the job before the OIDC token is minted; a comment does not. The plan role stays read-only and the apply role is reachable only through that gate.
That gives a clean split. The plan role trusts a branch or pull request subject and holds read-only permissions. The apply role trusts repo:org/repo:environment:production and holds write permissions. The human approval becomes part of authentication rather than a note attached to it. A merged change can produce a plan; only an approved deployment can produce an apply.
Three constraints make the split hold.
The environment needs protection rules, not just a name: required reviewers, a deployment branch policy that admits only the protected branch, self-review disabled, and a wait timer where a second look is warranted. An environment called "production" with no rules is a label, and a label is assumable by any workflow that declares it.
The subject needs to be narrow. An environment subject is stable across trigger types and cannot be produced by a pull request, which is the property you want. A pull_request subject carries no pull request number, no author and no indication that the branch came from a fork; it says "any pull request in this repository, forever". A branch subject says every workflow on that branch, including one added by a merged pull request.
The apply role must not be able to widen its own trust. No permission to change the OIDC provider, its own trust policy, the state bucket policy, or the workflow file that requests the token. Those belong to a bootstrap root owned above the workload. An apply role that can edit its own trust policy is an administrator with extra steps, and the workflow file is part of the boundary: treat a change to the apply workflow as a privilege change, with code owners and its own review.
The apply job itself should be boring. Check out the recorded commit, run init -lockfile=readonly, download the artifact by digest, verify it against the record, apply the plan file, and write the role session ARN, approver, timestamp and plan digest into the run record. It should not run a fresh plan "to be safe", and it should not retry automatically. Both turn a reviewed decision into an unreviewed one.
Serialize Applies by State and Handle Exit Codes
One state key has one writer
Two applies against the same state produce a record that describes neither configuration. One snapshot overwrites the other, objects created by the loser become orphans, and the next plan proposes to create things that already exist.
Three layers protect the invariant, and they fail at different moments:
| Layer | Mechanism | Failure timing | Recovery |
|---|---|---|---|
| Pipeline | Concurrency group per environment and state, cancel-in-progress: false | A queued run is cancelled or the wrong commit is applied | Prove the applied commit against the plan record; re-plan |
| State lock | Backend lock object, for example .tflock beside S3 state | Contention happens before any change | Bounded retry with -lock-timeout; inspect an apply-time lock |
| Human process | Change freeze, release window, named on-call owner | Judgement, not automation | A real pause mechanism, not disabling the workflow |
The queue detail matters: a GitHub concurrency group normally allows one running and one pending run, so a third merge can cancel the second. That is tolerable only if the pipeline can prove which commit was applied, which the plan identity record does.
Exit codes are the smallest part of this section and the most common bug:
| Exit code | Meaning | Correct pipeline behavior |
|---|---|---|
0 | Success, no changes | Pass; record a no-op |
1 | Error | Fail; never apply |
2 | Success, changes pending | Publish the plan and require approval |
A workflow running under set -e, or one that maps any nonzero status to failure, fails every pull request that changes anything. A workflow that reads 1 as "changes pending" applies after an error. Two of these three codes are successes, and only one means there is something to review.
A Failed Apply Is a Reconciliation Problem
Terraform's behaviour on a failed apply is documented and short: it logs the error, writes state for whatever completed, unlocks the state, and exits. It does not roll back. You are left with the state of a partial change.
Three views then disagree: what state says Terraform owns, what the provider says exists, and what the configuration says should exist.
The gaps are the work. A resource created successfully whose state write failed exists in the cloud and not in state; it needs an import. A resource destroyed before the failure is gone while the configuration still asks for it, so the next plan creates a new one with a new identity. A resource whose create failed is usually tainted, so the next plan proposes a replacement, which on a data-bearing resource is a data-loss instruction rather than a retry.
Git revert is not rollback, and that is the sentence to put in the runbook. Reverting the commit changes the desired state. Applying the revert computes a new plan against the partially changed world: it destroys what the failed apply created, recreates what it destroyed, and fails on anything the provider will not undo. If the original change deleted a database, the revert creates an empty one. The revert is a legitimate step, but it is a new change with its own plan and blast radius.
Reconcile in a fixed order: stop the pipeline so nothing retries, capture the failing run's log and the state serial, inspect the three views, decide per resource whether to complete, import, destroy or leave, write the reconciliation plan, have someone who did not write the original change review it, apply it, and record the decision with timestamps. The lock gets its own line: a killed runner can leave it held, and force-unlock is only safe after confirming no operation is running. The lock ID in the error is evidence, not an obstacle.
Git revert is not rollback
Reverting the commit changes desired state; the next apply computes a new plan against a partially changed world. It may destroy what the failed apply created, recreate what it destroyed, and fail on anything the provider will not undo.
A failed apply needs a per-resource decision, not one global command:
| Failure shape | What the evidence shows | Next action |
|---|---|---|
| Object created, state write failed | Cloud object exists, no address in state | Import it, then plan to no-change |
| Object destroyed before failure | Address exists in state, object is gone | Recreate deliberately, or import a replacement |
| Create failed and object is tainted | State marks the object for replacement | Inspect the provider error before re-planning |
| Lock held after a killed runner | Lock ID names a run that is not active | Confirm no writer, then force-unlock with the ID |
| State serial moved unexpectedly | Another writer or restore changed the record | Stop writers, inspect lineage, choose recovery |
The lab turns that into a pipeline design and an interrupted-apply tabletop.
Review the team pipeline
Execution status: design-only. Terraform CLI 1.17.1 was current on 5 November 2026. No cloud account, token or pipeline run is used; every identifier below is a placeholder.
Prerequisites. Terraform CLI 1.17.1, Git, a text editor, and read access to one repository's CI configuration. No cloud credentials.
Minimal setup. Create labs/p26/ and one record per artifact:
| Record | What it holds |
|---|---|
roots.md | One row per root and state: path, key, environment, apply owner, cadence, data-bearing resources |
pipeline.md | Plan, approval and apply stages with every credential that crosses the boundary marked |
plan-identity.md | The six checkable facts, account placeholder, created-at, expiry, approver, retention and reader list |
reconcile.md | Interrupted-apply and stale-plan tableaux, with one decision per resource |
evidence.md | Artifact, producer, approver, retention period and reader group |
Root choice. One root with a remote state key and a data-bearing resource; if you have none, use a network root and treat a subnet as the data-bearing object.
The backend the design assumes, with placeholders:
terraform {
required_version = "1.17.1"
backend "s3" {
bucket = "example-tfstate-prod"
key = "payments/network/terraform.tfstate"
region = "eu-west-1"
use_lockfile = true
encrypt = true
}
}
- Inventory. One row per root and state: path, state key, environment, apply owner, change cadence, data-bearing resources. Two roots sharing a state key is a finding, not a detail.
- Draw the pipeline in
pipeline.md: plan on pull request, approval gate, apply on the protected branch. Draw the approval boundary as a line and mark every credential that crosses it. The plan job holds no write credential; the apply job holds no credential the gate did not create. - Write the plan identity record: commit, CLI version, lock digest, state key, plan digest, variable source digest, account placeholder, created-at, expiry, approver. Add the artifact's reader list and a retention period in days.
- Write the exit-code handler for your platform. Test it in a scratch copy with the local backend and a
terraform_dataresource, so nothing leaves the machine: run it against a no-change plan, a change plan and a syntax error, and record all three codes. The version below omitsset -edeliberately.
set -uo pipefail
terraform plan -input=false -lock-timeout=5m \
-out=tfplan -detailed-exitcode
code=$?
case "$code" in
0) echo "no changes"; exit 0 ;;
1) echo "plan failed"; exit 1 ;;
2) echo "changes present"; exit 0 ;;
*) echo "unexpected exit $code"; exit 1 ;;
esac
- Tabletop the interrupted apply. Take a five-resource plan and fail resource 3. Write what state contains, what the cloud contains, what the revert commit would plan, and the action for all five. Include one "import", one "destroy", and one "leave until the data owner decides".
- Tabletop the stale plan. Plan at 09:00, another apply at 09:20, approval at 09:40. Write what Terraform returns, what the pipeline does next, and who is told.
- Tabletop the fork. A contributor's pull request adds an
externaldata source tomain.tf. Write which job runs, which credentials exist, and what the reviewer sees. - Complete the evidence contract in
evidence.md: artifact, produced by, approved by, retained for, reader group.
Expected observation. A pipeline where the only path from plan to apply runs through a named approval and a role a pull request cannot assume, a plan identity record with six checkable facts, and three failure tableaux with a decision per resource.
Failure checks. The design fails if the plan job can write the state key, if one role covers plan and apply, if the apply workflow trusts a pull request or branch subject, if the approval has no expiry, or if the reconciliation begins with git revert.
Cost dimensions. Zero. No cloud calls; the only artifact is a design document.
Cleanup. Delete labs/p26/, or keep it as a reviewed design with placeholders intact. Remove any saved plan from step 4.
Evidence to keep. The roots inventory, the pipeline diagram with the approval boundary, the plan identity record, the exit-code transcript, the interrupted-apply table and the evidence contract.
A pipeline is not a way to change infrastructure faster. It is a way to make the decision to change something explicit, and to keep the evidence that the decision was made.
Next in the Series
In HCP Terraform: Workspaces, Runs, Variables and Private Modules, we'll explore Map the CLI workflow to hosted team execution while checking feature and data-handling requirements.