Back to Terraform

Plan JSON and Machine-Readable Automation Contracts

November 6, 2026 Wasil Zafar 34 min read

Build consumers that handle unknown values, sensitive data, exit codes and evolving schemas correctly

Table of Contents

  1. Choose the Correct Machine-Readable Interface
  2. Interpret Resource Actions and Unknown Values Explicitly
  3. Sensitive Metadata Does Not Sanitize JSON Values
  4. Handle Exit Codes, Run States and Partial Apply
  5. Write a Consumer Contract with Versioned Fixtures

Choose the Correct Machine-Readable Interface

A machine-readable interface is a promise about shape, not a flag. Terraform publishes several, and each answers a different question. An automation that picks the wrong one usually looks correct in a demo and misreads its first real plan.

Terraform draws a hard line between a document and a stream. A saved plan rendered as JSON is one complete object with a versioned schema. The -json flags on plan and apply produce a stream of line-delimited UI events, which is a different contract with a different purpose.

The plan document is the one a reviewer or policy gate needs. It carries the proposed actions, the values after the change, the markers for values still unknown, and the sensitivity map. It also records whether the plan is applyable and complete, which a stream of progress messages cannot tell you.

A saved plan is the price of admission. The document comes from showing a plan file created with the output flag; a speculative plan is never written, so there is nothing to inspect afterwards. That single constraint decides most review architectures, and it is why the plan artifact is the pivot in the CI/CD workflow.

State JSON answers a different question. Showing a state snapshot returns the values that exist now, with no proposed change and no action vocabulary. It is the right input for inventory, drift baselines and output consumers, and the wrong input for approval.

Streaming events are for progress, not for decisions. Each line is a self-contained object with a type, a timestamp and a message; resource events can interleave when parallelism is above one. The first message declares the UI schema version, which is not the same version as the plan document.

A stream is lossy by design. Planned change events name resources and actions but carry no after values, which live only in the plan document. A consumer that tries to make a value decision from the stream will either invent the value or silently skip it.

Outputs are a state read. The output command with JSON enabled returns root module outputs from the last applied state as a stable object. It does not know what the next plan intends, and before the first apply it has nothing to say.

The version numbers alone prove these are separate contracts. In Terraform 1.17.1 the plan document reports format version 1.2 while the state document reports 1.0. They evolve on independent schedules, so one parser should never be reused for both without a version check.

The -json flag also changes the input contract. On plan and apply it implies non-interactive input, so an unassigned root variable becomes an error instead of a prompt. Automation that relied on a prompt was never automation; it was a human with a long command.

A stream can be watched while the document is kept. The practical pattern is to run the plan with both output modes: a plan file for the gate, and a JSON stream for the log. The stream tells the operator that work is happening; the file is what the gate actually reads.

Choose the Correct Machine-Readable Interface
%%{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
    A["Automation question"] --> B{"What must the consumer know?"}
    B -->|"the proposed change"| C["plan -out saves a plan file"]
    C --> D["show -json renders one plan document"]
    D --> E["Actions, after values,
after_unknown, checks"] E --> F["Policy, review, approval"] B -->|"live progress"| G["plan -json or apply -json"] G --> H["One JSON object per line"] H --> I["Counts, hooks, diagnostics"] G --> J["No after values:
not a plan document"] B -->|"applied values"| K["show -json state
or output -json"] K --> L["Values from the last apply"] D --> M["Artifact may contain secrets"] 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 A,B,E primary; class C,D,G,K secondary; class F,I,L ok; class J,M warn;
Three paths, three contracts The plan document path saves a plan file, renders it with show -json, and feeds policy or review. The streaming path emits one JSON object per line for counts, hooks and diagnostics, without after values. The state path reads applied values from state or the output command. Three paths, three contracts Only the first one is a reviewable document A โ€” proposed change plan -out opaque plan file show -json plan document actions and values after_unknown, checks policy and review the decision input format 1.2; may hold secrets B โ€” live progress plan -json apply -json one object per line version message first counts and hooks diagnostics operator display never the value source no after values, no applyable flag C โ€” applied values last apply writes state output -json show -json state real values root outputs downstream scripts state version 1.0 A stream describes work in progress. A document describes the work being proposed or already recorded.
InterfaceReadsOutput shapeStrongest claimWeakest point
show -json on a planBinary plan from -outOne plan documentThe proposed change, with unknowns and sensitivity pathsValues are planned, not real
show -json on stateState snapshotOne state documentWhat exists nowNo proposed change
plan -jsonA live planLine-delimited eventsProgress, counts and diagnosticsNo after values
apply -jsonA live apply or saved planLine-delimited eventsPer-resource completionNo reviewable artifact
output -jsonCurrent stateName-to-value objectRoot outputs after applyBlind to the next plan

Read the table as a routing rule. If the next step is a decision, take the document. If the next step is a progress display or a timeout watchdog, take the stream. If the next step is a value lookup after apply, take state.

The routing question is not "which output is newest". It is "which claim does the next step need to make". Approval needs the plan document, monitoring needs the stream, and a post-deploy lookup needs state.

Interpret Resource Actions and Unknown Values Explicitly

A change is a small object with a large vocabulary. Each entry in the change list has an address, a resource identity, and a change object containing the action list, the before and after values, the unknown markers and the sensitivity markers.

The action list is not a single verb. It is an array because replacement is expressed as two actions in a deliberate order. Creation before destruction and destruction before creation are both replacements, and the order tells an operator which outage shape to expect.

Replace is two actions

The action list distinguishes create-then-delete from delete-then-create. Collapsing both into "replace" discards the only signal that tells an operator whether capacity exists during the change.

Read replacement order, not just the word replace. A create followed by a delete means the new object exists before the old one goes away. The reverse order means capacity or identity disappears first, and a consumer that flattens both cases into "replace" throws away the only signal that distinguishes them.

Display hints are not the contract. Reason codes such as tainted or requested are documented as hints whose set can grow, so an unrecognised value must fall back to an unspecified reason instead of failing the run. The action itself remains the decision input.

Data sources read; they do not own. Their action is a read, and a read can be deferred into apply when an argument is unknown or a dependency has pending changes. A policy that treats a read as a create will demand creation-only controls for an object it does not manage.

No-op entries are bookkeeping, not approval. A plan may record an object as unchanged, or may omit it from the change list entirely. Either way, the array is a change set, not an inventory: absence means no change was recorded, never that the object is unmanaged or safe.

Deposed objects share an address. A replacement can leave an old object awaiting destruction under the same resource address, distinguished by a deposed key. A consumer that keys only on address will collapse two objects into one decision.

Imports arrive inside the change, not beside it. An import change carries the import identifier alongside the action, so the gate can separate "we adopted an existing object" from "we are creating a new one". Both may create state, but they carry different risk and different evidence.

Unknown is a fourth state, not a missing value. A field can hold a known value, an explicit null, no key at all, or a marker that the value will only exist after apply. The last two are easy to confuse, and confusing them is how a gate passes something it never examined.

The document keeps unknowns in a parallel tree. The after object contains only what is known; a companion tree marks the paths that are unknown, with a boolean at each unknown leaf. A wholly unknown collection can be marked at its parent instead of being expanded into children.

That shape difference is a required branch. A consumer must handle both a nested marker object and a bare boolean at the same path. Code that assumes one shape either crashes on the other or, worse, iterates nothing and reports a clean pass.

The planned values section cannot carry this distinction. Unknowns there are omitted or rendered as null, indistinguishable from an attribute that was deliberately unset. That is documented behaviour, and it is the reason policy reads the change list rather than the convenient flattened snapshot.

Sensitive markers are a third parallel tree. They say which values a display should hide, not which values are absent. They are covered separately in the next section because treating them as redaction is a security bug rather than a parsing bug.

A rule needs a verdict for each state. The useful contract is not pass or fail; it is pass, deny, or indeterminate, with the state recorded as the reason. An unknown on a path the rule depends on must produce indeterminate, and indeterminate must never be coerced into pass.

Unknowns that do not matter should not block. A generated identifier in an unrelated attribute is unknown on almost every create. Failing the whole plan for it trains teams to add blanket exceptions; the rule should name the exact path it needs and ignore the rest.

Three questions per change prevent most mistakes. What action is proposed, which attributes does the rule actually read, and is each of those attributes known? If any answer is missing, the gate has no business issuing a pass.

Output changes are a separate collection. Only root module outputs appear, with their own before and after values and their own unknown markers. A plan can change an output while changing no resource, so an empty resource list is not an empty plan.

Output actions have a smaller vocabulary. Create, update and delete are the valid output actions; replacement does not exist for an output. A parser that reuses the resource action enum carries branches this collection never emits and blurs the one destructive case: delete.

Checks are a separate collection and a different kind of evidence. They report pass, fail, error or unknown for checkable objects such as conditions and check blocks. The representation is explicitly experimental, so it can change within a minor release and must not be the only input to a gate.

A check status is not an exit status. A failing check block may produce a warning rather than a failed command, while a failing precondition fails the plan. The verdict still comes from the command result and the diagnostics; checks explain, they do not decide.

Read the three collections in a fixed order. First the change list for the proposal, then outputs for the contract with downstream systems, then checks for supporting evidence. Merging them into one list loses the difference between a change, a result and a warning.

Interpret Resource Actions and Unknown Values Explicitly
%%{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
    A["Plan document"] --> B{"format_version is 1.x?"}
    B -->|"no"| C["Contract error: reject the major version"]
    B -->|"yes"| D["Iterate resource_changes"]
    D --> E{"actions"}
    E -->|"no-op or read"| F["Record, no decision"]
    E -->|"create, update, delete, replace"| G{"Rule attribute marked unknown?"}
    G -->|"yes"| H["Indeterminate: deny or require review"]
    G -->|"no"| I{"Attribute in after?"}
    I -->|"absent"| J["Absent: apply the explicit default"]
    I -->|"null"| K["Null: known absence"]
    I -->|"value"| L["Evaluate the rule"]
    J --> M{"Rule outcome"}
    K --> M
    L --> M
    M -->|"violation"| N["Deny: address and path"]
    M -->|"compliant"| O["Pass: record the evidence"]
    N --> P["Gate exit: policy"]
    H --> Q["Gate exit: indeterminate"]
    C --> R["Gate exit: contract"]
    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 A,B,D,E,G,I,M primary;
    class F,J,K,L,O secondary;
    class C,N,P,R danger;
    class H,Q warn;

The hard case is a rule that reads a parent object. If the marker sits on the parent, there are no child keys to inspect, and a naive lookup returns nothing. The consumer must check the parent path first, then descend only when the parent is known.

The second hard case is an empty collection. A known empty list and an unknown list both yield no elements to iterate. The marker tree is the only reliable way to tell "the provider says there are none" from "the provider has not answered yet".

Sensitive Metadata Does Not Sanitize JSON Values

A sensitivity marker is a display instruction, not a lock. It records which paths a terminal UI should replace with a placeholder. It does not encrypt, remove or tokenise the value in the document.

Sensitive is a display hint

The marker tells a terminal to print a placeholder; the JSON still contains the plaintext value. Treat the plan document itself as the sensitive artifact, not just the screen output.

The documentation is blunt about this. Showing a plan or state as JSON prints sensitive values in plain text, and the output command behaves the same way. The marker survives so a UI can choose to hide the value; the value survives because the file itself is the sensitive object.

Secrets appear in more places than the obvious one. Root variable values, constant values in the configuration section, after values, output changes and the prior state snapshot can all carry them. A projection that keeps only resource changes is smaller, not safe.

Sensitivity markers nest. A whole object can be marked sensitive, or individual leaves can be, and the structure mirrors the value it describes. A consumer that reads only the top-level boolean will miss a nested credential.

Sensitive and unknown can overlap. A value can be both hidden from display and unresolved until apply, and the two trees mark it independently. Neither marker implies the other, and neither one changes the underlying value's presence.

Ephemeral values are genuinely absent. They never enter state or a plan, and the output command omits them even when named. That absence is correct, but it means a consumer cannot treat a missing ephemeral output as a null or a failed apply.

Diagnostics are an underrated leak. Parse failures, validation messages and policy errors often quote the value that caused them. A gate that prints the offending JSON line to make debugging easier has just published the secret it was protecting.

Plan artifacts deserve secret handling, not artifact handling. Encrypt at rest, restrict to the job identity, set a short retention period, and delete on completion. Broad read access to a build artifact store is the usual failure, not a compromised runner.

Keep the plan inside the trusted job when you can. Run the policy engine in the same job that produced the plan, and publish only the verdict and the addresses. This removes an entire class of storage and sharing mistakes rather than mitigating them.

A projection is a compromise, not a sanitizer. Dropping variables, outputs and prior state reduces exposure while keeping actions and unknown markers. It can still contain resource secrets, so it needs the same access control with a shorter life.

Emit evidence that cannot be replayed into a secret. Resource addresses, rule identifiers, attribute paths, action names and a hash of the artifact are enough to audit a decision. None of them reveals a password, and all of them let a reviewer reconstruct why the gate fired.

Hash the artifact for provenance, not for secrecy. A digest proves the reviewed plan is the applied plan; it does not make the plan publishable. Store the digest with the run record and keep the bytes in the restricted location.

Redact logs at the source. Turn off verbose request logging for the policy job, avoid dumping environment variables, and make the consumer's error path print a path and a reason code instead of a document fragment. The safest redaction is the one that never had the value.

Access control beats clever filtering. A field allowlist is useful, but the durable control is that only the plan job can read the plan. Rotation, short-lived identity and job-scoped permissions survive a bug in the filter; a regex does not.

The plan stays inside the boundary A plan document may contain variable values, resource secrets, output values and prior state. The consumer and policy engine run inside the trusted job. A verdict and an address-level evidence record may leave. Raw values, the plan artifact and diagnostic fragments may not. The plan stays inside the boundary Sensitivity markers control display, not access Trusted job: plan bytes never leave plan document variables, outputs, prior state, secrets consumer four-state evaluation field allowlist policy engine compares inside the job sensitive paths a display hint only verdict pass, deny, indeterminate evidence record addresses, rule ids, paths, digest safe to attach to a review raw values, plan bytes blocked at the boundary A parse error must name the offset and the expected field, never echo the line that failed.

The test is simple and uncomfortable. Ask whether the artifact you are about to upload, attach or log could be replayed to recover a credential. If the answer is yes, it is a secret, regardless of its file extension or its location in the pipeline.

Handle Exit Codes, Run States and Partial Apply

Four questions get collapsed into one word: success. Did the command finish, did it propose changes, is the proposal applicable, and did every intended change actually complete? An automation that answers only the first question will report success for a partially applied estate.

The plan command has two exit-code contracts. Without the detailed flag it returns zero for a successful plan whether or not changes exist, and one for an error. With the flag it adds two for a successful plan that contains changes, which is a signal rather than a failure.

An exit code of two breaks naive scripts. A shell running with immediate exit on error treats a legitimate change set as a fatal condition, so the caller must capture and branch on the status explicitly. A pipeline that also hides the status behind a pipe turns every outcome into the last command's status.

The plan document answers applicability. It carries boolean flags for whether applying makes sense, whether the result is expected to converge, and whether planning errored. The documentation recommends the first two as the primary conditions for wrapping automation, precisely because the exact definition may evolve.

Incomplete is not the same as failed. A plan can be applyable but incomplete, meaning a second plan and apply round is expected before the estate converges. Treating that as success leaves drift in place; treating it as an error sends a healthy multi-stage change back to the author.

Errored plans can still list actions. The actions planned before the failure are useful evidence about how far the engine got, but they are not an approval and must not be applied. The errored flag is the authority, not the length of the change list.

Apply has a simpler status and a worse failure mode. Zero means the apply completed; non-zero means it did not. Before exiting, Terraform writes the state for everything it did complete and does not roll back, so the next reader sees a partially changed estate rather than the previous one.

Partial apply is a reconciliation problem, not a retry problem. The correct next step is a fresh plan that shows what remains, followed by a deliberate repair. Re-running the same apply blindly can duplicate work, fight a lock, or repeat a destructive step that already succeeded.

A killed job has no exit code from Terraform at all. A timeout, an out-of-memory kill or a cancelled workflow produces a signal status, and the process never got to report. That is an unknown outcome, not a failure, and it requires the same reconciliation as a partial apply.

The stream needs a terminal rule. A stream begins with a version message, carries per-resource events and diagnostics, and normally finishes with a change summary. A consumer should require a clean command status plus the expected completion evidence, not merely the absence of an error message.

Absence of an event is not a negative result. Events can be interleaved, buffered or lost when a runner is killed, and a log collector may truncate the tail. Counts from a summary are a cross-check; the authoritative change details remain in the plan document.

Interactive input is removed by the JSON mode. The flag implies non-interactive input, so a missing root variable fails the run instead of waiting forever. That is a feature, and it should be tested, because a pipeline that hangs is worse than one that errors.

Give the gate its own vocabulary. Our consumer returns pass, deny, indeterminate, contract error or operational error, each with a distinct process status and a one-line reason. A policy denial, an unreadable schema and a killed runner are not the same failure and should not share a colour in the dashboard.

A useful mapping is small and stable. Zero for pass, a dedicated status for a policy denial, another for indeterminate, another for a contract breach, and another for an operational failure. The exact numbers are a local convention; the separation is the contract.

Closure needs its own assertion. After apply, run a fresh plan and require an empty diff. That is the only evidence that the intended state was reached, and it catches provider normalisation and resources that were planned but never reported complete.

Record the evidence at each layer. The plan status, the review decision, the apply status and the post-apply plan result are four separate facts. A single green check that hides which one failed is not an audit trail.

Automation run state decisions
%%{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
    A["plan -out=tfplan"] --> B{"Plan exit status"}
    B -->|"1"| C["Plan errored: stop"]
    B -->|"0"| D["No changes proposed"]
    B -->|"2"| E["Changes proposed"]
    E --> F{"applyable and complete?"}
    F -->|"no"| G["Not a normal apply:
inspect flags and diagnostics"] F -->|"yes"| H["Policy reads plan JSON"] H -->|"deny"| I["Stop: policy failure"] H -->|"indeterminate"| J["Stop: unknown on a decisive path"] H -->|"pass"| K["apply tfplan"] K --> L{"Apply exit status"} L -->|"0"| M["All planned changes reported complete"] L -->|"1"| N["Partial apply: state updated,
no rollback"] L -->|"signal or timeout"| O["Unknown: reconcile before retry"] N --> P["Fresh plan, then repair"] O --> P P --> Q["Closure: fresh plan exit 0"] M --> Q D --> R["Closure: nothing to do"] C --> S["errored true: listed actions
are evidence, not approval"] 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 A,B,E,F,H,K,L primary; class D,M,P,R secondary; class Q ok; class C,I,S danger; class G,J,N,O warn;
After a partial apply, the state is the fact A reviewed plan proposed three changes. Apply reported two completions and one error, so state holds two objects. Git revert does not touch the cloud. A fresh plan shows the single remaining change, which is the repair input. After a partial apply, the state is the fact Three planned changes, two completed, one decision left Reviewed plan 3 changes applyable, complete policy passed Apply 2 complete events 1 errored event status 1 State 2 objects recorded 1 never created no rollback Fresh plan 1 change remains the repair input not a revert The tempting path git revert the change configuration returns to old text cloud keeps the two new objects no effect Next plan disagrees the revert looks like a new change and may destroy what did succeed Repair forward resolve the error re-plan, then apply Completion evidence per change, not per command A green pipeline step says the process exited. It does not say every object in the plan was created or updated.

The one-line summary is worth writing down. A step is complete only when its exit status, its artifact and its post-condition agree. When they disagree, the artifact and the post-condition win, because the exit status is the least specific of the three.

Write a Consumer Contract with Versioned Fixtures

A consumer contract is a list of assumptions made explicit. It names the inputs it accepts, the versions it supports, the states it can distinguish, the outputs it promises and the evidence it retains. Without that list, every parser bug becomes an incident discovered by a reviewer.

Start with the version gate. Accept the same major format version, tolerate unknown keys within it, and reject an unknown major before reading any other field. The documented rule is exactly this: minor versions add compatible fields, major versions break them.

Do not confuse the three version numbers. The plan document, the state document and the streaming UI each carry their own. Record all of them in the run evidence, and gate on the one that belongs to the document you actually parsed.

Treat the checks section as experimental on purpose. Its representation may change within a minor release, so isolate it behind an adapter and never let its absence fail the whole plan. The core change set is the stable input; checks are supporting evidence.

Publish a verdict, not a modified plan. The consumer's output should be a small object with a decision, a reason code, the resource address, the attribute path and the contract version it applied. That object is safe to store and easy to test.

Version the contract separately from the format. The consumer's own version changes when its verdict shape or reason codes change, which is a different event from a Terraform minor release. A rule that turns a pass into a denial is a breaking change for every dashboard that consumes it.

Give every reason code a meaning a human can act on. "Denied by rule" is not enough; the useful pair is which rule and which path, plus the smallest change that would satisfy it. An indeterminate result needs the same treatment, naming the unknown path and the review that can resolve it.

Keep the four-state rule in one place. A single evaluator decides whether a path is known, null, absent or unknown, and every rule consumes its result. Duplicating that logic per rule is how one rule starts treating an unknown as a pass.

Fixtures are the contract's regression test. Each fixture is a small JSON document representing one behaviour, with the expected verdict stored beside it. The set becomes the executable definition of what the consumer promises.

Build fixtures from a plan for a disposable root, then replace every value. Keep the structure, the markers and the action vocabulary; substitute synthetic identifiers and strings for anything tied to an account. The fixture should teach one behaviour without carrying production context.

Never capture a production plan as a fixture. A fixture is committed and shared, so it must be synthetic by construction. Rebuild the document from a value allowlist rather than hoping a search-and-replace caught every secret.

Cover the shapes that break parsers. A whole-value unknown, an unknown nested inside a list, a null that differs from an absent key, an output-only change, a replacement in each order, a sensitive nested object and an empty change list are the minimum set.

Add a schema-tolerance fixture. Take a valid document and add an unrecognised field at the top level and inside a change. The consumer must ignore it and reach the same verdict, which proves the minor-version promise rather than merely asserting it.

Add a major-version fixture. Change the format version to the next major and require a clean contract error with no partial evaluation. A consumer that half-reads an unsupported document is worse than one that refuses it.

Mutation tests prove the gate fails for the right reason. Remove the unknown marker and require the gate to complain rather than pass; remove the action and require a contract error; add a sensitive marker to a policy-relevant path and require the same verdict with no value in the evidence.

The fixture harness runs on every consumer change. Load each document, run the contract, compare the full verdict object and the process status. A diff in either is a contract change and needs a version decision, not a silent update.

Version the fixtures with the consumer. A consumer release names the fixture set it was tested against, so an old failure can be reproduced after the rules move on. The consumer version and fixture set together form the unit of evidence.

Test the stream separately. Feed a truncated event log, an interleaved log and one with an unknown message type, and require the reader to keep going while the completion logic refuses to claim success. The document fixtures do not cover stream behaviour, and the stream is where a killed job shows up.

Advanced Lab

Review the plan consumer

Goal: build a small consumer that reads a plan document, distinguishes known, null, absent and unknown values, and returns a verdict that a gate can trust.

Execution status: design-only. The fixtures are synthetic and the steps use Terraform 1.17.1 locally with the built-in terraform_data resource, so no cloud account is needed. No output is transcribed here; record your own values.

Contract under test.

AssumptionRequired behaviourFailure it prevents
Format major is 1Reject any other major before parsingSilent half-read of a future schema
Unknown markers are authoritativeDecisive unknown returns indeterminateAbsence of evidence read as compliance
Null, absent and unknown are distinctEach maps to a different branchDefaults applied to values never seen
Replacement order is preservedCreate-then-delete and delete-then-create stay distinctAvailability risk flattened away
Verdicts are small and typedDecision, rule, address, path, contract versionValues leaking into review comments

Steps:

  1. Create a root with three managed objects: one with a literal argument, one with an argument derived from another object's identifier, and one with an optional argument set to null. Pin the CLI version.
  2. Save a plan, render the document, and record how the provider represents each case: the derived argument in the unknown tree, the explicit null in the after object, and the omitted argument as an absent key. Provider schemas differ, so the fixture records what this pair actually emitted.
  3. Write the consumer so that every rule returns a verdict object and returns indeterminate whenever a path it reads is unknown. Make the default for an unexpected shape a contract error, not a pass.
  4. Add a rule that requires a specific tag. Run it against the fixture where the tag is known, absent, null and unknown; expect pass, deny, deny and indeterminate respectively.
  5. Add a fixture with a replacement in each action order and assert that the verdict records the order. Then add an output-only change and assert that the resource list may be empty without the gate concluding "no changes".
  6. Add the tolerance fixture with extra fields and the major-version fixture; expect the same verdict for the first and a contract error for the second.
  7. Mutate a copy of each fixture: delete the unknown marker, change an action to an unknown verb, and set the format version to the unsupported major. Expect a failure in every case.
  8. Run the suite in CI and fail the job on any verdict diff, not only on a denied result. A changed pass is still a changed contract.

Expected observation: a correct consumer never turns an unknown into a pass, never conflates a null with an absent key, and refuses an unsupported major before evaluating a rule. The same fixture set then runs unchanged against the next CLI patch release.

Failure checks: a gate that passes the unknown fixture usually reads the flattened planned values instead of the change list. A gate that denies the null fixture is applying a default where the configuration made an explicit choice. A consumer that crashes on an extra field has broken the forward-compatibility promise it claimed to keep.

Cost and cleanup: no cloud spend; a few local files and runner minutes. Remove the working directory and the plan artifacts, and confirm that no fixture contains a real account identifier or secret.