Back to Terraform

Audit Where Terraform Secrets Persist

November 6, 2026 Wasil Zafar 29 min read

Test a synthetic secret across configuration, plans, state, logs and historical snapshots

Table of Contents

  1. Design the Experiment with a Synthetic Marker
  2. Trace Redacted and Non-Persisted Value Paths
  3. Inspect Artifacts Privately and Report Only Findings
  4. Old Object Versions and CI Artifacts Remain Part of the Scope
  5. Write a Remediation Record with Explicit Residual Exposure

Design the Experiment with a Synthetic Marker

A persistence audit needs a value that is safe to leak. Generate a marker from a fixed prefix and a random suffix, then handle it exactly like a production credential for the rest of the exercise. The prefix makes it searchable, and the randomness keeps an unrelated string from producing a false match.

Isolation belongs to the directory, not to the configuration. Create one directory outside every repository, remove group and other permissions, and use the local backend so the state object never leaves the machine. Do not run version control inside it, do not point a workspace at a hosted organisation, and do not configure a remote backend.

Publishing is the failure this experiment exists to avoid. A CI artifact, a screenshot, a pasted transcript and a ticket comment are copies with their own readers and their own retention. Keep the run on one machine, keep the evidence in one file, and plan to delete both.

The inventory below is the real deliverable. Six surfaces can hold the marker in a local run, and each one is written by a different part of the tool.

ArtifactWritten byCan hold the markerReader during the test
Saved planterraform plan -out=tfplanEvery input variable and every planned valueThe account running the CLI
State fileplan and applyResource attributes, data source results and outputsThe same account
State backupthe next write to local stateThe previous version of everything aboveThe same account
Plan documentrendering the plan with terraform show -jsonThe same values as the plan, without screen redactionWhatever the pipe reaches
Debug logTF_LOG and a crashing providerRequest and response bodies from the failing callThe log file, then its readers
Backend recordinitialisationEndpoint, bucket name and any credential written into the backend blockThe same account

The two easily forgotten rows are the backup and the backend record. Neither appears in plan output. The backup is created beside the state on the next write, and the backend record is written by initialisation into a hidden directory, where it sits until someone reads it.

Figure 1 follows the marker from generation to deletion and marks the two paths that leave the sandbox.

Design the Experiment with a Synthetic Marker
%%{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
    M["Synthetic marker
fixed prefix, random suffix"] --> E["Disposable directory
owner-only permissions"] E --> V["Sensitive variable
supplied at the prompt"] V --> P["Plan with a saved file
local backend only"] P --> A["Apply completes"] A --> R["Artifacts written to disk"] R --> C1["Saved plan"] R --> C2["State file and backup"] R --> C3["Plan document on stdout"] C1 --> Q["Record path, size and match count"] C2 --> Q C3 --> Q Q --> W["Delete the directory
and the evidence note"] P -. "remote backend configured" .-> X["Outside this run
add it to the audit inventory"] A -. "debug logging enabled" .-> Y["Log becomes an artifact
count it, do not read 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 M,E,V,P primary; class A,R,C1,C2,C3 secondary; class Q,W ok; class X danger; class Y warn;

Layers, not files, are what an audit has to name. A value moves from configuration into process memory, from process memory into an artifact, and from an artifact into somebody else's copy. Each layer has a different owner and a different way of being cleared.

Figure 2 draws those five layers with the persistence boundary between the third and the fourth, and names what an audit can honestly claim at each level.

Five layers a synthetic marker passes through, with the persistence boundary after process memory A synthetic marker enters through configuration, is used in plan and apply memory, and is then written into a saved plan, state and backup. A dashed boundary separates runtime from stored artifacts. Beyond it, CI artifacts, debug logs and pasted transcripts keep further copies. The right column states what the audit can prove at each layer: that the value is the one you control, that configuration holds a reference, that memory leaves no record, that artifacts either contain or omit the bytes, and that outside copies are only observable. One value, five layers, one boundary The marker sits in configuration and memory before any artifact exists. LAYER WHERE THE VALUE SITS WHAT THE AUDIT CAN CLAIM source marker in the environment, never in a file you keep you generated it and can rotate it configuration variable and argument hold a reference, not the file the source is checked, not the value runtime plan and apply keep it in process memory only memory leaves no record to erase PERSISTENCE BOUNDARY artifacts saved plan state file backup contains or omits the bytes provable by count and hash outside copies CI artifact debug log pasted transcript observable, rarely removable owner and retention only A claim about the fourth layer is evidence. A claim about the fifth is a question to the owner.

Two limits belong in the experiment design, stated before the first apply. A local sandbox cannot show what a hosted backend retains, what a provider keeps on its side, or what a colleague copied last month. Those are scope items for the audit in the next sections, not gaps in the proof.

A marker also fails quietly when it is transformed. If the provider base64-encodes the value or the plan compresses it, a plain text search of the file finds nothing and the result looks clean. Search for the encoded form as well, and prefer asking Terraform to render the artifact over reading its bytes.

Trace Redacted and Non-Persisted Value Paths

Sensitivity is a display instruction. Marking a value sensitive makes Terraform print a placeholder in human-readable plan output, apply output and the hosted UI. The bytes remain in the plan file and in state, and the machine-readable forms return them in clear text.

The version each mechanism arrived in matters. This is the Terraform 1.17.1 baseline, where all three are available, but an estate running an older CLI will reject the declarations rather than fall back quietly. Check the CLI version of every pipeline that could plan the configuration before the configuration uses it.

Ephemeral means the value has no record. Terraform 1.10 added ephemeral input variables, ephemeral resources and ephemeral outputs from child modules. The value exists for the operation and is omitted from both artifacts, which is a stronger promise than redaction and a narrower one than deletion: the source still holds it.

Write-only is a property of the provider schema. From Terraform 1.11, a provider can mark an argument as write-only, and Terraform then sends the value during the operation while storing null in its place. A companion version counter supplies the diff that a value Terraform never stores could not otherwise produce.

The table is the comparison to put in a design review, because each row answers a different question about what survives.

MechanismWhat Terraform changesPlan fileState fileCopies that remain
Plain argumentNothingValueValueEvery artifact below
sensitive = trueDisplay onlyValue on disk, placeholder on screenValueEvery artifact below
Ephemeral valueOmits the valueAbsentAbsentEnvironment, variable file, shell history
Ephemeral resourceOmits the objectAbsentAbsentProvider lease, request log
Write-only argumentStores null plus a versionWrite-only marker, no valuenullProvider store, request log

Read the last column before the middle ones. The first two rows persist everywhere and protect a screen. The last three remove a copy from Terraform's artifacts, and none of them removes the copy at the source or the copy the provider keeps.

Figure 3 places the three mechanisms side by side against the same boundary, with the shared source that all of them leave behind.

Sensitive, ephemeral and write-only paths against the persistence boundary A single value source feeds three lanes. The sensitive lane writes the value into the plan file and the state file and returns it in clear text from the JSON form. The ephemeral lane writes nothing to plan or state, but the environment or variable file still holds the value. The write-only lane writes a placeholder to the plan and null plus a version counter to state, while the provider keeps its own versions. All three lanes begin at the same unprotected source. Three mechanisms, one shared source The declarations decide the two middle columns. The outer two belong to someone else. value source environment or variable file outside Terraform the audit starts here MECHANISM SAVED PLAN STATE THEN READ FROM sensitive display flag value written placeholder on screen value written plus a redaction path JSON and named output clear text ephemeral one operation absent no value on disk absent no value on disk the source still holds it write-only schema flag no value stored no value in the file null and a version counter is stored the provider keeps its versions The declaration governs what Terraform writes. It never reaches the copy above it. An audit that stops at the artifacts answers half the question and calls it finished.

The mechanisms compose rather than compete. An ephemeral value can feed a write-only argument, which is the strongest arrangement the language currently offers: the value has no source file inside the configuration and no stored copy on Terraform's side. Each mechanism covers one leg, and the pair covers both.

Figure 4 follows the decision and the three branches that turn a good intention into a stored secret.

Trace Redacted and Non-Persisted Value Paths
%%{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["Value arrives
environment, file or store"] --> D{"Which mechanism
is in use?"} D -- "sensitive" --> S1["Marked for display redaction"] S1 --> S2["Plan and state keep the bytes"] S2 --> S3["JSON form and named output
return it in clear text"] D -- "ephemeral" --> E1{"Destination supports
an ephemeral value?"} E1 -- "no" --> E2["Plan error
invalid use of ephemeral value"] E1 -- "yes" --> E3["Omitted from plan and state"] E3 --> E4["Source still holds a copy
environment, file, history"] D -- "write-only" --> W1{"Provider schema marks
the argument write-only?"} W1 -- "no" --> W2["Ordinary argument
value persisted as usual"] W1 -- "yes" --> W3["Null in state
version counter remains"] W3 --> W4{"Counter incremented?"} W4 -- "no" --> W5["No diff for a reviewer to see"] W4 -- "yes" --> W6["Provider receives the new value"] W3 --> W7["Provider store keeps versions
outside Terraform's reach"] 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,D,E1,W1,W4 primary; class S1,S2,W3,S3 secondary; class E3,W6 ok; class E2,W2,W5 danger; class E4,W7 warn;

Each failure branch is a different kind of wrong. A plan error stops the run, which is the good outcome. A write-only argument without a version bump produces a clean plan and no change, which is the quiet outcome. Sensitive in an ordinary argument produces a redacted screen and a stored value, which is the common outcome.

A root output is the sharpest example of the difference. Terraform rejects an ephemeral output at the root module, because a root output exists to be stored for other configurations to read. The rejection is the language telling you that the value would have become an artifact.

The audit question is therefore not which flag is set. It is which artifact still contains the bytes, and who can read that artifact today. A workspace full of sensitive marks can still be the leakiest configuration in the estate.

Inspect Artifacts Privately and Report Only Findings

An audit reads artifacts; it does not print them. Every probe should return a property of the artifact, such as a count, a boolean, a hash or a key name, rather than its content. That single constraint is what makes the result safe to attach to a ticket.

Start with a filename-only search over the working directory. A recursive search that lists matching paths tells you where the marker landed without printing a byte of it. Record the command, the directory, the exit status and the timestamp beside the counts, because those four fields are what make the number evidence.

Binary artifacts need a different probe. A saved plan is not a text file, and a text search of it proves nothing when the bytes are compressed. Ask Terraform to render the plan as a document, then reduce that document to a count of matching strings, so the value never reaches the terminal.

The table maps each surface to a probe that returns a verdict rather than a value.

SurfaceProbe that stays safeWhat comes backHow it leaks by accident
Working treefilename-only recursive searchpaths with a matchprinting the matching line
Saved planplan document piped to a match countan integerredirecting the document to a file
Current statestate pulled through a pipe, countedan integerwriting the raw state to disk
Previous versionsbackend version listingversion ids and datesdownloading a version to inspect it
Logsper-file match countone integer per fileopening the log to see the context
Provider cachefile listing and schema dumpplugin names, attribute namesnothing: schema has no values

A workspace audit starts at the backend, not at the files. The backend configuration names the object that holds the state, its versioning and lock settings say what history exists, and its policy says who can read that history. Read those three things before running a probe, because they bound every finding that follows.

The provider cache is the one surface that is genuinely clean. It holds plugin binaries and module source, and the lock file beside it records provider hashes; none of those contain attribute values. Saying so explicitly is worth the sentence, because it stops an auditor from spending a day on the least interesting directory.

Encoded forms are the silent false negative. If the provider stores the value base64-encoded, or the artifact nests it inside a JSON string, a raw text search returns zero while the value sits in the file. Encode the marker and search for that form too, and treat a zero result from one probe as one result, not a conclusion.

Figure 5 places the probe outside the artifact zone and shows the only thing allowed to cross back: counts, hashes and verdicts.

A read-only probe outside the artifact zone, returning only counts and verdicts to the finding record A read-only probe on the left queries four surfaces inside a bounded artifact zone: the saved plan, state and its versions, logs, and the provider cache. Only counts, file hashes and verdicts cross into the finding record on the right. A red band explains that a value copied into the report becomes a new artifact with a new owner and no retention date. Read the artifact, publish the verdict The value never crosses to the right side of this picture. read-only probe filename search count in a document hash of the artifact no write, no copy ARTIFACT ZONE, READ WITHOUT PRINTING saved plan binary, compressed state and versions current and retained logs job output, trace provider cache binaries and schema finding record artifact and scope probe and result verdict and owner no values anywhere counts and hashes only Copying the value into the report creates a new artifact with a new owner. That copy has no retention date, no reader list and no place in the inventory.

Findings have three values, and unknown is one of them. A surface is present, absent or not observable from where you sit. The third value is the most useful, because it forces the record to name the reader who could observe it instead of pretending the surface was checked.

A claim is only as good as its scope. "Absent from the current state and the saved plan, in this directory, at this time, using these two probes" is evidence. "The workspace is clean" is a sentence that will be quoted back at you after the next release.

The record below is enough for a reviewer to reproduce the result without seeing the value.

FieldWhat to writeWhy it belongs
ScopeRoot, backend, artifact set, timestampBounds the claim to what was checked
ProbeCommand shape and filter, not its outputAnother auditor can repeat it
ResultMatch count, boolean or artifact hashShows the finding without the bytes
VerdictPresent, absent or not observablePrevents a gap becoming a pass
OwnerTeam accountable for the artifactMakes the follow-up actionable
Next reviewDate tied to the retention clockKeeps the finding from ageing silently

The strongest finding is usually an absence that should not be there. A marker missing from state may mean the argument is write-only, or that apply never wrote the resource. The probe cannot tell you which, so the record needs the second observation: the value present at the provider, or the resource absent from the plan.

Old Object Versions and CI Artifacts Remain Part of the Scope

A clean current artifact says nothing about yesterday. Every write creates a new version, and every versioning scheme keeps the old one for a period that was chosen by someone who was not thinking about this secret. Fixing the configuration changes what the next write contains; it does not reach backwards.

Versioning is a feature that works against deletion. S3 versioning, blob versioning and object generations all retain the previous object, and an object-lock policy can refuse removal until a date. Hosted backends keep their own state version list, so a workspace can show a clean current state while the previous three still hold the marker.

CI keeps what it was given. An uploaded plan or a job log is a secret-bearing artifact with the platform's default retention, which for GitHub Actions is ninety days for both artifacts and logs unless the repository changes it. Ninety days is not a storage detail; it is the floor of the exposure.

Editing state edits one file. Removing a resource from state, or pushing a hand-edited state, changes the current object and leaves the previous version, the backup beside it and the hosted version list untouched. The edit is a story about the file, not about the copies.

Figure 6 puts the write history on a timeline and keeps the outside copies visible beside it.

A state version stack and CI copies after the configuration is fixed A timeline runs from marker creation to a fixed configuration to rotation. Below it, three state versions are retained: the current clean version, the previous clean version, and the oldest version that still contains the marker. Two amber boxes show an uploaded plan and a job log from the first apply, both still inside their retention window. A red band states that deleting the current object removes a pointer, not a version. The current object is the newest version, not the only one Fixing the configuration moves the top of the stack. It does not empty it. T0 marker created T1 first apply T2 configuration fixed T3 rotation STATE VERSIONS, NEWEST FIRST v3 current clean: the argument no longer stores the value v2 retained clean, and still readable by anyone with version access v1 retained contains the marker in the resource record uploaded plan from T1 inside the platform retention window job log from T1 same window, different reader group Deleting the current object removes a pointer, not a version. Exposure ends when the credential is revoked, the copies expire and no reader still holds one.

Three clocks decide how long the exposure lasts. The credential stays valid at the target until it is revoked there. The artifact stays readable until its retention expires. The reader keeps whatever they downloaded, for as long as they keep it.

ClockReset byNot reset by
Credential validityRevocation or rotation at the targetChanging the Terraform variable
Artifact retentionExpiry of the version, object or CI artifactDeleting the current state file
Reader accessRemoving the permission, or the readerEither of the above

The honest inventory lists the copies you cannot delete. A provider's secret versions, a backup under a retention lock and a transcript in a ticket are all in scope, and none of them will be removed by a Terraform change. Naming them is what separates a remediation from a claim.

This is why the record needs two dates, not one. The date the new value was deployed is the start of the fix. The date the old value stopped working is the start of the end. Between them, every retained copy is still a working credential.

Write a Remediation Record with Explicit Residual Exposure

Remediation is a record, not a cleanup. The work is ordered, the evidence is written down as it happens, and the note ends with what is still exposed rather than with what was deleted. A reader who was not in the room should be able to reconstruct the decision.

The order is issue, deploy, verify, revoke, purge. A new credential is issued at the source, applied so the target and the state both move, verified with a real request, then the old one is revoked at the target. Purging comes last, because until revocation succeeds the old value is still live and the artifacts may be needed for a rollback.

Evidence is metadata, never content. For each surface, record the command shape, the filter, the exit status, the timestamp and a hash of the artifact. Together they prove what was checked and let another auditor repeat it, without creating the copy the audit was meant to prevent.

Residual exposure is a section, not a disclaimer. It names the copies that remain, who can read each, when each expires and which owner accepted the gap. A record with an empty residual section is usually a record that stopped looking.

Access remediation changes who can reach the copies. Narrow the backend role to one state key, remove the artifact readers who only needed last quarter's plan, and retire the CI secret that still holds the old value. Permission is the only control that works on a copy you cannot delete.

Retention is the change you can ship this week. Shorten the plan artifact window, add a lifecycle rule on noncurrent state versions, and test a restore before you expire anything. A retention policy nobody has restored from is a guess about availability and a promise about deletion.

The lab below runs the whole sequence against a disposable root, with a legacy snapshot that deliberately contains the marker so the difference between current and historical is observable rather than assumed.

Lab

Audit the persistence boundary

Status: design-only. The sequence is written for Terraform 1.17.1 with the local backend and no cloud account. No command below was executed to produce recorded output, every identifier is a placeholder, and the marker is synthetic throughout.

Prerequisites. Terraform 1.17.1, a shell with a text search tool, a SHA-256 utility and a JSON filter, and one disposable directory outside every repository. No remote backend, no CI, no version control inside the directory.

Setup. Create the directory, restrict it to your own user, and export a marker built from a fixed prefix and random hex. Keep the marker in the environment only, never in a file you intend to keep.

DeliverableFilePass condition
Marker recordmarker.sha256Hash only, no value
Artifact inventoryinventory.mdEvery surface has a writer and a reader
Probe resultsfindings.mdCounts, hashes and verdicts, no content
Retention checkretention.mdVersioning, object lock and CI window named
Rotation recordrotation.mdIssue, deploy, verify, revoke, purge with times
Residual exposureresidual.mdRemaining copies, readers, expiry, owner
  1. Export the marker, then write only its hash to the record file. From this point the value exists in one process environment and nowhere else that you control.
  2. Write a minimal root: one variable marked sensitive, one resource argument that stores it, and the local backend. Apply once, so a real artifact set exists.
  3. Copy the state into a snapshots/ directory with owner-only permissions. This is the stand-in for yesterday: a copy that the migration will not touch.
  4. Probe the working tree with a filename-only recursive search, then probe the saved plan and the current state through a counted pipe. Write down one integer per surface and nothing else.
  5. Fix the configuration to the non-persisting route the provider supports, ideally a write-only argument fed by an ephemeral source, apply, and repeat the same three probes. The current plan and state should now return zero; the snapshot and the backup should still return a match.
  6. List the retained versions through the backend, if one is reachable, and record version ids, dates and reader groups. Where no backend is reachable, mark the surface not observable rather than absent.
  7. Rotate in order: issue at the source, apply, verify a real request, revoke the old value, then delete the snapshot and the plan. Confirm the old value now fails at the target, not only in Terraform.
  8. Write the residual section: the provider's own versions, any backup under retention, the CI window and the readers who may still hold a copy. Give each a date and an owner.
CheckExpected resultEvidence to keep
Current state after the fixZero matchesCount and timestamp
Saved plan after the fixZero matchesCount and timestamp
Snapshot taken before the fixOne or more matchesCount only, never the line
Backend version listOlder versions still presentVersion ids and dates
Old credential after revocationRejected at the targetStatus or error class, no secret
New credential after rotationAcceptedStatus code and time

Expected observation. The probes separate three states that are easy to conflate: the current artifacts are clean, the retained copies are not, and the provider still holds its own history. The snapshot match is the finding that a configuration-only fix would have missed.

Failure checks. A zero result in the snapshot means the copy was taken after the fix, so repeat step 3 first. A zero result everywhere including the provider means the value never reached the target. A match in the current state means the argument is not actually write-only, so re-check the schema rather than the configuration. A match that appears only after decoding a base64 string means the raw search was a false negative.

Cost and cleanup. Zero cloud spend; the cost is disk and attention. Delete the directory, the snapshot, the plan and the markers, clear the environment variable, and close the shell so the value does not survive in its history. On a shared machine, check the trash and any backup tool before declaring the copy gone.

Evidence to keep. The marker hash, the inventory with writers and readers, one count per surface per run, artifact hashes, the retention findings, the ordered rotation record with timestamps, and the residual exposure section with an owner per remaining copy. Never keep the marker, a raw state file, a plan file or a log line that contains either.