Choose the IAM Resource That Matches the Ownership Scope
Three resources, three different promises. Google Cloud stores access as an allow policy: a document of role bindings, each naming a role and its members. Terraform exposes three ways to write that document, and each one claims a different amount of ownership. The choice is not stylistic, because it decides what a later apply is allowed to delete.
The authoritative resource owns the whole document. google_project_iam_policy writes the complete policy. Any binding added outside that root, by another team, the console, or a one-off script, disappears on the next apply. The provider documentation warns that deleting the resource removes all policies from the project and can lock out anyone without organization-level access (project IAM resources).
The binding owns one role and every member in it. google_project_iam_binding replaces the member list for a single role while leaving other roles alone. It is authoritative at role scope, not project scope. That makes it the right tool only when one team genuinely owns every principal that should hold that role.
The member resource owns one pairing. google_project_iam_member adds a single principal to a single role and leaves every other member untouched. It is additive, idempotent, and the safest default for a shared project. Destroying it removes only that pairing.
Mixing scopes produces a fight, not a merge. A policy resource cannot coexist with a binding, member, or audit config on the same project, because each writes a different version of the same document. A binding may coexist with member resources only when they target different roles. Two bindings for one role, or a member and a removal guard for the same pairing, produce perpetual diffs.
Figure 1 turns the choice into a gate rather than a preference.
%%{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
Q1{"Does one root own
the entire project policy?"}
Q1 -->|"yes, and it was imported"| P["google_project_iam_policy
whole document"]
Q1 -->|"no"| Q2{"Does one team own
every member of this role?"}
Q2 -->|"yes"| B["google_project_iam_binding
one role, full member list"]
Q2 -->|"no"| M["google_project_iam_member
one principal, one role"]
P --> F1["next apply removes grants
other teams still need"]
B --> F2["another writer's member
disappears from the role"]
M --> OK["additive and reversible
the shared-project default"]
F1 --> R["one writer per scope
never mix policy with member"]
F2 --> R
OK --> R
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 Q1,Q2,R primary;
class P,B secondary;
class M,OK ok;
class F1,F2 danger;
Read the left branch as a last resort. A whole-policy root belongs to a project that Terraform fully manages, where the policy was imported before the first apply and an organization-level break-glass administrator is documented. For everything else, the right-hand path is smaller, reviewable, and reversible.
Each resource draws a different boundary. Figure 2 makes the difference visible: the policy boundary encloses every binding, the binding boundary encloses one role's member list, and the member boundary encloses a single pairing. Only the last two can share a project safely, and only when their roles differ.
The table is the review checklist; the last column is where most incidents start.
| Resource | Owns | Apply consequence | Destroy consequence | Safe alongside |
|---|---|---|---|---|
google_project_iam_policy | the entire allow policy | removes bindings the document omits | removes all project access not inherited from above | nothing on the same project |
google_project_iam_binding | every member of one role | replaces that role's member list | removes the role binding entirely | member resources for other roles |
google_project_iam_member | one member in one role | adds or updates one pairing | removes one pairing | other members and bindings for other roles |
google_project_iam_member_remove | the absence of one pairing | removes the pairing if present | stops enforcing absence, restores nothing | only pairings nothing else manages |
Give each scope exactly one owner. A workload module should accept a project and add members. A platform module may own a role binding for a role it exclusively controls. A whole-policy root should be rare enough to require a named approver and a documented recovery identity.
Separate Service Account Identity from Its Permissions
A service account is two objects wearing one name. It is an identity that can be granted roles on other resources, and it is a resource with its own allow policy that decides who may use or manage it (service account permissions). Creating one with google_service_account grants no permission in either direction.
Acting as an account is a grant on the account, not on the workload. To attach a service account to a Cloud Run service, a Compute instance, or a GKE workload, the caller needs iam.serviceAccounts.actAs, normally through roles/iam.serviceAccountUser on that service account. Granting that role at project level covers every service account in the project, which is far wider than most teams intend.
Impersonation is a different permission with a sharper edge. roles/iam.serviceAccountTokenCreator allows minting OAuth tokens, ID tokens, and signed assertions, and it enables the gcloud impersonation flag. It does not attach the account to anything; it lets the holder become the account for API calls. Grant it on the service account resource, with a condition or a short expiry where the workflow allows.
Target permissions live somewhere else entirely. What the service account may do is decided by allow policies on the resources it calls: the project, a bucket, a topic, a secret. The member string is serviceAccount: followed by the account email. A role on the service account does not widen the account, and a target grant does not let a human use it.
Figure 3 follows both paths and keeps the failure attached to the layer that produces 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
H["CI job or engineer
needs the service account"] --> A{"Attach the account
or impersonate it?"}
A -->|"attach to Cloud Run,
GCE or GKE"| U{"serviceAccountUser
on the account resource?"}
U -->|"no"| E1["403 iam.serviceAccounts.actAs
resource create fails"]
U -->|"yes"| R["Resource runs as the account"]
A -->|"mint a token or use
gcloud impersonation"| C{"serviceAccountTokenCreator
on the account resource?"}
C -->|"no"| E2["403 iam.serviceAccounts.getAccessToken
no credential issued"]
C -->|"yes"| T["Short-lived token
no key file in state"]
R --> G["Call the target API"]
T --> G
G --> P{"Allow policy on the target
resource names the account?"}
P -->|"no"| E3["403 from the target API
the identity was valid"]
P -->|"yes"| OK["Allowed and logged
as the service account"]
S["google_service_account
identity only"] -.-> R
S -.-> T
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,A,U,C,P,S primary;
class R,T secondary;
class OK ok;
class E1,E2,E3 danger;
The three failures name three different APIs. A missing actAs permission fails the resource create or update. A missing token-creator permission fails the credential call. A missing target grant fails the actual API request after a valid token was issued. Reading the error is faster than widening all three.
Keys are a third path and a worse one. google_service_account_key creates long-lived private key material and writes it to state, so anyone with the state or the key file holds the account's access until rotation. Prefer impersonation or workload identity federation, and treat key creation as an exception with a named owner and an expiry.
A custom role is a permission list, not a scope. google_project_iam_custom_role defines which permissions exist under a project-level name; it grants nothing until a binding references it. Keep custom roles small and version them with the code that uses them, because deleting one breaks every binding that names it. Deleted custom roles are soft-deleted for seven days, and the name can stay unavailable for up to 37 days (custom role resource).
Handle Conditions and Organization Inheritance Explicitly
Inheritance is additive, and that is the whole problem. A role granted on the organization or a folder applies to every descendant resource. A project-level allow policy cannot take it away. The only ways to narrow it are to remove the high-level grant or to attach a deny policy below it; adding a more specific allow changes nothing.
Conditions narrow a binding only when no unconditional grant exists. A conditional role binding applies only if its CEL expression evaluates true, and conditional bindings do not override an unconditional binding for the same principal and role (conditions overview). Before adding a condition, search for the same pairing without one. If it exists, the condition is decoration.
Some grants cannot carry conditions at all. Legacy basic roles, including Owner, Editor, and Viewer, reject conditions, as do bindings to all users or all authenticated users. The API returns a 400 rather than silently ignoring the condition. Conditions also work only on resource types that support them; for the rest, grant at the project or folder above.
A condition change is a replacement, not an edit. Terraform treats the role plus the condition title, description, and expression as the binding's identity. Changing any part destroys the old binding and creates a new one, with a propagation gap in between. If the grant is load-bearing, stage the new condition alongside the old one, then remove the old binding after the new one is effective.
Deny policies are the guardrail, and they run first. A deny policy attaches to an organization, folder, or project, is inherited downward, and is evaluated before any allow policy (deny overview). Deny conditions recognize only resource tag functions, and only some permissions can be denied, so check the supported list before promising a guardrail. Several deny policies are evaluated independently, and one matching deny is enough.
Propagation is part of the contract. Policy changes typically take about two minutes and can take seven minutes or longer. Group membership changes can take hours, and nested groups are slower still (access change propagation). A verification run immediately after apply can prove the old state rather than the new one.
Evidence should name the policy, not the plan. Policy Troubleshooter takes a principal, a resource, and a permission and reports whether allow, deny, and boundary policies permit it, including which binding decided. The gcloud form, gcloud policy-intelligence troubleshoot-policy iam, is repeatable, and the console also accepts an error ID when that is all the user has. A green apply is not evidence of effective access.
A custom role that is too broad is still broad. Custom roles are useful when no predefined role fits, but the permission list is the whole contract. Review it against actual API calls, keep the stage deliberate, and treat deletion as a policy cleanup: removing the role does not remove the bindings that name it.
Give Required APIs a Long-Lived Activation Owner
An API is enabled for a project, not for a module. Every workload in the project shares the activation, its quotas, and its service agents. When a workload root owns the activation, a routine destroy in that root can remove a dependency another team never agreed to lose. That is an ownership bug disguised as cleanup.
The provider default is kinder than folklore suggests. In hashicorp/google 8.10.0, disable_on_destroy unset or false leaves the service enabled when the resource is destroyed; the documentation recommends true only for configurations that also manage the project itself (project service). Many older modules set it to true explicitly, so audit the module source rather than assuming the default.
Disabling is not a neutral rollback. Disabling the Cloud Run API deletes the Cloud Run resources in the project, and disabling the Kubernetes Engine API suspends clusters, which are deleted after 30 days (enable and disable services). Disabling a service that other enabled services depend on also fails unless dependent services are disabled too, so the blast radius is not limited to the API you named.
Give the list one long-lived owner. A platform root owns a curated set of activations for the shared project, with state in a long-lived bucket and a review that names the service owner. Workload roots consume the project and never declare the shared APIs. Keep the list small and justified, because every enabled API adds quota, service agents, and billing surface.
Destroy semantics need a second lock. deletion_policy = "PREVENT" makes Terraform refuse to remove the activation record, and ABANDON removes it from state without calling the API. Both are stronger than relying on a default that a future module edit can change. For a service that automation must never disable, use PREVENT and document the manual path.
The dependency lag has three layers. The enable call returns a long-running operation, and the provider waits for it. IAM propagation then takes its own minutes, and a service agent may need an explicit grant before the API can act. depends_on orders the calls but does not shorten either wait. A short explicit delay is sometimes the honest fix, and a retry is better than a sleep when the provider supports one.
Service agents are resources too. Some APIs expose an agent identity through google_project_service_identity, which is beta-only and create-only: update and destroy are no-ops (service identity). Grant roles to that agent after the API exists, and do not assume deleting the Terraform resource removes the agent.
The usage guard exists, but check its stage. check_if_service_has_usage_on_destroy rejects a disable when the service has been used in the last 30 days, but it is marked Beta and needs the beta provider. If you cannot use it, record the usage check as a manual step in the destroy runbook rather than skipping it.
Figure 4 contrasts the two ownership arrangements.
The right panel is not more expensive; it is differently owned. The platform root pays the review cost once, and every workload root gets a stable dependency. The left panel looks cheaper until the first destroy, when a shared API leaves with a workload that was only supposed to remove its own resources.
Adopt a Narrow Grant Without Replacing Everyone Else
The lab proves two things a plan cannot. A no-change baseline shows that the configuration already matches the policy, and a pair of API calls shows that the new grant allows one action and denies its neighbour. Run it in a disposable project with Terraform 1.17.1 and hashicorp/google 8.10.0; the versions are part of the evidence because provider defaults move.
Adopt a Narrow Grant Without Replacing Everyone Else
Execution status: design-only. These steps were not run against a live project. The sequence is written to be executed and recorded, not quoted as a transcript.
Prerequisites. A disposable project where you can grant IAM, one Cloud Storage bucket with one small object, one service account, and permission to enable the Storage API. Terraform 1.17.1 with hashicorp/google 8.10.0. Keep an organization-level administrator available outside the lab root; that is the recovery path if a policy experiment goes wrong.
- Record the baseline. Export the project allow policy and store it outside the root, then run a plan. Expect no changes for the resources already in state. If the plan is not empty, stop: the baseline is not a baseline.
- Import an existing pairing. Choose a project-level pairing that already exists, or create one with gcloud outside the root. Add an import block with the ID in the form
PROJECT_ID ROLE MEMBER. Plan again and expect no changes. This is the step that stops an authoritative resource from adopting by deletion. - Add one narrow member. Declare
google_storage_bucket_iam_memberfor the service account androles/storage.objectVieweron the bucket. This is the same member shape at bucket scope, and it grants nothing on the rest of the project. Apply; the plan should add one resource and replace no policy. - Prove the grant. As the service account, read the object, which requires
storage.objects.get. Expect success, and expect the audit log entry to name the service account as the principal. - Prove the denial. Attempt to delete the object, which requires
storage.objects.delete. Expect a 403 that names the missing permission rather than an authentication error. - Ask the troubleshooter. Run it for the allowed and denied permission. Expect an allow decision naming the bucket binding, and a not-granted decision that lists the roles considered.
- Add the condition last. Enable uniform bucket-level access, then add a condition that limits the grant to the object prefix. Apply and repeat steps 4 and 5. Expect the member resource to be replaced, a short propagation wait, and the same pair of outcomes for the in-prefix and out-of-prefix object.
- Destroy without collateral. Remove the member resource, destroy the lab root, and confirm the shared project and its API activation are still present. If the API was owned by the lab root, that is the failure this article is about.
| Check | Evidence | Pass looks like |
|---|---|---|
| Baseline | saved policy plus empty plan | no diff before your change |
| Import | plan after the import block | no changes, no replacement |
| Allowed | read as the service account | the object returns |
| Denied | delete as the service account | 403 naming storage.objects.delete |
| Effective | Policy Troubleshooter output | allow names the binding, denial names the gap |
| Cleanup | plan after removal | only lab resources disappear |
Expected observation. The import produces an empty plan, the member add produces a one-resource diff, and the two API calls split cleanly into allowed read and denied delete. The condition change replaces the member resource rather than editing it in place.
Failure checks. If the plan wants to replace the whole policy, a policy resource is already present. If the denied call returns 401, the token is wrong rather than the permission. If the allowed call succeeds before the grant, the service account may be inheriting a broader project role.
Cost dimensions. The lab is close to free: one bucket, one small object, a handful of IAM calls, and a few storage requests. Leaving a versioned bucket or a large object behind is the only realistic cost.
Cleanup. Delete the object and bucket, remove the member and the service account, then run a final plan. Confirm the project policy still contains the bindings recorded in step 1, and that the shared API owner did not change.
The baseline is the deliverable. It separates your change from everyone else's, and it is the only way to prove that a narrow grant stayed narrow. Keep the policy export, the two decisions, and the destroy record together as the ownership evidence.
Next in the Series
In Google Networking: VPCs, Shared VPC, Firewall and Private Service Paths, we'll explore Model project-aware connectivity and private access without translating AWS concepts mechanically.