Back to Terraform

Key Vault and Managed Identity: Permissions, Secret Persistence and Recovery

November 6, 2026 Wasil Zafar 18 min read

Separate secure storage, caller authorization and Terraform artifact exposure

Table of Contents

  1. Separate Vault, Key, Secret and Certificate Ownership
  2. Trace Managed Identity Authorization Through the Data Plane
  3. Prove the Network Path Before Debugging Permissions
  4. Inspect State and Historical Artifacts with Synthetic Values
  5. Rehearse Rotation and Soft-Delete Recovery

Separate Vault, Key, Secret and Certificate Ownership

A vault is a container, not a secret. It supplies a name, a region, a network boundary, a permission model and a retention policy. The values inside it are separate objects with separate lifetimes, and treating the vault as the unit of ownership produces one identity that can rewrite everything.

The platform team owns the boundary. That team decides whether the vault accepts public traffic, which private endpoint and DNS zone serve it, whether soft delete is backed by purge protection, and whether authorization runs through Azure RBAC or access policies. None of those choices belongs to the application that stores one connection string.

Each object type has a different writer. A key is created by the team that owns the cryptography, because its operations and rotation policy are a cryptographic contract. A secret is created by the application team that knows when the credential changes. A certificate is created by the team that terminates TLS, because renewal is tied to an endpoint and a hostname.

Rotation is an ownership claim, not a permission. The principal allowed to write the next version is the rotation owner, and that is usually a different identity from the reader. A reader with get-only rights cannot rotate, which is deliberate: reading a credential and replacing it are different levels of trust.

One object, one writer. Managing the same secret through an inline access-policy block and a separate policy resource produces a permanent diff; managing the same secret in two Terraform states is worse, because each apply restores its own value. Pick one owner per object and reference it everywhere else.

The permission model is a vault-level decision, and 5.13 makes it explicit. rbac_authorization_enabled is required, so a missing value fails validation instead of silently defaulting. Switching it later needs an unrestricted role-assignment write, which Contributor does not have.

Separate Vault, Key, Secret and Certificate Ownership
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','tertiaryColor':'#c4873b','tertiaryTextColor':'#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','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    V["Key Vault
platform team owns the boundary"] --> K["Key
crypto owner writes"] V --> S["Secret
application owner writes"] V --> C["Certificate
edge owner writes"] K --> KC["Consumer
encrypt, decrypt, sign"] S --> SC["Consumer
read at runtime"] C --> CC["Consumer
terminate TLS"] K -.->|"next version"| R["Rotation owner
writes a new version"] S -.->|"next version"| R C -.->|"renewal"| R R -.-> A["Audit record
principal, object, version"] N["Reader role
no write"] -.->|"get only"| SC 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 V primary; class K,S,C secondary; class KC,SC,CC,A ok; class R warn; class N danger;

Figure 1 separates the container from its contents. The dashed edges are the ones that matter in review: a reader never becomes a writer by accident, and every new version leaves an audit record with a principal attached.

Four Key Vault objects, their owning teams, and the boundary the platform team controls A vault boundary owned by the platform team contains a key owned by the crypto team, a secret owned by the application team, and a certificate owned by the edge team. Each object feeds a different consumer. A footer states that rotation is a write, not a permission. Four objects, four owners, one boundary VAULT BOUNDARY — PLATFORM TEAM Key — crypto owner wrap, unwrap, sign; the rotation policy owns versions Secret — application owner runtime credential; every write creates a version Certificate — edge owner TLS termination; renew before expiry, not after an outage Encrypt and decrypt workloads holding the crypto role Read at runtime the workload identity, never the plan Terminate TLS the edge endpoint and its clients Rotation is a write, not a permission. Name the principal that may create the next version, and keep it separate from every reader.

Figure 2 draws the layer that contains the objects and the readers outside it. The vault boundary protects the objects, while rotation and audit sit beside the reader rather than inside its permission.

ObjectCreatorReaderRotation ownerTerraform resource
Vaultplatform teamcontrol-plane readers onlyplatform teamazurerm_key_vault
Keycrypto ownerworkloads that encrypt or signcrypto ownerazurerm_key_vault_key
Secretapplication teamruntime identity, never the plan stepapplication teamazurerm_key_vault_secret
Certificateedge teamTLS endpoint and its clientsedge teamazurerm_key_vault_certificate

Read the table as an ownership contract. A row with two creators is a review failure, because both will eventually believe they are authoritative. The Terraform resource column is also the blast radius: whoever can change that address can replace the object.

Scale changes the representation, not the rule. A handful of principals can live in access policies; many teams usually need RBAC groups and a narrower set of role assignments. Either way, the vault owner grants access and the object owner writes the value.

Trace Managed Identity Authorization Through the Data Plane

Authentication answers who is calling; authorization answers what this vault allows. A managed identity can obtain a valid token and still be refused, because the vault evaluates a data-plane role or access policy after the token is accepted. A successful control-plane read proves neither.

The two planes use different endpoints and different permissions. Azure Resource Manager manages the vault resource itself, and Contributor is enough for that. Secret, key and certificate operations go to the vault endpoint, where a data-plane role is required.

The token audience is part of the failure surface. A token minted for Azure Resource Manager is not accepted by the vault; the caller must request one for the vault audience. A 401 usually means audience, tenant or expiry, not a missing role.

Role choice is narrower than the vault. Key Vault Reader sees metadata only, Secrets User reads values, Secrets Officer writes them, and Administrator covers the data plane. Grant at the vault scope, not the subscription, unless every vault in that subscription has the same readers.

Access-policy mode is still supported, and it is a different audit model. Each azurerm_key_vault_access_policy carries an explicit list of key, secret and certificate permissions, capped at 1024 policies per vault. That is precise for a handful of principals and expensive to review at scale.

The mode cannot be mixed. Inline policies and separate policy resources fight over the same collection, and the provider documents the conflict. Choose one representation per vault before the first apply.

Propagation is eventual, and the graph does not model it. An azurerm_role_assignment can be complete while Azure is still distributing the grant. Ordering the secret after the assignment is necessary but not sufficient, so the first apply may fail and the second may succeed.

A group assignment is the scalable unit. Put readers in one group and assign once; then membership changes are directory operations, not vault changes. Keep writers in a separate group so rotation rights never ride along with read access.

Trace Managed Identity Authorization Through the Data Plane
%%{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','tertiaryColor':'#c4873b','tertiaryTextColor':'#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','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Managed identity
or workload identity"] --> B["Request a token
from IMDS or federation"] B --> C{"Audience is the vault?"} C -->|"no"| X1["401 Unauthorized
wrong resource or tenant"] C -->|"yes"| D["HTTPS request
to the vault FQDN"] D --> E{"Name resolves to
the private endpoint?"} E -->|"no"| X2["403 ForbiddenByFirewall
public path is closed"] E -->|"yes"| F{"Permission model"} F -->|"Azure RBAC"| G{"Data-plane role
at vault scope?"} F -->|"access policy"| H{"Policy object ID
with Get permission?"} G -->|"no"| X3["403 AccessDenied
token was valid"] H -->|"no"| X3 G -->|"yes"| I["Vault data operation allowed"] H -->|"yes"| I I --> J["Audit record
principal, object, version"] 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,D primary; class B,C,E,F,G,H secondary; class I,J ok; class X1 danger; class X2,X3 warn;

Figure 3 ends at the audit record, because success is not the only outcome worth tracing. The three failure branches are deliberately different: wrong audience, wrong network path, and wrong data-plane grant.

Read the status code before changing anything. 401 points at the token, 403 with a firewall message points at the path, and 403 with an access-denied message points at the role. A 404 can mean the object was soft-deleted rather than never created.

Prove the Network Path Before Debugging Permissions

A private endpoint changes the address, not the authorization. The vault still authenticates the caller and still evaluates the same role or policy. What changes is which address answers, and therefore whether the request reaches the service at all.

Resolve the name from the runner that failed. A correct private path returns a CNAME into privatelink.vaultcore.azure.net and an RFC 1918 address. A public address from inside the VNet means the zone is missing, unlinked, or not reachable through the resolver in use.

The runner is part of the path. A hosted CI agent outside the VNet cannot use a private endpoint no matter which role it holds; a self-hosted agent in the wrong subnet has the same problem. Name the runner before naming a permission.

Public access and the firewall are separate switches. Disabling public access closes the public endpoint; a default-deny ACL closes everything not explicitly allowed. Both can produce a 403, and neither is fixed by adding a role.

The trusted-services bypass is not a runner bypass. It admits specific Azure services, not an arbitrary pipeline or laptop. A private endpoint remains the supported path for a runner that must reach a closed vault.

DNS forwarding is the usual break. A hub zone linked only to the hub VNet does not answer for a spoke; the spoke needs a link or a conditional forwarder to Azure DNS. Test resolution after every peering and every zone change.

Prove TCP 443 before the SDK. If the name resolves but the port is closed, the error will look like a timeout rather than an authorization failure. A socket test separates reachability from policy.

Then make one data-plane read from the same runner. A single secret read with the workload identity distinguishes an authorization problem from a routing problem, and it produces the principal and object name the audit needs.

Keep the evidence, not the guess. Record the resolved address, the zone link, the private-endpoint connection state and the exact error code. That record is what prevents the next person from granting a broader role to "fix" a DNS fault.

Inspect State and Historical Artifacts with Synthetic Values

A read is still a write to state. A data source that fetches a secret records the value in the state file, so reading from the vault does not keep it out of Terraform's artifacts. The provider says this plainly, and the plan rarely shows it.

The secret resource has the same property. The ordinary value argument is stored as plain text in raw state; redaction in the CLI is a display rule. In 5.13 the write-only alternative keeps the value out of plan and state, and leaves a version counter behind.

Sensitive is not a storage control. It hides a value in human-readable output and requires matching sensitive outputs; it does not encrypt state, purge a plan file or stop a debug log. Treat it as handling guidance, not as a boundary.

Artifacts multiply after the apply. A saved plan, the state file, each state version, CI logs, provider debug output and a terminal scrollback can each hold the same value. The one you remember is rarely the one that leaks.

History outlives the resource. Backend versioning keeps old state objects after the secret is rotated or destroyed, and pull-request artifacts can keep a plan long after the branch is gone. Retention policy is part of the secret's lifetime.

Use a synthetic canary, never a credential. A unique marker written as the secret value can be searched across state, plan and logs without exposing anything real. If the marker appears, the artifact holds it; if it does not, the claim is testable rather than assumed.

Where a synthetic secret value persists, compared with a write-only argument On the left, an ordinary value passes through a saved plan, state and retained state versions, with sensitive only redacting the display. On the right, a write-only value reaches the provider but leaves only a version integer in state. A footer states that reading from the vault still writes a copy. The read path is not the storage path ORDINARY VALUE value = synthetic canary saved plan — plaintext value state — plaintext value retained state versions keep the copy sensitive = true redacts the display only WRITE-ONLY VALUE value_wo at apply time provider call — no artifact state — write-only attribute version integer remains Reading a secret still writes a copy. Only the write-only path keeps the value out of plan and state.

Figure 4 compares an ordinary value with a write-only one. The left path stores the marker in the plan, state and every retained state version; the right path leaves only the version integer that triggered the write.

Absence in the plan is not absence in state. Those are different files written at different times, and a value can be redacted on screen while remaining readable in both. Check the artifact you actually intend to defend, then expire the ones you cannot.

Rehearse Rotation and Soft-Delete Recovery

Rotation creates a version; it does not erase the old one. A versioned identifier pins the value the consumer read before rotation, while a versionless identifier follows the latest. A consumer that caches the versioned form keeps presenting the old credential while the vault still holds that version, and nothing in the plan will warn you.

Write-only rotation is a version bump. value_wo carries the new value and value_wo_version is what the plan compares, so the counter must change for the write to happen. Changing only the value produces no persisted diff, which looks like a no-op.

Keys can rotate on a policy; secrets need an owner. A key rotation policy can create a new version automatically before expiry, and a certificate policy can renew on a lifetime trigger. A secret rotation policy can notify near expiry, but the code that writes the new value is still yours.

Soft delete is always on; purge protection is the irreversible choice. soft_delete_retention_days accepts 7 to 90 days and can be configured once, while purge_protection_enabled keeps deleted objects beyond the reach of purge. Once enabled, purge protection cannot be turned off.

Terraform's destroy defaults to purge. This is the sharpest trap in the lifecycle: purge_soft_deleted_secrets_on_destroy defaults to true, so with purge protection off a destroy permanently removes the object rather than leaving it recoverable. A recovery rehearsal must turn the purge toggle off before the destroy, not after.

Recovery is not a restore of the same version. For a secret, the provider recovers the object and then writes the configured value, producing a new version. That is safe for a secret the pipeline owns and wrong for one that was rotated outside Terraform, because the new version overwrites the external state of the world.

A soft-deleted vault blocks its own name. Vault names are globally unique, and the name stays reserved until the vault is recovered or purged. Create-after-destroy fails for a reason that has nothing to do with permissions.

Rehearse in dependency order. Recover the vault, then the objects, then verify the version, and only then restart the writers. A writer that runs between steps recreates the object and races the recovery.

Lab

Rehearse Rotation and Soft-Delete Recovery

Status: design-only. No Azure subscription or credential was used here, and none of these steps were executed. The vault, secret and canary are synthetic, and every identifier is a placeholder you supply in your own sandbox.

Prerequisites. Terraform 1.17.1, hashicorp/azurerm 5.13.0, a sandbox vault with purge protection off, and permission to read, write, recover and purge secrets. The vault must be disposable; no production value enters this lab.

Setup. One secret with a canary value, a write-only variant with a version counter, and a provider feature block that disables purge on destroy and enables recovery. Keep the state in a local backend so the retained artifacts are easy to inspect and easy to delete.

CaseSettingExpected result
Rotate a write-only secretincrement the version countera new version appears, the old version stays readable by its versioned ID
Destroy with defaultspurge toggle left at truethe object is permanently removed and the name becomes reusable
Destroy for recoverypurge toggle false, recovery truethe object is soft-deleted and the name stays blocked
Purge under protectionpurge protection enabledthe purge is rejected until the retention window ends
  1. Write the canary value and confirm the secret has a version identifier, not only a versionless one.
  2. Read the secret through the runtime identity, then through the plan identity; record which one fails and why.
  3. Rotate by incrementing the write-only version counter, and confirm the old version still resolves by its versioned identifier.
  4. Run a destroy with the rehearsal feature block, then confirm the secret is in a deleted state rather than absent from the vault.
  5. Recover the object, apply again, and compare the recovered version with the version that existed before the destroy.
  6. Repeat the destroy with the default purge toggle, and confirm recovery is no longer an option.
  7. Enable purge protection on a separate vault, delete one object, and attempt a purge to capture the rejection.

Expected observation. The rehearsal path leaves a recoverable object with a new version after recovery; the default path leaves nothing to recover. The purge-protection vault rejects the purge without changing the object's deleted state.

Failure check. If the same name is immediately reusable after a destroy, the purge toggle was active. If recovery produces the old version unchanged, the provider did not write the configured value. If a consumer still authenticates with the old credential after rotation, it resolved a versioned identifier or cached the value.

Evidence to keep. The version identifiers before and after rotation, the feature-block values, the destroy and recovery transcript with exit codes, and the purge rejection. Keep the canary, never a real credential.

Next in the Series

In Azure Edge and Governance: Front Door, DNS, Monitor and Policy, we'll explore Coordinate delivery policy, telemetry and Azure administrative controls around observable requirements.