Map KMS Keys, Service Agents and Workload Permissions
A key ring is a location, not a secret. It groups keys that live in one place and holds nothing else: no key material, no caller-facing permission, and no delete call that removes it. Destroying the Terraform resource only drops it from state, so the ring stays in the project and its name stays taken.
Destroy is not deletion
A key ring is a location boundary, not a deletable secret. Removing it from Terraform only removes your record; the ring remains in the project and the name stays taken, so plan the name and location as permanent.
A key is a purpose plus a policy. The purpose is immutable, so an encrypt-decrypt key can never become a signing key, and the rotation period decides when the service promotes a new primary version. The version template decides the protection level for future versions, which is a compliance decision rather than a performance one.
A version is the only object that performs cryptography. Rotation appends a version; it does not re-wrap data that an older version encrypted. A disabled version stops decrypting at once, and a destroyed version takes every wrapped data key with it, which is the reason a scheduled destruction delay exists.
Encryption configuration is not authorization. Declaring a default key on a bucket, a disk, or a secret chooses which key protects the bytes. It grants no caller the right to use that key, and reviewing the encryption setting tells you nothing about who can decrypt.
Encryption is not authorization
Choosing a default key decides which key protects the bytes; it grants nobody the right to use it. Verify the key-level IAM grant separately, and test a decrypt as the workload identity rather than reading the bucket setting.
Three callers need three different grants. The service agent of the consuming service uses the key on your behalf. A workload that calls the KMS API directly authenticates as its own service account. A human operator debugging an outage authenticates as a person. Each evaluation is separate.
Grant on the key, not on the project. A project-level grant reaches every key ring in the project, including rings another team owns. The google_kms_crypto_key_iam_member resource writes one principal onto one key, which is the smallest scope the API offers.
Service agents are Google-managed identities with recognizable addresses. Storage's agent lives in the gs-project-accounts domain and Secret Manager's in gcp-sa-secretmanager; the local part carries the project number. Read the address from the project's IAM page rather than typing one from memory, because the number is the part that must match.
The failure names the layer, and the layer names the fix. A missing grant on the service agent breaks the service's own wrap operation, so the caller sees a service error rather than a KMS error. A missing grant on the workload identity produces a permission denial from the KMS API itself.
Location is part of the key's identity. A regional resource needs a key in a compatible location, and a multi-region resource needs a matching multi-region key; the service's documentation lists the valid pairings. The location is fixed when the key is created, so a later move is a new key and a re-encryption project, not an edit.
Figure 1 asks who is calling before it asks which key exists.
%%{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','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
W["Workload or operator
presents a principal"] --> D1{"Calls KMS directly,
or through a service?"}
D1 -->|"direct Encrypt or Decrypt"| K1{"Role on this key
for the workload?"}
D1 -->|"storage, SQL, secrets"| S1["Google service acts
with its own agent"]
S1 --> K2{"Role on this key
for the service agent?"}
K1 -->|"no"| E1["PERMISSION_DENIED
caller is the workload"]
K2 -->|"no"| E2["Service-side failure
on wrap or unwrap"]
K1 -->|"yes"| V{"Key version
ENABLED?"}
K2 -->|"yes"| V
V -->|"no"| E3["FAILED_PRECONDITION
disabled or destroyed"]
V -->|"yes"| OK["Operation allowed
principal, key, version logged"]
R["Key ring
location boundary"] -.->|"contains"| V
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 W,D1,K1,K2,V primary;
class S1 secondary;
class OK ok;
class E1,E2 danger;
class E3 warn;
class R secondary;
Figure 1 separates the two ways a key gets used. The left branch is a workload holding a role on the key; the right branch is a Google service using its agent. Both converge on the version state, because an enabled role on a destroyed version still fails.
Figure 2 draws the boundary that survives a destroy. The ring outlives the key, the key outlives its versions only as a container, and the version is where both the permission check and the destruction decision land.
Review the grant list rather than the encryption checkbox. A resource that declares a key but grants nothing to its service agent fails on the first write, and a key that every project can use is a key with no owner. The pair of settings is the contract: which key, and which principal may use it.
Rotation is not a re-encryption plan. A rotation period limits how long a single version encrypts new data; stored ciphertext stays under the version that wrapped it. Moving old data to a new version is a rewrite project with its own owner and rollback.
Choose Secret Provisioning, Retrieval and Rotation Owners
A secret is a name and a replication policy. The replication choice is fixed at creation, so automatic replication and user-managed replicas are different objects rather than a setting you can revisit. Changing your mind means a new secret, and existing versions do not follow it.
A version is an immutable payload. Adding a version creates a new object with a new number; the previous payload is never edited in place. The latest alias follows the newest enabled version, while a pinned version keeps returning its own bytes until someone disables or destroys it.
Reading a payload is a data-plane permission. The roles/secretmanager.secretAccessor role returns bytes; a metadata reader sees names, labels, and versions but not the value. Grant the reader role at the secret, not the project, and keep it separate from every write role.
Writing the next version is a different role. The version manager role adds and destroys versions, which makes it the rotation role. A consumer that can only read cannot rotate, and that separation is deliberate: reading a credential and replacing it carry different levels of trust.
Terraform can own the container without holding the plaintext. An ordinary payload argument is stored in state, so the pipeline becomes a secret holder whether or not it wanted the job. The write-only argument plus its version counter keeps the value out of plan and state, and the counter is what tells the provider to write again.
The rotation block notifies; it does not rotate. A rotation period requires a Pub/Sub topic and publishes a message when the interval elapses. The code that mints the new credential and adds the version is still yours, and so is the failure when that code stops running.
Destruction is a state machine, not a delete call. A version can be disabled first, and a version destroy TTL keeps it disabled for a chosen window before the bytes are removed. That window is the difference between a reversible mistake and an outage with no recovery path.
A data source is still a read, and a read writes state. Fetching a secret into Terraform records the payload in the state file, and the plan view hides it from humans rather than from the artifact. No data source prevents persistence; only never reading the value does.
Figure 3 follows a payload from the owner who writes it to the consumer who must stop using it.
%%{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','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["Owner decides the value
and its lifetime"] --> B["Secret container
replication fixed at create"]
B --> C{"Who writes the
next version?"}
C -->|"Terraform root"| D["Payload argument
stored in state"]
C -->|"runtime writer"| E["Writer adds version
with its own credential"]
D --> F{"Consumer holds
secret accessor?"}
E --> F
F -->|"no"| X1["PERMISSION_DENIED
no payload returned"]
F -->|"yes"| G["Payload returned
DATA_READ entry written"]
G --> H["Rotation publisher
adds the next version"]
H --> I{"Old version
still enabled?"}
I -->|"yes"| J["Two valid credentials
until the consumer moves"]
I -->|"no"| K["Disabled, then destroyed
after the destroy TTL"]
B -.->|"replication edited"| X2["Secret replaced
versions do not follow"]
B -.->|"rotation block only"| X3["Pub/Sub notice sent
no value written"]
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,C,F,I primary;
class B,D,E secondary;
class G,H,J ok;
class X1,X2 danger;
class K,X3 warn;
Figure 3 puts the failure branches where they actually occur. The solid denial is a missing permission; the dashed branches are design errors that a plan will happily render as a replacement.
Read the plan for a replacement, not an update. Editing replication forces a new secret, and the old versions die with the old object. A routine refactor becomes a credential outage, and the plan says so if you read the action rather than the summary.
Destroy protection belongs to the object with the longest life. A secret can carry a deletion policy that refuses destroy, and the version carries its own policy that can disable or abandon instead of deleting. Use the version policy for rotation hygiene, and the secret policy for the object a service will still need tomorrow.
Configure Logs, Metrics and Alert Destinations
Admin Activity is the floor, not the ceiling. These entries are always on, free, and retained for 400 days in the required bucket. They record the control-plane moves that matter for ownership: creating a secret, adding a version, destroying one, and changing its IAM policy.
Data Access is opt-in, and the gap is the whole story. Reading a payload is a data read, and metadata reads are recorded there too even though their permission type is admin read. The log type is enabled per service through an audit configuration, and it is billed, so the day you enable it is the first day of that evidence.
KMS use lands in the same category. Encrypt and decrypt are data reads, recorded with the key, principal, and version. They prove a key was used, not what the plaintext said.
A denial is only evidence if the log type was already on. A refused payload read produces no admin activity entry, because the method is a data read. Teams discover this during the incident, when the missing entry is the one they need.
Retention is a bucket property, and a bucket is not deletable at will. The default bucket holds 30 days, the required bucket holds 400, and a custom bucket can hold up to 3650. Locking a bucket freezes its retention, and a locked bucket can only be removed while it is empty.
A sink is an ownership decision before it is a filter. The unique writer identity is the only principal that should write to the destination, and it needs the bucket writer role on a log bucket. An exclusion is a decision to have no evidence, not a cost control.
Independence is what makes a log trustworthy. A sink that writes back into the project the workload administers can be disabled by the same principal that disables the workload. Put the destination in a separate project with a different owner.
Metrics and alerts prove arrival, not intent. A log-based metric counts specific audit entries, and an alert policy on that metric tells you the pipeline stopped. An alert to the workload team is a notification; to the control owner, whose recovery runbook names the same person, it is evidence.
The table compares what each layer can actually prove on the day someone asks.
| Evidence layer | What it proves | Default state | Where it lands | Blind spot |
|---|---|---|---|---|
| Admin Activity | who created, changed, or destroyed a secret or key | always on, no charge | required bucket, 400 days | never shows a payload read |
| Secret Data Access | which principal read which secret version, and when | off until configured | chosen log bucket or sink | absent for every day before enablement |
| KMS Data Access | which principal used which key and version | off until configured | chosen log bucket or sink | names the key, never the plaintext |
| Sink delivery | that entries reached a destination another team owns | absent until a sink exists | destination project bucket | a broken writer identity is silent |
| Log-based alert | that the expected entry stopped arriving | absent until a metric exists | notification channel | alert fatigue hides a real gap |
Set retention before the incident, and lock it before the audit. Raising retention after the fact cannot recover entries that were already deleted, and locking is one-way for the retention period. Both actions belong in the platform root, with a named owner and a change record.
Separate Organization Policy from Terraform Run Policy
Organization policy constrains every caller, including Terraform. It is evaluated by the API on the request, so it applies to the console, a one-off script, and a pipeline alike. That universality is why it belongs to an organization or folder administrator rather than to the root that manages a project.
Run policy is what the pipeline identity may attempt. The CI service account's roles decide which calls can be made, and the state backend decides which objects it can reach. Broad project roles can still be stopped by a constraint; narrow roles are already stopped by IAM.
The plan never evaluates organization policy. Planning reads state and calls read APIs; the constraint is checked when the write arrives. A green plan followed by a failed apply is the normal signature, so a successful plan is not an authorization decision.
Three KMS constraints carry most of the value. constraints/cloudkms.disableBeforeDestroy forces a version to be disabled before destruction, constraints/cloudkms.minimumDestroyScheduledDuration sets a floor on the delay, and an allowed protection level list limits which key types may be created.
Inheritance differs by constraint type. A list constraint can inherit from its parent or become a new root; a boolean constraint inherits unless a policy at the resource resets it to the constraint default.
A dry run is the safe way to learn the blast radius. A dry-run spec records what the policy would have blocked without blocking it, which is how you find the one legacy workload that still creates software keys. Promote it to enforcement after the violations are zero, not before.
Only an organization administrator should change these policies. The pipeline that creates keys should not be able to remove the constraint that protects them, or the control is advisory. Keep the policy root in a separate state with a different approver, and document the break-glass identity that can act when that root is unavailable.
A denial surfaces as a precondition failure that names the constraint. The message is specific enough to route: the constraint name identifies the control, and the resource name identifies the caller's intent. The failed call also appears in Admin Activity, which is how you prove the attempt happened even though it changed nothing.
Figure 4 contrasts a run policy acting alone with the two-plane arrangement.
Figure 4 shows where the two planes sit relative to each other. The pipeline can only attempt; the organization decides. When both live in the same root, the constraint becomes a suggestion that the next refactor can delete along with the key.
Write down the administrator scope before you need it. Name who may edit the policy, which identity acts during break-glass, and where that policy's state lives. Otherwise the control is a memory of a console click.
Investigate a Harmless Denial with Redacted Evidence
The lab produces one denial and one success, both synthetic. A secret holds a canary string rather than a credential, a test service account starts with no access, and the only thing collected is the audit entry. Terraform 1.17.1 and hashicorp/google 8.10.0 are part of the record because provider defaults change between minor versions.
Investigate a Harmless Denial with Redacted Evidence
Execution status: design-only. None of these steps were run against a live project, and no identifier below is real. Substitute your own project, project number, and service account in a disposable sandbox.
Prerequisites. A disposable project, permission to create secrets and service accounts, permission to edit the project audit configuration, and read access to Cloud Logging. Terraform 1.17.1 with hashicorp/google 8.10.0. One synthetic value, clearly labeled as a canary, and no production credential anywhere in the root.
Setup. One secret with user-managed replication in a single region, one version holding the canary, and one test service account with no secret role. Enable data-read audit logging for Secret Manager before the first read, because a denial before enablement leaves no entry to study.
| Check | Evidence to capture | Pass looks like |
|---|---|---|
| Container | plan and state for the secret | replication matches the declared location |
| Version | version number and state | the canary version is ENABLED |
| Denied read | the access attempt as the test account | permission denied, no payload printed |
| Denial entry | one filtered audit record | principal, method, and status, no payload |
| Granted read | the same read after the grant | payload returns, new entry names the version |
| Sink arrival | the same entry in the destination project | same insert ID, other project, other owner |
| Destroy guard | a destroy with the policy in place | refused, object unchanged |
- Record a baseline plan and confirm it is empty before adding anything. A non-empty baseline makes every later diff ambiguous.
- Create the secret with replication pinned to one location, then add the canary version. Note the version number the provider reports, because the denial entry will name it.
- Enable data-read audit logging for Secret Manager in the project and wait for the configuration to take effect. Confirm the setting by reading it back, not by assuming the apply was enough.
- As the test service account, attempt to read the version. Expect a permission denial, and capture only the error code and the principal, never the returned body.
- Query the log destination for that principal and the access method, projecting a small field set: principal, method, resource, status code, and timestamp. Do not print the whole entry.
- Grant the secret accessor role on the secret to the test account, repeat the read, and confirm that the payload returns and a second entry appears with the same principal and a success status.
- Point a sink at a bucket in a second project, read the version once more, and look for the entry at the destination. If it is missing, the writer identity or an exclusion is the cause.
- Temporarily set the deletion policy that prevents destroy, run a destroy, and capture the refusal. Restore the policy afterwards so the lab can still be cleaned up.
- Rotate by incrementing the write-only version counter, confirm a new version exists, and confirm the old one stays enabled until you disable it.
- Clean up in reverse order: remove the grant, destroy the lab root with the restored policy, and verify the destination bucket still holds the evidence you collected.
Expected observation. The denial appears only after data-read logging is enabled, and the entry names the principal, method, resource, and status. The granted read produces a matching success entry, and the destination holds both.
Failure checks. No denial entry means the log type was off or the filter named another service. A payload with no entry means the audit configuration landed in a different project. Source entries with an empty sink mean the writer identity lacks the destination role.
Redaction rules. Keep the principal, the method, the resource, and the status. Drop request and response bodies, and anything that could carry a credential. A canary that never leaves the sandbox is safe to search for; a real value is not safe to prove anything with.
Evidence to keep. The empty baseline plan, the audit configuration read-back, the denial entry, the success entry, the destination copy with its insert ID, and the refused destroy. Together they answer who tried, what they touched, whether it worked, and who else can still see it.
The denial is the deliverable. A refused read that leaves a trace proves the logging path works, and a success with the same shape proves the trace records more than failures. Both are cheap to produce and impossible to fabricate afterwards.
Redaction is part of the method. Projecting fields at query time keeps payloads out of terminals, tickets, and screenshots. An evidence pack that contains a credential has created a second incident while investigating the first.
Next in the Series
In Google Edge Delivery: Cloud DNS, Load Balancing, Certificates and Cloud Armor, we'll explore Choose a coherent edge chain and verify DNS, TLS, cache and security behavior across service scopes.