Skip to content

feat(infra): show the terraform plan on the PR, and guard the unattended apply - #360

Merged
athvin merged 2 commits into
mainfrom
bm/infra-plan-pr-comment
Oct 31, 2026
Merged

athvin merged 2 commits into
mainfrom
bm/infra-plan-pr-comment

Conversation

@athvin

@athvin athvin commented Oct 31, 2026

Copy link
Copy Markdown
Owner

Follow-up to #358, which landed the plan role's bootstrap/*.tfstate grant this PR's new matrix leg needs (already applied on main: 0 added, 1 changed, 0 destroyed).

The service-account half of §14.2 has been live since #352 — two federated OIDC roles, zero repository secrets, plan on every PR, unattended apply on merge. Four gaps around it, closed here.

1. The plan never reached the PR

It went only to the run summary, so reviewing an infra PR meant leaving the PR. A new comment job upserts one sticky comment per PR, keyed by an HTML marker — a per-stack add/change/destroy table with destroy counts bolded, a > [!WARNING] block when any is non-zero, over collapsed per-stack diffs. Upserted, so a ten-push PR has one comment and not ten. It is the only job in the file with a write scope (pull-requests: write).

You should see it on this PR, with four rows and all-zero counts — the diff touches no Terraform.

2. The plan was not a required check, and could not become one

The workflow carried paths: filters. A workflow a path filter skips never reports, and a required check that never reports blocks every backend-only PR forever (CLAUDE.md's rule). Replaced with the detect-job pattern rust.yml and frontend.yml already use.

Its push path fails safe: an absent, all-zero or unreachable before-SHA (force-push, new branch) reports "changed" rather than "unchanged". A wrongly-skipped plan is cosmetic; a wrongly-skipped apply silently diverges the account from config until someone notices.

Promoting the contexts to required is a follow-up step, not part of this PR — a required context naming a job that has not yet reported on main blocks every PR until it does.

3. "All our terraform" was three of five stacks

The matrix is now a list of {key, dir} objects:

key validate plan apply
state-backend yes yes never
organization yes no never
core / dev / prod yes yes yes
  • bootstrap/state-backend is planned and never applied — it owns the bucket its own backend lives in, so applying it from CI is the circular case, but a plan still catches drift in the bucket's config.
  • bootstrap/organization joins the credential-free validate tier only. Its one required variable is a root account email deliberately absent from a public repo, and terraform validate evaluates no variables — verified, which is why the TF_VAR workaround I expected to need is absent.

Every matrix job now sets name: explicitly. Left alone GitHub names it plan (core, infra/terraform/envs/core) and silently un-protects plan (core).

4. The apply had no speed bump and left no record

It now plans to a file, shows it, guards it, and applies that file rather than letting -auto-approve re-plan invisibly. tf-destroy-guard.sh refuses any non-zero destroy count unless the commit message carries ALLOW-DESTROY — the repo squash-merges, so that means the PR title, reviewed in the same diff as the destroy. The shown plan goes to the run summary, under if: always(), so a refused apply still records what it refused.

A speed bump, not a policy engine: it cannot tell a benign replace from losing Aurora, and a replace trips it too (1 to add, 1 to destroy). That is the accepted cost of having no per-env carve-out to forget. §14.2's prod-scoped apply role is still the real remaining defence-in-depth.

tfplan is never uploaded and show -json is never printed — both carry sensitive values in cleartext, while show -no-color redacts to (sensitive value).

Verification

Three helpers under scripts/ci/ rather than heredocs, because a gate is not trusted until it has been observed failing and a parser inside a matrix job can only be exercised by pushing a commit.

  • tf-destroy-guard.sh — 9 cases: no-changes / adds-only / outputs-only allowed; 1 to destroy refused (exit 1); same with ALLOW-DESTROY allowed; Plan: 1 to import, …, 3 to destroy refused (the import variant a full-line pattern would miss); unparseable input fails closed (exit 2) rather than reading zero destroys out of garbage; bad usage 2.
  • tf-plan-meta.sh — 6 cases across exit codes 0/1/2 including the import variant and an outputs-only diff.
  • tf-plan-comment.sh — all-clean, mixed, plan-failed, an unknown env key (appended, not dropped), empty dir → exit 2. Four 241 kB plans render to a 59,645-byte body, inside the 65,536 cap with 5.9 kB headroom, with a truncation notice per stack. A triple-backtick inside plan text does not break the ~~~~ fence. The jq -Rs payload round-trips byte-identically.
  • The real plan-step and apply-step shell, extracted from the YAML and run against a stub terraform: init-failure leaves the init log in plan.txt (so the comment explains why rather than showing an empty diff); the untokened destroy exits 1 with nothing applied.
  • terraform fmt -check -recursive, offline validate across all five stacks, actionlint clean, every uses: SHA-pinned, scripts/ci/tf-plan-comment.sh fed real artifact layouts, scripts/skills-check.sh all green.

Two bugs found by reviewing the diff rather than running it

  • skills-check.sh reported >- as the if: condition for any job using a folded block scalar — so the generated reference would have stated something false. It now collects the block. (Three jobs here use folded if:.)
  • The comment upsert hid a failing gh. It looked the id up through gh api … | jq …. GitHub's default shell is bash -e {0}; pipefail is added only by an explicit shell: bash, which nothing in this repo sets. So a failed gh was invisible — jq succeeds on empty input, the id comes back empty, and the job posts a new comment every push instead of updating. Silent duplicates, green job. Split into two statements so the assignment carries gh's exit status; verified against a stubbed failing gh under bash -e, which now exits 1.

One deliberate coupling worth noting in review: apply needs the whole plan job, so a plan (state-backend) failure blocks all three applies. That is fail-safe — a broken plan tier means CI's view of the account is broken — but it does couple a never-applied stack to the apply path.

🤖 Generated with Claude Code

…ded apply

The service-account half of §14.2 has been live since #352: two federated
OIDC roles, zero repository secrets, plan on every PR and an unattended
apply on merge. Four gaps around it, closed here.

**The plan never reached the PR.** It went only to the run summary, so
reviewing an infra PR meant leaving the PR. A new `comment` job upserts
ONE sticky comment per PR by an HTML marker, carrying a per-stack
add/change/destroy table — destroy counts bolded, and a warning block
when any is non-zero — over collapsed per-stack diffs. Upserted, so a
ten-push PR has one comment and not ten. It is the only job in the file
with a write scope.

**The plan was not a required check, and could not become one.** The
workflow carried `paths:` filters, and a workflow a path filter skips
never reports, so a required check there would block every backend-only
PR forever. Replaced with the `detect`-job pattern `rust.yml` and
`frontend.yml` already use. Its push path FAILS SAFE: an absent, all-zero
or unreachable before-SHA reports "changed" rather than "unchanged",
because a wrongly-skipped plan is cosmetic while a wrongly-skipped apply
silently diverges the account from config until someone notices.

**"All our terraform" was three of five stacks.** The matrix is now a
list of `{key, dir}` objects, so `bootstrap/state-backend` joins the plan
tier — planned and never applied, since it owns the bucket its own backend
lives in. `bootstrap/organization` joins the credential-free `validate`
tier only: its one required variable is a root account email deliberately
absent from a public repo, and `terraform validate` evaluates no
variables, which is exactly why it fits there and cannot fit the plan
tier. Every matrix job now sets `name:` explicitly — left alone GitHub
would name it `plan (core, infra/terraform/envs/core)` and silently
un-protect `plan (core)`.

**The apply had no speed bump and left no record.** It now plans to a
file, shows it, guards it, and applies THAT file rather than letting
`-auto-approve` re-plan invisibly; the shown plan goes to the run summary.
`tf-destroy-guard.sh` refuses any non-zero destroy count unless the commit
message carries `ALLOW-DESTROY` — the repo squash-merges, so that means
the PR title, reviewed in the same diff as the destroy. A speed bump, not
a policy engine: it cannot tell a benign replace from losing Aurora, and a
replace trips it too. §14.2's prod-scoped apply role is still the real
remaining defence-in-depth.

Three helpers under `scripts/ci/` rather than heredocs, because a gate is
not trusted until it has been observed failing and a parser inside a
matrix job can only be exercised by pushing a commit. All three are
fixture-verified, including the guard observed RED on a real destroy and
failing closed on unparseable input.

Two bugs caught by reviewing this diff rather than by running it:

- `skills-check.sh` reported the block indicator `>-` as the `if:`
  condition for any job using a folded scalar, so the generated reference
  would have stated something false. It now collects the block.
- the comment upsert looked the comment id up through a pipeline,
  `gh api … | jq …`. GitHub's default shell is `bash -e {0}` and
  `pipefail` is added only by an explicit `shell: bash`, which nothing
  here sets — so a FAILING `gh` was invisible: jq succeeds on empty input,
  the id comes back empty, and the job posts a brand-new comment on every
  push instead of updating the existing one. Silent duplicates rather than
  a red job. Split into two statements so the assignment carries gh's exit
  status and `-e` aborts; verified against a stubbed failing `gh` under
  `bash -e`, which now exits 1.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@github-actions

github-actions Bot commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

terraform plan

f962239 · run log and full plans

env add change destroy
state-backend (plan only) 0 0 0
core 0 0 0
dev 0 0 0
prod 0 0 0

Planned with -refresh=false, so this is the config-versus-state diff and
not out-of-band drift. That is a security choice, not a speed one: a refreshing
plan reads secret values, and this role is reachable from any PR on a public
repository. Drift is caught at apply time, which refreshes fully.

…stroy warning

Reading the first real comment this posted (#360), a `state-backend` row
sitting beside `core`/`dev`/`prod` reads as "merging applies this". For
that stack it is exactly wrong: it is planned for drift detection and
never applied, because it owns the bucket its own backend lives in.

So the table marks it `(plan only)`, and the `[!WARNING]` block — whose
whole claim is "merging applies it unattended" — now skips plan-only
stacks. Their destroy count is still bolded in the table, because config
and state disagreeing about the state bucket is worth seeing; it just is
not about to happen on merge.

`PLAN_ONLY` has to be kept in step with the apply matrix by hand, which
the comment beside it says.

Verified over three fixtures: the clean case marks the row; a destroy on
`prod` still names prod in the warning; a destroy on `state-backend` alone
is bolded with zero warning blocks.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@athvin
athvin merged commit faf407a into main Oct 31, 2026
25 checks passed
athvin added a commit that referenced this pull request Nov 1, 2026
#365)

I made `plan (state-backend)`, `plan (core)`, `plan (dev)` and
`plan (prod)` required in #360's follow-up. The next non-infra PR — #359,
the agentic workflows — went unmergeable, with all four stuck on
"Expected — waiting for status to be reported", and the four contexts have
been removed from branch protection to unblock it.

The behaviour, stated exactly, because it is genuinely surprising:

  While a matrix job RUNS it reports one check-run per leg —
  `plan (core)`, `plan (dev)`, … — which look like perfectly good
  contexts. When the job is SKIPPED by its `if:`, GitHub reports a single
  check-run under the literal, uninterpolated name
  `plan (${{ matrix.key }})`.

So per-leg contexts never report at all on a PR that skips the tier, and a
required context that never reports blocks the PR forever — the same
failure mode as a `paths:` filter, which is precisely what this workflow's
`detect` job exists to avoid. I replaced one trap with another wearing a
different hat.

`fmt + validate (credential-free)` was fine throughout, and the contrast is
the diagnosis: it is not a matrix job, so it reports `skipped` under its own
name and branch protection accepts that.

The fix is a non-matrix aggregator, `terraform plan`, which `needs: plan`
and inspects `needs.plan.result` — the aggregate, `success` only if every
leg succeeded. It reports `skipped` when the tier is skipped, so it is
safe to require in the legs' place.

Two details in it:

- `skipped` is ACCEPTED. Exactly one thing produces it: a fork PR, which
  is issued no `id-token` and so cannot assume the plan role (the `plan`
  job skips itself for that reason). Treating it as failure would make
  every fork PR unmergeable — this same bug pointed the other way.
- anything unrecognised, including an empty result, FAILS. Verified
  against all five values `needs.*.result` can take.

Documented where the next person will hit it: the `ci-and-supply-chain`
skill now carries it as the third `name:`-is-a-context failure mode, and
the generated job table — which displays `plan (${{ matrix.key }})`
verbatim, i.e. the trap itself — gained a preamble line saying a context
containing `${{ matrix.* }}` cannot be required.

Nothing is added to branch protection here. That comes after this reports
green on `main`, which is the only safe order.

One bug caught while verifying, in the gate's own message: a backticked
word inside a double-quoted shell string is command substitution, so the
first draft ran `validate` and printed its empty output in place of the
word. Single-quoted now.

Co-authored-by: bmoore813 <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants