Provider and Backend Identities Have Different Jobs
A building has two kinds of access. A staff pass opens the doors you work behind. A separate key opens the records room, where the building logs who did what. Most organisations would not hand the records-room key to everyone who can open a door, and they would not let a contractor keep either one forever.
Terraform has the same two jobs, and many teams quietly merge them.
The provider identity is the principal the provider plugin uses to read and change managed objects. When Terraform creates aws_s3_bucket.logs, this is the identity that calls CreateBucket. The backend identity is the principal that reads and writes the state object and its lock: the record of what Terraform believes it owns. Two more identities sit around them. The human is an engineer at a terminal, authenticated through single sign-on. The workload is the CI job that runs plan and apply on a merge.
Merged identities cannot be audited
They are separate because they fail differently. A provider identity with broad permissions can delete a database; a backend identity with broad read access can read every attribute ever recorded, including the password the provider returned on create. Merge the two into one role and a single stolen credential does both, and the audit log cannot tell you which job was which.
The old answer was a long-lived access key pasted into CI secrets. It is still common, and it is the wrong default for three reasons. A static key is a bearer token: whoever holds it is the role, from any network, for as long as nobody rotates it. It carries no statement about which repository, branch or environment produced the request, so a key lifted from a test pipeline works against production if the policy is broad enough. And in CloudTrail or Activity Log, its use looks exactly like legitimate use, because the principal is the same.
Federation replaces the secret with a signed statement about the job. GitHub Actions, GitLab CI and HCP Terraform can each mint a short-lived OIDC token that says "this workflow, in this repository, on this ref, in this environment". The cloud's token service validates the issuer signature, the audience and the subject claim against a trust policy, then issues credentials that expire in about an hour. Nothing long-lived is stored in the repository, and the trust policy becomes the security control. It is a document you can review, diff and manage in a bootstrap root.
The exchange has four moving parts, and each one is a place to get it wrong. The issuer must match exactly, character for character, or any token service can pretend to be yours. The audience must be the one your cloud expects, or a token minted for another service is accepted. The subject must name the repository and, ideally, the environment. And the role's permissions must be the smallest set that finishes the run. A narrow subject with an administrator role is still an administrator.
Figure 1 traces both paths, including the one that no longer exists after federation.
%%{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
H["Engineer with SSO
MFA, session measured in hours"] --> HP["Provider identity
local plan or break-glass"]
H --> HB["Backend identity
read state during an incident"]
C["CI job on a ref
repository plus environment"] --> O{"OIDC exchange
issuer, audience, subject"}
O -- "subject matches the trust policy" --> A["Workload role
credentials valid about one hour"]
O -- "wrong repo, ref or environment" --> DENY["Token service denies
no cloud API call is made"]
A --> AP["Provider identity
plan or apply permissions"]
A --> AB["Backend identity
one state key and its lock"]
K["Long-lived access key
in a CI secret"] --> KP["Provider identity
same permissions, no expiry"]
K --> KB["Backend identity
state readable from anywhere"]
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 H,C primary;
class O,A secondary;
class HP,HB,AP,AB ok;
class DENY,K danger;
class KP,KB warn;
Two habits keep the split honest. The first is that plan and apply get different roles. The plan role reads state and cloud objects and needs no write permission beyond the lock; the apply role writes. That difference is what makes a reviewed plan meaningful, because the plan could not have changed anything even if the code tried.
The second habit is that neither role can change its own trust policy, the OIDC provider, or the state bucket's policy. Those belong to a bootstrap root owned by a platform team, for the same reason the key to the records room is not kept inside the records room. Without that rule, an apply role that can edit its own trust policy is an administrator with extra steps.
Figure 2 draws the boundary: two identity sources converge on one exchange, which issues two distinct roles.
State access is secret access
The state side is the one teams forget. Granting the provider role read access to the state bucket to "make things work" quietly gives the deployment path the ability to read every secret in the estate. The backend role should reach one key; the provider role should reach none.
Choose a Secret Store by Trust and Rotation Requirements
A secret store answers four questions: who may read this value, how long the answer stays valid, what happens when it expires, and who can prove the read happened. Feature comparisons that ignore the second and third question produce a store that holds secrets beautifully and never rotates them.
Four models cover most estates. The table compares them by the property that decides the choice: what the workload must already have, and what happens when a credential is no longer needed.
| Store | Best fit | Rotation and lifetime | Access control | Failure to design out |
|---|---|---|---|---|
| HashiCorp Vault | Multi-cloud or mixed estates; database and cloud credentials issued on demand | Dynamic secrets carry a lease and TTL, and expiry revokes the credential at the target. KV v2 versions a static value; expiry there is opt-in metadata, not a lease | Policies bind an authenticated identity to a path; audit devices record every request and response | A lease longer than the run; a token with a long TTL cached in CI |
| AWS Secrets Manager | Workloads already running under an AWS identity | A rotation function updates the value, and staging labels keep AWSPREVIOUS readable during rollout | IAM identity policy, KMS key policy, optional resource policy; CloudTrail records reads | Cross-account reads granted to a whole account; rotation that updates the store but not the consumer |
| Azure Key Vault | Workloads under Entra ID, especially with private endpoints and managed identity | Versions accumulate; a rotation policy raises near-expiry events, but you supply the rotation logic | RBAC or access policies, managed identity, soft delete and purge protection | Disabling purge protection; granting Key Vault Secrets User at subscription scope |
| SSM Parameter Store | Small configuration and non-rotating values inside AWS | Manual or custom rotation; SecureString is encrypted with KMS | IAM scoped to a parameter path; limited native cross-account sharing | Treating a parameter as a secret manager with leases it does not have |
The first question is the one that saves the most work. If the workload already authenticates to the cloud where the secret lives, the native store removes an entire credential hop: the CI role or managed identity reads the secret directly, and there is no second token to distribute. Secrets Manager and Key Vault are strongest in that position, because their access control is the cloud's own identity system rather than a parallel one.
Vault earns its extra hop when the estate is not one cloud, or when the credential itself can be issued rather than stored. A database password generated on request, valid for an hour and revoked on lease expiry, is a different security property from a password that sits in a store until someone remembers to rotate it. That property is worth a service to operate. It is not worth it for three static API keys in one account.
The storage model matters less than the rotation model. Secrets Manager rotation runs a function you own, against a database you own, and can fail silently while the store still shows a current version. Key Vault's rotation policy emits an event near expiry; something must consume it. Vault revokes on lease expiry, which is the only one of the three that fails closed on the credential side. For static values in any store, the honest description is "rotation is a scheduled job with an owner", and the runbook should name that owner.
Figure 3 follows a request through policy, decryption and expiry, with the branches that produce support tickets.
%%{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["Workload needs a credential"] --> I{"Already has a cloud
identity in that cloud?"}
I -- "yes" --> N["Native store
Secrets Manager or Key Vault"]
I -- "no, or needs a lease" --> V["Vault as identity broker"]
N --> AU{"Policy allows this identity
on this path?"}
V --> AU
AU -- "no" --> E1["Denied before decryption
fix the policy, not the code"]
AU -- "yes" --> D["Decrypt with the KMS
or transit key"]
D --> L{"Static or dynamic?"}
L -- "dynamic" --> T["Lease with a TTL
revoked at expiry"]
L -- "static" --> R["Version plus a rotation job
old label stays readable"]
T --> U["Value in process memory"]
R --> U
U --> P["Passed to Terraform
variable, data source or provider"]
P --> W["Recorded in state or plan
once it reaches an attribute"]
W --> C["Copies: backup, versioned
object, CI artifact, log"]
X["Secret rotated or deleted"] -. "old value still valid until
revoked at the target" .-> C
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,I,L primary;
class N,V,AU,D secondary;
class T,R,U,P ok;
class E1,X danger;
class W,C warn;
Every branch after "policy allows" produces a value that Terraform will treat like any other string. That is the hinge of this article: the store solves issuance, and none of the three stores solves persistence. A vault can hand you a perfectly leased credential and Terraform will still write it into state the moment it becomes a resource argument.
So choose the store for the trust boundary it fits, then design the Terraform path as if the value will be stored, because it probably will. The next section follows exactly that path.
Trace a Secret Through Variables, Data Sources and Resources
Follow one password from a store to a database and count the copies. Five representations sit on that path, and four persist.
| Representation | What it is | What persists | Who can read it |
|---|---|---|---|
| Variable | An input, from a CI secret or an environment variable | A saved plan file, if one is kept, holds every input value, even when the variable is marked sensitive | Anyone who can read the plan artifact |
| Data source | A read from a secret store | The result, recorded in state under the data source's address | Anyone who can read state |
| Local | An expression evaluated during the run | Nothing on its own; an assigned argument then stores the value in its resource record | The plan process only |
| Resource attribute | An argument sent to the provider | State, inside the resource's record | Anyone who can read state |
| Output | A published value with a wider audience | The state's outputs block, marked for redaction | Any remote-state consumer, along with state readers |
A read is still a write. Reading a secret through a data source looks transient, but Terraform records the result in state under the data source's address, exactly as it records a managed resource.
The resource argument is the copy that matters. Some providers omit an attribute on read for security, but the planned argument is stored in most cases. Where the provider exposes password_wo, use it; the next part covers when that is allowed. Adding sensitive to an argument does not change what the record holds.
Figure 4 places those five representations in a row and marks which ones survive the process.
Two propagation details bite in practice. First, sensitivity is a mark on a value, not a property of the resource: Terraform treats any expression derived from a sensitive variable as sensitive, which is why the redaction follows the value through locals and functions. Second, nonsensitive() removes that mark. It exists for cases where you know a derived value is safe. It is also the escape hatch people reach for when for_each rejects a sensitive map, and using it there is a real leak: the keys become resource addresses, and addresses appear in plans, state and logs.
Reduce copies before hardening them
Minimise copies rather than sanitise them later. Read the secret as late as possible, pass it directly into the one argument that needs it, expose no output, and let the store's own tooling deliver it to workloads that can read it at runtime. Where a provider supports write-only arguments or ephemeral resources, use them; the next part covers the contexts where those values are allowed.
Until then, assume the value is in state. The question becomes how many people and systems can read that state, and for how long.
Sensitive Redacts Output but Does Not Remove Stored Values
sensitive = true is a display instruction. It tells Terraform to print (sensitive value) instead of the value in plan and apply output and in the HCP Terraform UI. It does not encrypt, hash, drop or tokenise anything. The bytes are stored exactly as they were supplied or observed.
Terraform's own documentation is direct about this: values marked sensitive are stored in state and plan files, and anyone who can access those files can access the values. The sensitive_attributes array in state is an index of paths to redact on display. It is not a list of encrypted fields.
Four paths are worth naming separately, because each has a different reader.
State is the primary copy. It holds resource attributes, data source results and root outputs. Reading the object is reading the secrets, which is why the backend identity from the first section is a security boundary and not an implementation detail.
Saved plans are the second copy, and they are easy to forget because they feel temporary. terraform plan -out=tfplan writes the full configuration, every planned value and every input variable, including values redacted on screen. The plan file is how apply can run without re-reading variables, so it must contain them. A plan uploaded as a CI artifact for review is a secret-bearing artifact with a retention clock.
Output commands print plain text by design, and the direct forms do not redact. Terraform's output command treats a named output as an explicit request, so only the listing form hides a sensitive value.
Debug logs are the fourth. TF_LOG=TRACE, the per-component variants, and crash.log capture provider request and response bodies during a failing operation. CI systems capture stdout by default, so a trace enabled to diagnose one failure can deposit a credential in a log that outlives the run. Masking lists help, but they match known prefixes and miss derived values.
Redaction is not storage
Redaction is a rendering decision, not a storage transformation. The same bytes appear in terraform.tfstate, its backup, any saved plan, the JSON form of an output and a verbose log; only the first of those is usually treated as a secret.
The consequence is organisational rather than syntactic. A team can pass a security review with sensitive = true everywhere, a redacted plan screenshot and a Git hook that blocks .tfstate, and still ship a plan artifact with the production password in it. The control that fails is not the annotation. It is the assumption that annotation is protection.
The right mental model is that sensitive protects a screen, and access control protects a file. Both are useful. Only one survives someone downloading the artifact.
Secure Artifacts and Rotate Exposed Credentials
Artifact security starts with an inventory, because the copies are not in one place. For each root, list where its state, backups, plan files, logs and caches live, who can read each, how long each is kept, and which of them are encrypted with a key whose policy the reader cannot change. A state bucket encrypted with the same role policy that reads it is encrypted in name only.
Four controls do most of the work, in this order.
Do not store the value. Ephemeral values and write-only arguments keep a secret out of state and plan entirely, where the provider supports them. This is the only control that removes a copy rather than guarding it. It is also the one with the most constraints, which is why it has its own part.
Encrypt with a separate key boundary. SSE-KMS on the state bucket, a customer-managed key in Key Vault or Cloud KMS, or HCP Terraform's hold-your-own-key. Encryption protects against a reader who can reach the storage object but not the key: a leaked snapshot, a misconfigured replica, a bucket copied to another account. It does not protect against the role that reads state legitimately, because that role must also be able to decrypt. The key policy should be owned above the workload, and no workload role should be able to change it.
Restrict readers per environment. One state key per environment, in a separate account or subscription where the blast radius justifies it. Bucket policy on the exact key, not the prefix. No terraform_remote_state grant to another team as a convenience; publish the one output instead, as the remote-state part argued.
Expire aggressively. Plan artifacts measured in days, not the platform default of ninety. Noncurrent state versions expired on a schedule you have tested a restore from. Log retention set per policy, with the understanding that a TRACE log is a secret-bearing document. Caches and test fixtures are artifacts too, and they are the ones nobody lists.
Rotation is where the ordering matters, and the common sequence is backwards. Changing var.db_password and applying updates state and the database, but the old credential remains valid at the target until it is changed there, and every old artifact still contains it. Revoking before the replacement is deployed is equally wrong: the connect path still needs a working credential, and you would be debugging an outage and a rotation at the same time.
Rotation order: issue, deploy, verify, revoke, purge
Purging is last for a reason. Until revocation succeeds at the target, the old value is still live, and you may need the artifact to debug the rollback. Figure 5 contrasts the two orders.
Two state commands create false confidence. Both change the current file, not the history behind it.
The edited state may be valid, but history is not. The previous version is still in the bucket, the backup sits beside the state, and the managed object may still hold the credential. Sanitising state by editing is a story about the current file, not about exposure.
What actually reduces exposure is a short, ordered list: revoke at the source, replace the value, confirm the consumer works, then delete the copies you can reach and expire the ones you cannot. Record the rotation in the same place you record the incident, so the next person knows which copies were considered.
Write an OIDC Trust Policy with a Narrow Subject
A trust policy is the whole security model in one document. The cloud does not know your repository; it knows the claims in the token. If the policy accepts any repository in your organisation, then any repository in your organisation is an identity that can assume the role.
Start with three exact matches. The issuer identifies the token service and must be the literal URL, not a pattern. The audience must be the value your cloud expects: sts.amazonaws.com for AWS, api://AzureADTokenExchange for Entra ID. The subject is where the specificity lives, and it is where most policies are too generous.
GitHub's subject formats are worth memorising:
repo:org/repo:ref:refs/heads/mainfor a job on a branch.repo:org/repo:pull_requestfor a pull request job.repo:org/repo:environment:productionfor a job that declares that environment.
The first two are easy to write and easy to get wrong. A branch subject means any workflow on that branch can assume the role, including a workflow file added by a merged pull request. A pull_request subject means any pull request job that is granted the token, including one opened by a contributor, can assume it. Neither is automatically unsafe, but both put the control in code review rather than in the deployment gate.
The environment subject is stronger because the environment has protection rules: required reviewers, a deployment branch policy, a wait timer. The token is only minted after those rules pass, so the human approval becomes part of the authentication. That is the cleanest way to separate plan from apply. The plan role trusts a branch or pull request subject and holds read-only permissions. The apply role trusts environment:production and holds write permissions. A merged change can produce a plan; only an approved deployment can produce an apply.
Two extra constraints close the obvious holes. Add job_workflow_ref when the deployment runs through a reusable workflow, so the token must come from that workflow file and not from any workflow in the repository. And make sure neither role can modify the OIDC provider, its own trust policy, or the state bucket policy. Otherwise an apply role can grant itself a new subject and the narrow claim means nothing.
Audit the credential journey
Status: design-only. No cloud account, token or credential is used. The exercise produces an exposure map, two trust policies, a permission matrix and a retention checklist for one CI system. Every account identifier below is a placeholder.
Prerequisites. Terraform CLI 1.17.1 (terraform version), a text editor, and read access to one repository's CI configuration. No cloud credentials.
Minimal setup. Create one lab folder, such as labs/p20/, with six deliverables, then pick one repository and one deployment target. If you have no CI system to inspect, use a GitHub Actions repository whose workflow runs a plan on pull requests.
| Deliverable | File | Pass condition |
|---|---|---|
| Identity inventory | identities.md | Four identities, static keys flagged |
| Exposure map | exposure-map.md | Every artifact has a reader, retention and owner |
| Plan trust policy | trust-plan.json | Exact audience and subject, no wildcard |
| Apply trust policy | trust-apply.json | Exact environment subject, no wildcard |
| Permission matrix | matrix.md | Plan writes only the lock; apply cannot edit policies |
| Rotation checklist | rotation.md | Issue, deploy, verify, revoke, purge; named owner |
- Inventory four identities: the human SSO path, the CI plan identity, the CI apply identity, and the backend identity. For each, record how it authenticates, its maximum lifetime, and what it can read. Mark any identity that is a static key as a finding.
- Build the exposure map. For the target root, list every artifact that can contain the secret: state object,
.backup, noncurrent versions, saved plan, plan JSON, workflow log,crash.log, module cache, ticket attachment. Give each a reader group, a retention period and an owner. The map passes only if no artifact has "everyone in the org" as its reader group. - Write the plan trust policy with a branch subject. Keep it to the two conditions below, substituting your own organisation and repository. Do not widen the subject to a wildcard to make it work.
- Write the apply trust policy with an environment subject, then add the environment's protection rules to
matrix.md: required reviewers, deployment branch policy, and who can approve. If the repository has no protected environment, that is the first finding, not a detail. - Build the permission matrix. Plan: read the state key, read and write the lock object, read-only on the target resources, no IAM or role changes. Apply: read and write the state key, deploy permissions, and still no permission to change the trust policy or the bucket policy. One row per action, one column per role.
- Tabletop three failures. A workflow file on
mainis changed by a merged pull request: which role can it assume? A contributor opens a pull request from a fork: does a token get minted, and does the subject match? A plan artifact from three weeks ago is downloaded: which secret does it contain, and is it still valid? - Write the rotation checklist in the order from the previous section: issue, deploy, verify, revoke, purge. Add the artifact list from step 2 with a delete-or-expire action for each. Name the person who owns the purge.
The two policy bodies, with placeholders left in place:
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Federated": "arn:aws:iam::<account-id>:oidc-provider/token.actions.githubusercontent.com"},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:<org>/<repo>:ref:refs/heads/main"
}
}
}]
}
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {"Federated": "arn:aws:iam::<account-id>:oidc-provider/token.actions.githubusercontent.com"},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
"token.actions.githubusercontent.com:sub": "repo:<org>/<repo>:environment:production"
}
}
}]
}
Expected observation. Two policies that differ only in the subject, two roles with visibly different permissions, and an exposure map where every artifact has a named reader, a retention period and an owner. The plan role should be unable to change anything outside the lock.
Failure check. The lab fails if either subject contains *, if one role covers both plan and apply, if the apply role can edit its own trust policy, if the exposure map omits the saved plan or the state backup, or if the rotation checklist starts with terraform apply.
Cost and cleanup. Zero: no cloud resources and no tokens. Delete labs/p20/ after capturing the evidence, or keep it as a reviewed design document with placeholders intact. Nothing in the lab should ever contain a real account identifier or secret.
Evidence to keep. The four-identity inventory with static keys flagged, the exposure map with owners and retention, both trust policies with placeholders, the permission matrix, and the ordered rotation checklist with a named purge owner.
Next in the Series
In Ephemeral Values and Write-Only Arguments in Practice, we'll explore Keep supported temporary values out of Terraform artifacts while understanding provider limits.