Back to Terraform

Capstone D: Operate a Governed Multi-Environment Platform

November 6, 2026 Wasil Zafar 42 min read

Integrate isolated state, versioned modules, short-lived pipelines, policy and operational evidence

Table of Contents

  1. Define Teams, Environments and State Ownership
  2. Promote Small Versioned Modules Across Environments
  3. Use OIDC and Protect the Reviewed Plan
  4. Enforce Policy and Cost Review at the Actual Gate
  5. Prove Secret Boundaries Rather Than Promising No Secrets in State
  6. Operate Drift, Incidents and Decommissioning
  7. Submit a Reviewable Platform Evidence Pack

Define Teams, Environments and State Ownership

A capstone is judged by what a stranger can verify. This one builds a platform a small company could actually run: one product, three environments, four accounts, ten roots and six deliverables. Nothing in it is exotic. The difficulty is that every claim has to survive a reviewer who was not in the room when it was made.

Choose one cloud, one region and one provider line, then stop negotiating. AWS is the reference, with Terraform 1.17.1 and hashicorp/aws 6.72.0. A second cloud doubles the identity, policy and cost evidence without testing a skill this project is about. Record the choice and the region in the scope file before the first resource exists.

An account is the only boundary that survives a stolen credential. The platform account holds state, DNS and the identity broker. Dev, stage and prod are separate accounts, so a principal in one cannot read another's resources without an explicit trust. A folder named prod has never slowed an apply.

An environment is an approval regime, not a path segment. Dev is disposable, runs on synthetic data and needs no approval. Stage is production-shaped, keeps masked data and needs one reviewer. Prod needs two reviewers, a change window and a tested rollback. Those rules belong to the pipeline and the account; the directory name only points at them.

Three teams own the surfaces, and one of them owns the state. Ownership is per root, not per repository, because the repository is a review tool and the root is the change unit. The table below is the first deliverable: every surface has a team, an approver and an on-call rotation.

SurfaceAccountable teamApproves productionOn call
Bootstrap, state, DNS, policy packplatformplatform lead plus securityplatform
Network root, per environmentplatformplatform plus productplatform
Data root, per environmentdatadata owner plus platformdata
Service root, per environmentpaymentsservice owner plus platformpayments

Ten roots, one state key each, and a fixed apply order. Bootstrap exists once. Network, data and service repeat in each environment, because their lifecycles differ: quarterly, monthly under protection, and several times a day. Ten thin roots is more files and less reasoning than four thick ones, which is the right trade for a platform team.

RootAccountState keyApply identityApproval
bootstrapplatformplatform/bootstrapbootstrap role, human break-glasstwo reviewers
networkdev, stage, prodenv/networkone network role per environmentnone, one, two
datadev, stage, prodenv/dataone data role per environmentnone, one, two
servicedev, stage, prodenv/serviceone service role per environmentnone, one, two

The state bucket is the most sensitive object the platform owns. It is versioned, encrypted with a customer managed key, reachable only over TLS, closed to public access, and guarded by prevent_destroy. A root's apply role gets object access to its own key and nothing else. No workload root may administer the bucket, because the bucket is what proves every other resource existed.

Reading state is a data-sharing decision. A state object holds every attribute the provider returned, including values that were never outputs and values marked sensitive. Consumers therefore receive published values as variables, and only the owning team and its apply role read the object. The promotion record names each value that crosses a boundary and who may change it.

CLI workspaces are not an isolation mechanism. A workspace shares the backend, the credentials and the provider configuration with its neighbours, so selecting prod is one flag away from selecting dev. Use workspaces for short-lived review environments, and use accounts for everything that carries customer risk.

Run the stolen-token test on paper before you build. For each role, write what it could change if it leaked tonight. If any role reaches two environments, or a workload role can delete the state bucket, the boundary is already broken and no diagram will save it.

Define Teams, Environments and State Ownership
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    R["Change request
queue, bucket or ingress rule"] --> T{"Which team owns
the outcome?"} T -- "platform" --> P["Platform account
bootstrap, DNS, state"] T -- "product" --> E{"Which environment
accepts the risk?"} E -- "dev" --> D["dev account
no approval, synthetic data"] E -- "stage" --> S["stage account
one reviewer, prod-shaped"] E -- "prod" --> PR["prod account
two reviewers, change window"] P --> L{"Same lifecycle and
on-call as its neighbours?"} D --> L S --> L PR --> L L -- "yes" --> ONE["One root
network, data or service"] L -- "no" --> SPLIT["Separate roots
one state key each"] ONE --> K["State object in the
platform account"] SPLIT --> K K --> G{"Could a stolen token
reach a second account?"} G -- "yes" --> BAD["Boundary failed
redesign before apply"] G -- "no" --> OK["Register signed
roots may be built"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class R,P,PR primary; class D,S,ONE,SPLIT,K secondary; class T,E,L,G warn; class OK ok; class BAD danger;

Figure 1 asks the four questions in the order a reviewer should ask them. Which team owns the outcome, which environment accepts the risk, whether the lifecycle matches its neighbours, and where the state object lands. A "yes" at every step produces one root; any "no" produces a split, even when the resources obviously talk to each other.

The containment view is the one to pin above the desk. Figure 2 nests the organization, the accounts, the environment band and the roots, then shows where state really lives. A boundary that exists only in a diagram is a preference; this one is drawn as the construction it is meant to be.

Accounts, environments and roots, with state owned by the platform account Three environment accounts for dev, stage and prod each hold network, data and service roots. Every root writes one state object to the platform account, which holds a versioned and encrypted bucket with one key per root. A crimson strip warns that two environments in one account turn the environment band into a label. One organization, four accounts, ten state keys The account is the credential boundary. The environment is the approval regime. The root is the change unit. dev account — no approval network root dev/network data root dev/data service root dev/service stage account — one reviewer network root stage/network data root stage/data service root stage/service prod account — two reviewers network root prod/network data root prod/data service root prod/service State bucket — platform account versioned, customer managed key, TLS only public access blocked, destroy guarded One key per root — ten objects, ten locks An apply role reaches its own key and no other. No workload root may administer this bucket. state and lock If dev and prod share one account, the environment band is a label. A leaked pipeline token then reaches both, and only the review process disagrees.

Read the picture outward-in and the next failure is obvious. One shared account for dev and prod makes the environment band a label, and the same token reaches both. The state bucket sits outside every workload account for the same reason: a teardown must not delete the record of what it destroyed.

Promote Small Versioned Modules Across Environments

Small means one reason to change. A network module owns subnets, routes and zones; a data module owns the table, bucket and key; a service module owns compute, queues and its role. Each fits on a screen or two, has typed inputs, and returns outputs named for their meaning. A module that needs an environment name inside its logic is two modules pretending to be one.

The module is the unit of promotion, not the directory. A release goes to dev, then stage, then prod, and the same version string appears in all three roots. Differences between environments are values in a tfvars file, so the diff a reviewer reads is values rather than duplicated code. That is what makes a release reviewable in three places at once.

Pin every layer that can change a plan. "The same configuration" is not the same plan when the producer moves, so the version record covers the tool, the provider, the modules and the CI image. The lock file is committed beside the configuration, because a resolved provider is part of the input.

LayerPinned valueWhere it is recordedWhat moves if it is loose
Terraform CLI1.17.1CI runner image and version fileplan shape and provider protocol
AWS provider6.72.0required_providers plus the lock fileattribute behaviour and defaults
Module setone release per environmentmodule call constraint and release tagthe input contract between roots
CI runnerimage digestpipeline definitionthe producer of the reviewed plan
Policy packtagged releasepolicy repositorythe decision the reviewer saw

A version constraint is a promise about compatibility, not a formality. Modules take a constraint on the minor version, the provider takes an exact pin with a committed lock file, and a major bump is a new integration test rather than a find-and-replace. The constraint is what lets three environments share one release without sharing one upgrade date.

A private registry is a distribution decision with an operational cost. HCP Terraform's private registry gives you versioned modules, a changelog and access control; Git tags over HTTPS are the self-managed fallback. Either way, the pipeline needs a credential that can read the source, the repository needs a compatibility policy, and a breaking input needs a deprecation window rather than a rename.

The promotion gates have the same shape in every environment and get stricter with risk. Dev proves the module works. Stage proves it works in a production-shaped account with the same version. Prod proves the change was reviewed against evidence from both.

Gatedevstageprod
Module versionnewest releasesame version applied in devsame version applied in stage
Plan evidencesaved plan and digestdigest compared with devdigest plus change window
Policyadvisory for new rulesmandatorymandatory, no standing override
Costestimate recordedreview above the thresholdowner approval above the threshold
Approvalsnoneone reviewertwo reviewers, one from platform
Rollbackrebuild from the previous releaseprevious versionprevious version plus a tested plan

A hotfix is a new version, not an exception. If prod runs a patch that stage never saw, the next promotion silently reverts it or reintroduces the bug it fixed. The skew is the incident. Release forward, run the gates, and let the register show one version in three places.

Figure 3 is the promotion path with the branches that make it look successful while it is not. A missing lock file lets the provider move under a pinned configuration. An unpinned constraint lets one environment take a release nobody applied elsewhere. A registry credential that works in one pipeline makes init fail in another, which is a gate that depends on luck.

Promote Small Versioned Modules Across Environments
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    T["Module change
one repository, one test suite"] --> V["Release vX.Y.Z
changelog and compatibility note"] V --> DV["dev root
constraint pin"] DV --> DP{"Plan clean and
policy pass?"} DP -- "no" --> FIX["Fix in the module
cut a new release"] FIX --> V DP -- "yes" --> DA["Apply dev
no approval"] DA --> ST["stage root
same version"] ST --> SP{"Plan diff matches
the dev evidence?"} SP -- "no" --> SKEW["Stop
the environments have diverged"] SP -- "yes" --> SA["Apply stage
one reviewer"] SA --> PD["prod root
same version"] PD --> PP{"Lock file committed
and provider pinned?"} PP -- "no" --> DRIFT["Provider moves
prod plan differs from stage"] PP -- "yes" --> PA["Apply prod
two reviewers"] PA --> OK["One version recorded
in three registers"] PA -.->|"hotfix only in prod"| HOT["Version skew
next promotion overwrites it"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class T,V,PA primary; class DV,ST,PD,DA,SA secondary; class DP,SP,PP warn; class OK ok; class SKEW,DRIFT,HOT,FIX danger;

Two practices keep the register honest. The pipeline records the module version, the provider version and the plan digest in one row per environment, so three rows can be compared without opening a terminal. A repository check fails when a module call has no constraint. Both are cheap, and both prevent the slow divergence that turns "same module everywhere" into a story.

Use OIDC and Protect the Reviewed Plan

The pipeline should hold no cloud key at all. A job asks its CI provider for a short-lived OIDC token, the cloud validates the issuer, the audience and the subject, and returns a role session measured in minutes. Nothing long-lived sits in the repository, and revoking access is a trust-policy change rather than a key hunt.

Trust the repository and the environment, not the pipeline's display name. The subject condition names the repository plus the protected environment or ref, and the audience names the cloud's token service. A wildcard subject turns every fork and every branch into a trusted caller, which is the same as having no condition.

Plan and apply are different jobs with different reach. The plan reads, locks and writes an artifact; the apply writes resources and state. One role for both means the review has no enforcement point, because the job that produced the plan can also finish it.

CapabilityPlan identityApply identity
State objectread, plus write the lock objectread and write the state object
Cloud APIsread and list onlycreate, update and delete on one root
Plan artifactwrite the saved planread the approved plan
Approvalcannot approveverifies digest and expiry
Lifetimeone jobone job, minutes
Trust conditionrepository plus environmentrepository, environment and protected ref

The plan is the artifact under review, so the review has to name it. The plan job saves the plan, hashes it, and records the digest beside the commit and the environment. An approval is valid only for that digest and expires with the change window. The apply job verifies both before it configures a provider, so a re-plan or a stale approval fails before anything is touched.

A saved plan can contain values in clear text. Treat it as a secret artifact: encrypted at rest, readable by the named reviewers and the apply role, retained for the rollback window and then deleted. Attaching it to a ticket publishes everything the plan read, including values that never appear in a diff.

Two execution models satisfy the same requirement. A hosted platform gives you remote runs and a policy engine; a custom pipeline gives you control and asks you to build the custody yourself. The requirement does not change: the approved bytes are the applied bytes.

ConcernHCP TerraformCustom CI
Where the plan runshosted runners or your agentsyour runner
Identityworkspace credentials or dynamic provider credentialsOIDC to your cloud
Policynative policy at init and plan, or Sentinel and OPAa policy engine over plan JSON
Approvalrun approval and policy overridespull request plus a digest check
Plan custodyplatform-managedyour encrypted bucket and retention
Operational costsubscription and vendor dependencyyou own the runner, storage and audit trail

Figure 4 separates the three things a reviewer keeps confusing: who may plan, who may approve and who may change. The plan role reads and locks, the reviewer decides, and the apply role writes one root. Collapsing any two turns the pipeline into an approval-shaped formality.

OIDC plan and apply path, with approval bound to the plan digest A repository commit reaches a plan job that authenticates with a short-lived OIDC token, assumes a read-only plan role, and writes a saved plan with a digest. A policy and cost gate reads the plan, a reviewer approves the digest, and a separate apply job authenticates again to assume a narrow apply role that changes one root. A crimson strip lists long-lived keys, re-planning after approval and one broad role as rejected shortcuts. Nothing long-lived, nothing re-planned The approval names a digest. The apply verifies it before the provider is configured. Repository commit and environment protected branch Plan job OIDC session no stored key Plan role read and lock writes no resource Saved plan SHA-256 digest encrypted at rest Policy and cost decide on plan JSON unknown goes to review Review approves the digest with an expiry Apply job OIDC session verifies digest first Apply role one root per session write scope only Cloud account state and resources Rejected: a stored access key, a re-plan inside apply, one role for every root. Each one leaves a green pipeline and no way to prove which bytes a human approved. The plan role can read a whole environment, which is why its session is short and its logs are retained. The apply role can write one root, which is why a stolen token reaches one resource set and one state key.

The two shortcuts are worth naming because both look like governance. A stored access key makes every trust condition irrelevant. Re-planning inside the apply job turns an approved digest into a filename, and the change that lands is the one nobody read. The second is more common, because it is usually added to fix a stale plan.

Enforce Policy and Cost Review at the Actual Gate

A gate is the step that can stop the apply. Not a dashboard, not a weekly report, not a tag audit the next morning. If a rule fails and the pipeline still reaches apply, the rule is advice with a policy file attached.

ControlRuns whereCan stop the applyEvidence left
Static scan of configurationCI, before planyes, if it exits non-zeroscan report and commit
Plan policyCI or platform, on plan JSONyes, at mandatoryrule id, address, decision
check blockafter applyno, warning onlycheck result in the plan
Cost thresholdCI, on the estimateyes, as a required reviewerestimate, price date, owner
Budget alertcloud billingno, laggingnotification record
Tag auditafter applyno, detectioninventory query

Choose the framework by where the decision has to run. Terraform's native policy evaluates at init and at plan, and again after apply, but only on the platform that runs it. In a custom pipeline the equivalent gate is a policy engine reading the plan JSON and exiting non-zero. Pick one home per rule: the same intent written twice drifts, and the drift is invisible until an auditor asks which copy was enforced.

Unknown is not a pass. A value that exists only after apply, such as a generated ARN or an assigned CIDR, is unknown at plan time. The rule must say whether that blocks or waits, and the answer should be recorded per rule rather than decided by whoever reads the output. A policy that treats unknown as compliant fails open on exactly the changes it cannot see.

Cost review belongs at the same gate, with the owner in the loop. An estimate prices the planned change at list price; the invoice is what the company pays, including discounts, transfer and resources nobody wrote in Terraform. Put the estimate in the plan record, compare the monthly delta with a threshold, and require the cost-centre owner to approve in the pull request when the delta crosses it.

DecisionInputGateOwner
Delta under the thresholdestimate for the saved plannone, recordedservice owner
Delta above the thresholdestimate with usage assumptionsrequired approval in the pull requestcost-centre owner
Unknown usageestimate treated as a floortreated as above the thresholdcost-centre owner
Invoice differsbilling datamonthly review, not a gatefinance and platform

A rule with no owner is edited by whoever it blocks. Record the rule author and the exception approver beside every rule, and version the policy pack like code. A rule that anyone can change is a suggestion; a rule with a review and a test is a control.

A budget alert is a backstop, never an approval. It reacts to spend that has already happened, often hours or days later, so it belongs in the operations section rather than in the pull request. The gate is the reviewer who sees a number and an owner before the change lands.

Exceptions are decisions with a clock. Scope the exception to an address, name a team rather than a person, state the compensating control, and set an expiry. Store the register in version control and validate it in CI, so an expired entry makes the original finding return automatically. Break-glass is the same record with an incident ticket and a retrospective approval.

Post-apply checks detect; they do not prevent. The check block runs after Terraform has acted and a failed assertion is a warning, and a budget notification arrives after the spend. Record both as detection in the control matrix, because counting them as gates is how a control document becomes fiction.

Prove Secret Boundaries Rather Than Promising No Secrets in State

"No secrets in state" is a promise nobody can keep. State stores the attributes a provider returns. Marking a value sensitive hides it from the CLI and from a diff, not from the state object, which is a JSON document in a bucket. A platform that claims otherwise has confused the display with the storage.

What you can prove is narrower and more useful: a named value is absent from a named set of artifacts. Use a canary — a fake credential created only for the test — apply it in dev, then search the state object, the saved plan, the CI log, the module outputs and the error path. Record where you looked and what you found. That is evidence; a sentence in a design document is not.

Four patterns move a secret out of state, in descending order of strength. Reference a secret that lives elsewhere and pass only its ARN or name. Use a write-only argument where the resource supports one. Use an ephemeral resource whose value exists only for the run. Generate the secret outside Terraform and let rotation belong to the secret manager. Each pattern has a different residual risk, and the matrix records it.

SecretPatternWhat state holdsRotation owner
Database passwordwrite-only argument plus version companionno value, only the version counterdata
Third-party API keyreference to a secret manager entrythe ARN and metadataservice
Short-lived tokenephemeral resource used during the runnothing after the runplatform
Legacy resource passwordmanaged argument, no write-only supportthe value in plain textdata, with retention

Write-only arguments need their version companion. The value is accepted at apply and not stored, but Terraform cannot see that the secret changed. The companion version argument is what triggers an update, so rotation means incrementing the version, not editing the secret. Without it, a rotated password looks like no change at all.

Rotation is part of the boundary, not an afterthought. A secret that never rotates is a permanent credential, whatever the storage pattern. Write the rotation owner and cadence into the matrix, and test one rotation during the capstone rather than trusting that the schedule works.

Some persistence is unavoidable, and hiding it is the real failure. A resource without write-only support stores the value, a provider may echo it in an error, and a data source may return a secret the configuration never declared. Document each case, restrict the key that protects it, shorten retention, rotate on a schedule, and name an owner.

SurfaceWhy it leaksControlProof
State objectevery attribute after applycustomer managed key, bucket policy, narrow rolecanary search returns nothing
Saved planknown values and data resultsencrypted artifact, short retentioncanary search returns nothing
CI logsprovider errors and debug outputdebug mode off, masked variableslog search returns nothing
Module outputsoutputs are copied into statereferences only, no secret outputsoutput review
Error messagesa failing argument can echo a valuecurrent provider, reported failuresa deliberate failure test

State access is the secret boundary that matters most. A team that can read the bucket can read every attribute of every root it can reach, so the KMS key policy and the bucket policy are the control, not the absence of a secret in the configuration. Grant object access per key, never list access to consumers, and reserve break-glass reads for a named human with a record.

Publish nothing that came out of state. The evidence pack carries the canary result, the matrix and the location of the search, never the state object or the plan file. Redaction is part of the deliverable, because an evidence pack is copied, attached and forwarded.

Operate Drift, Incidents and Decommissioning

Drift is a fact; ownership is the decision. A scheduled plan per root with detailed exit codes turns "is anything different?" into a status: 0 for no change, 2 for a diff. Running it on a schedule is what turns a console surprise into a ticket with a timestamp and an owner.

Classify before you reconcile. The interesting question is not what changed but whether the change should survive. Restoring intent, adopting reality and escalating to an incident are three different responses, and each one leaves different evidence.

ObservationLikely causeDecisionAction
One attribute differs, owner knowna deliberate fix during an incidentadopt or restore, owner's callcodify the value, or apply the root
A resource exists that no root declaresmanual creationrestore or importremove it, or add an import block
A protected resource is gonedeletion outside Terraformincidentrestore from backup, then reconcile
The same diff returns every daya controller rewrites the attributeadopt with a documented exceptionrecord the drift and who owns it

A console edit is the cheapest drift test you can run. In stage, widen a security group rule by hand, wait for the scheduled plan, and follow it. The expected sequence is a diff in the network root only, an owner decision, an apply that restores intent, and a no-op plan afterwards. A diff in another root means the change crossed a boundary the matrix said it could not.

Recovery ends with a no-op plan, not with a working service. A service that answers again while a root still shows a diff is a recovery with an untreated cause. Reconcile the root that drifted, then confirm the other roots still plan no change, because a fix that reaches the bootstrap or another environment is a different change with a different reviewer.

A failed apply is a state question before it is a code question. Terraform may have created some resources before the provider refused the rest, and the state now records a partial result. Read the plan again, import anything the provider created without recording, remove anything the configuration no longer declares, and apply. -target hides the remainder rather than repairing it, and force-unlock returns the lock, not the fix.

SymptomFirst checkAction
Access denied partway throughthe caller identity and the policy on the failing actionfix the role, re-plan, apply
Quota exceededthe service quota in that accountrequest an increase or reduce the change
Lock held by a job that is gonethe lock object and the job historywait for expiry, then unlock with a reason
A resource exists but is absent from statethe apply log for a provider error after creationimport the object, never recreate it
Plan is clean, apply fails on a valuea value that changed between plan and applyre-plan, re-approve, apply

Break-glass is a path, not a bypass. A time-boxed override for an incident is legitimate when it is recorded at use, approved retrospectively within a day and reviewed weekly. The record is the whole difference between an emergency and an unreviewed change.

Decommissioning is an ordered inventory, not a destroy command. Every row has an owner and a verification, because "destroy everything" is not a step anyone can check. Remove protection in a reviewed change, destroy dependents before dependencies, and archive the final state before the bucket goes.

OrderObjectOwnerVerified by
1CI trust and test callersplatformthe old subject can no longer assume a role
2Service rootspaymentsdestroy plan shows zero to add
3Data roots, protection removed firstdatathe plan states the lifecycle change
4Network rootsplatformno dependent root remains
5Open policy exceptionsplatformthe register shows none active
6Retired module versionsplatformno root references the tag
7State archive, then the bucketplatformmanifest count and final object list

Figure 5 puts the declared and observed states side by side, then follows a failed apply to reconciliation. The left panel is what the last apply recorded; the right is what the scheduled plan found. The bottom band is the second incident shape, where the failure is partial rather than external.

Declared and observed state for drift, with a failed-apply recovery path The left panel shows the state recorded at the last apply. The right panel shows what a scheduled plan found after a console edit, including a wider ingress rule and an exit code of two. The bottom band follows a failed apply where some resources were created before a denial, through re-planning and import or removal to a no-op plan, with target flags and forced unlocks marked as false fixes. What Terraform recorded, and what the next plan found Drift is detected by a plan, classified by an owner and closed by a no-op plan. Declared at the last apply Ingress rule: the approved source range Three subnets, two routes, one key Two approvals recorded before the apply Plan after apply: no changes The state object is the record of this shape. Nothing here says the cloud still matches it. Observed at detection Ingress rule: a wider range added by hand Three subnets, two routes, one key No approval covers the console edit Plan after detection: exit code 2 One root differs, and only one. That is the boundary holding while the cloud moved. plan Failed apply: partial state, then reconciliation Apply stops denial after creates State holds the created subset Re-plan shows the remainder Import or remove the stragglers Apply again then exit 0 Targeting one module hides the remainder. Force-unlock returns the lock, not the fix. A partial state is a normal outcome. An unrecorded one is the incident.

Figure 6 turns the same work into evidence. Detection, classification, decision, reconciliation and verification each produce one artifact, and the loop closes only when the scheduled plan reports no change. A recovery that exists only in a chat thread cannot be reviewed and cannot be repeated.

Operate Drift, Incidents and Decommissioning
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','signalTextColor':'#132440','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    S["Scheduled plan
every root, every day"] --> E{"Detailed exit code"} E -- "0" --> N["No change
record the timestamp"] E -- "2" --> C["Diff found
name the root"] C --> Q{"Who made the change
and should it survive?"} Q -- "console edit, unwanted" --> R["Restore intent
apply the root"] Q -- "emergency fix, keep" --> A["Adopt reality
codify, then plan"] Q -- "unknown actor" --> I["Incident
security review first"] R --> V["No-op plan
exit 0"] A --> V I --> V V --> D["Record the timeline
actor, change, recovery"] E -- "1" --> X["Plan failed
state or credential problem"] X --> Y["Read the error
confirm the lock holder"] Y --> Z{"A partial apply
created resources?"} Z -- "yes" --> W["Import or remove
then re-plan"] Z -- "no" --> Y2["Fix the cause
credential or quota"] W --> V Y2 --> V V -.->|"no evidence"| U["Unreviewable recovery
the same incident returns"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class S,C,X primary; class R,A,I,V,W,Y2 secondary; class E,Q,Z warn; class N,D ok; class Y,U danger;

The timeline is the part auditors read. It names the actor, the change, the detection time, the decision and the recovery, in order. A paragraph written later from memory is a story with a timestamp, not a record.

Submit a Reviewable Platform Evidence Pack

Six deliverables, one index, and no claim without an artifact. The pack is what the reviewer opens first and what the next team inherits. Each row has an acceptance condition that can fail.

IDDeliverableAccepted when
D1Environment and ownership registerevery root has one account, key, role, approver and cost centre
D2Module release recordone version per environment, a changelog and a committed lock file
D3Identity and plan custody recordtrust conditions, plan digest and approval binding for each environment
D4Policy and cost decision logpass, fail, unknown and exception outcomes with rule versions
D5Secret boundary matrixthe canary is absent from state, plan, logs and outputs
D6Operations reportone drift, one failed apply, an ordered decommission and final no-change plans

Independent verification means someone else runs the checks. The verifier did not build the platform, does not approve the production change and can read the evidence without a walkthrough. If the author has to explain a step, the step is not evidence yet. The verifier signs the index, not the author's summary of it.

The closing argument is a no-change plan in every surviving root. Bootstrap, stage and prod return exit code 0, run after a quiet period rather than immediately after the last apply, and the digests are recorded beside the date. A destroyed environment has no plan to show, which is why the teardown comes last and its inventory is the evidence for what is gone. A plan that returns 2 during sign-off means the platform is still moving while the reviewer is reading.

Redaction is part of the deliverable. Account identifiers, state objects, plan files and secret values never enter the pack. The index records what each artifact contains, who may read it and how long it is kept, so a forwarded copy does not become an incident.

ArtifactContainsSensitivityRetention
Plan digest and policy resultno valuesinternalreview window
Approval recordactor, digest, expiryinternalaudit period
Canary resulta fixed string and the search locationsinternalaudit period
Drift timelineactor, change, recoveryinternalaudit period
State archiveevery attribute in the rootrestrictedper policy

A platform that cannot be handed over is not finished. The evidence pack is the handover: a register someone can act on, a release record someone can repeat, and a plan that proves the platform has stopped moving long enough to be accepted.

Capstone

Platform acceptance review

Status: design-only here. No cloud account or credential was used to produce this capstone, and the steps below were not executed against a live platform. Versions: Terraform CLI 1.17.1 and hashicorp/aws 6.72.0. All account identifiers, state keys and role names are chosen in D1; nothing in the evidence pack should be copied from this page as a real value.

Prerequisites. Four sandbox accounts or subscriptions (platform, dev, stage, prod) with a provider account allowlist, one region, permission to manage IAM, S3, KMS, budgets and the services in scope, a CI system that can issue OIDC tokens, and two named people: a builder and an independent verifier. A production change also needs two approvers, and the verifier is not one of them.

Deliverables to attach. D1 ownership register, D2 module release record, D3 identity and plan custody record, D4 policy and cost decision log, D5 secret boundary matrix, D6 operations report. The review is not complete until every acceptance row has an artifact behind it.

StageWhat you runPass condition
Preflightverify CLI and provider versions; plan the bootstrap rootversions match the record; only expected creates
Identityassume the plan role, then the apply role, from CIeach role fails outside its environment
Modulespromote one release from dev to stage to prodthe same version string in three registers
Gateplan a change with a deliberate violationthe gate exits non-zero; unknown routes to review
Secretsapply a canary in dev; search state, plan and logsthe canary is absent from every named artifact
Driftwiden a rule in the stage console; wait for the planone root differs, then a no-op plan
Failureremove one permission during a dev applypartial state reconciled, no targeting
Decommissiondestroy dev in the recorded orderinventory empty, state archived
Verifythe verifier repeats three checks unaidedall three pass without the author
  1. Record the baseline. Write the region, the account allowlist, the root inventory and the cost ceiling into D1, and confirm the versions in the pipeline match the record. A baseline with a missing root or an unowned key fails before anything is built.
  2. Build the bootstrap root alone. State bucket, key, lock, DNS zone and the trust policy for the pipeline. Apply it with a human identity and a second reviewer, then stop. No workload root may be able to change it afterwards.
  3. Apply the environment roots in order. Network, then data, then service, in dev first. Each root reads its own state key and changes resources only in its own account; the state object itself lives in the platform bucket, which no workload root can administer.
  4. Cut one module release and promote it. Apply the release in dev with no approval, then in stage with one reviewer, then in prod with two. Record the version, the plan digest and the approver in D2 at each step; the prod row must name the stage plan it was compared with.
  5. Prove the identity boundary. Attempt to assume the prod apply role from a dev job and record the denial. Attempt an apply with the plan role and record the refusal. A trust policy that accepts either is a wildcard with better formatting.
  6. Prove the gate. Plan a change that violates one mandatory rule, then a change whose value is unknown at plan time. Record the non-zero exit for the first and the review decision for the second; a green unknown result fails the review.
  7. Prove the cost gate. Estimate the same plan twice, once without usage assumptions and once with them, and record both numbers and the price date. Cross the threshold deliberately and record the owner approval in the pull request.
  8. Prove the secret boundary. Create a canary credential in dev, apply it through the strongest available pattern, then search the state object, the saved plan, the CI log, the module outputs and the failure message. Fill in D5 with where you searched and what you found.
  9. Exercise drift. Widen one ingress rule in the stage console, then wait for the scheduled plan rather than triggering it by hand. Record the diff, the owner decision, the restoring apply and the no-op plan that closes it.
  10. Exercise a failed apply. In dev, remove one permission that a later resource needs, after planning, then apply. Record the partial state, the failing action, the re-plan and the import or removal that reconciles it. Do not use targeting to finish the job.
  11. Decommission dev in order. Remove protection in a reviewed change, destroy the service, data and network roots in that order, close open exceptions and archive the final state. Confirm with a tag inventory that returns nothing.
  12. Hand over to the verifier. Give the verifier the index and nothing else. They repeat the role denial, the unknown-policy decision and the canary search, then sign D6 with the date and the no-change plans for the seven surviving roots.

Expected observation. Plan and apply roles fail outside their own environment and root, the promoted module shows one version in three registers, the violating plan never reaches apply, the unknown value is reviewed rather than passed, and the canary appears in none of the searched artifacts. The drift edit produces a diff in one root and a no-op plan after recovery, and every surviving root returns exit code 0.

Failure checks. The review fails if a role reaches a second environment, if prod runs a module version stage never applied, if an approval does not name a plan digest, if an unknown policy result is recorded as a pass, if the canary appears in state, plan, logs or outputs, if drift is fixed by a second console edit, if a failed apply is completed with a target flag, or if any surviving root still plans a change at sign-off.

Cost boundary. Record a monthly ceiling in D1 before the first apply and bound the drivers: one region, three environments, one NAT gateway per environment at most, short log retention, one key per root and no cross-region replication. Budget notifications at half and at the ceiling are backstops, not gates. Stop at the ceiling, not at the first surprising invoice, and destroy dev as soon as its acceptance row passes.

Cleanup. Revoke the CI trust and the test callers, destroy the service, data and network roots in that order, remove delete protection in a reviewed change rather than by hand, export and delete the log groups, and archive the final state before the bucket. Confirm with a tag-based inventory query and a final plan per surviving root; a bucket that refuses deletion because of its guard is working as designed.

Evidence to keep. D1 through D6, the plan digests, the approval records with expiry, the policy decisions for pass, fail and unknown, the estimate with its price date and owner approval, the canary search result, the drift timeline, the failed-apply reconciliation, the decommission inventory and the final no-change plans for every surviving root. Keep the evidence; destroy the credentials.

References. S3 backend and lock file, ephemeral resources, state and sensitivity, policy enforcement in HCP Terraform, OIDC between GitHub Actions and AWS, AWS IAM identity providers, Infracost documentation, AWS provider 6.72.0.

A governed platform is a set of owned surfaces with proof at each one. The project passes when a reviewer can name the owner of every root, replay a module release from its version and digest, read a policy decision and see which gate stopped the change, search for a canary and find nothing, and watch a drift incident close with a no-op plan. That is a stronger result than a green apply, and it is the result this capstone asks you to deliver.