Hour 2: Identity and access management (IAM)
Hour 2: Identity and access management (IAM)
Identity and access management decides who can do what, on which resource, in a Google Cloud organization. In a landing zone it is the control that every other layer leans on: the network team, the logging team and every application team receive access through it, and an attacker who obtains a credential is limited by it. Most serious cloud incidents involve an identity that could do more than its job required, so this hour is about making access precise, inherited by design, and explainable.
You start with the model: principals, permissions, roles and allow policies, and the way a policy is read and written safely. Then you compare basic, predefined and custom roles and use IAM Recommender to shrink them. You learn how access flows down the resource hierarchy, how IAM Conditions make a grant temporary or resource-specific, and how a deny policy overrides a grant. Workloads get their own treatment: service accounts, impersonation, the default accounts to contain, and keyless authentication with Workload Identity Federation for pipelines outside Google Cloud.
The second half moves to people and operations: group-based access, privileged access with approval and time limits, access reviews, and the admin audit trail. A ten-minute lab builds a least-privilege platform team from a group binding, a custom role and a service account, then proves the result with an impersonation test and the Policy Troubleshooter. The last module teaches a repeatable triage order for the most common error in Google Cloud, "permission denied".
Every module uses the same ten tabs: concepts, diagrams, an animation of the mechanism, commands with expected output and errors, a lab, production practice, troubleshooting, and video and documentation links.
What you will be able to do after this hour
- Explain an IAM decision as principal, permission, role and resource, and read an allow policy including its etag, conditions and version.
- Read and change a project allow policy with
gcloudwithout overwriting another administrator's change. - Choose between basic, predefined and custom roles, create a custom role from a YAML file, and use IAM Recommender output to remove unused access.
- Predict effective access from the organization, folders, project and resource policies, and prove it with Policy Troubleshooter and Policy Analyzer.
- Write an IAM Condition for an expiry date, a resource-name prefix or a tag, and describe what a deny policy can and cannot do.
- Create service accounts, attach them to workloads, impersonate them without keys, and contain the default service accounts.
- Configure Workload Identity Federation for GitHub Actions with an attribute condition that limits the repository.
- Design group-based access, privileged access with approval, and a quarterly access review, and diagnose a "permission denied" error in a fixed order.
Schedule (60 minutes)
The minutes are the reading and listening time of each module. Running every lab step takes longer; the lab tabs say how long.
What the labs create
| Module | Resources created | Cost class |
|---|---|---|
| 1 | One binding on a sandbox project for a test group, removed at the end | Free |
| 2 | One project custom role (logReader) and a binding | Free |
| 3 | A conditional binding with an expiry, an optional folder binding, and one deny policy | Free |
| 4 | One service account without keys, and an impersonation binding | Free |
| 5 and 6 | A workload identity pool and provider (configuration only), and read-only reviews of existing access | Free |
| 7 | A group binding, a custom role, a service account and an impersonation test, all in the sandbox project, then cleanup | Free |
| 8 | Read-only diagnostics | Free |
The hour does not create virtual machines, storage buckets with data or any other metered resource, unless an optional step says so and names the cleanup.
What you need
- A sandbox Google Cloud project where you hold
roles/owner(or Project IAM Admin plus Service Account Admin), preferably inside a sandbox organization and folder. - A Google group, or a second test user, to stand in for "the team". The setup page shows how to create one, and what to do without an organization.
- The Google Cloud CLI (
gcloud) or Cloud Shell, and basic command-line skills. - Optionally, a GitHub repository for the Workload Identity Federation lab in Module 5. Without it, you still configure the pool and provider and read the attribute mapping.
See the Setup tab for the environment checks.
PROJECT_ID, GROUP_EMAIL and ORG_ID and replace them with your own values. IDs in the expected output are illustrative, and you must never create service account keys or paste credentials into commands.Setup
Environment for Hour 2
This hour needs a sandbox project where you may edit the allow policy, a group or a second test user to receive access, a shell with gcloud, and a handful of APIs enabled. The steps are ordered so that you can stop where your environment ends. Nothing here is billable.
1. Choose your environment
| Option | What works | What does not |
|---|---|---|
| Sandbox organization with a lab folder (recommended) | Everything: folder and project bindings, groups, deny policies, Policy Analyzer at organization scope, access reviews | Nothing is missing. You need admin help to create groups unless you are the administrator. |
| Company organization with a delegated sandbox project | Project-level bindings, custom roles in the project, service accounts, Workload Identity Federation (if allowed), troubleshooter | Organization-level custom roles, organization and folder bindings, organization-wide Policy Analyzer; often groups |
| No organization (personal Google account, project at root) | Project bindings, project custom roles, service accounts, impersonation, conditions, project-level deny policies, troubleshooter, Workload Identity Federation | Folders, organization policies and organization-level roles or policies; Google groups through your own domain |
PROJECT_ID. Replace the group with a second Google account that you own (user:SECOND_ACCOUNT_EMAIL) wherever a lab says group:GROUP_EMAIL, and skip the steps that mention a folder or the organization, which the labs mark. Read those steps as exercises: the commands work the same way when you later have an organization. A free Cloud Identity account with a domain you own gives you an organization for the next hours.2. Open a shell with gcloud
Cloud Shell is the fastest option: open https://console.cloud.google.com, sign in and start Cloud Shell. It has a current gcloud CLI, git and jq. Cloud Shell itself is free; resources you create from it are billed to their project.
Local install. Install the Google Cloud CLI (current release channel) from cloud.google.com/sdk/docs/install and sign in:
gcloud init gcloud auth login
Use a separate gcloud configuration for the labs so that an impersonation setting or a default project from the lab cannot leak into other work:
gcloud config configurations create iam-lab gcloud config set account YOUR_EMAIL gcloud config set project PROJECT_ID gcloud config configurations list
3. A project with IAM permissions
You need a project where you can read and change the allow policy, create roles and create service accounts. Owner on a sandbox project is enough. In a shared environment, ask for these on the sandbox project only:
| For | Role | Scope |
|---|---|---|
| Reading and changing the project policy | roles/resourcemanager.projectIamAdmin | Sandbox project |
| Creating custom roles | roles/iam.roleAdmin | Sandbox project |
| Creating service accounts | roles/iam.serviceAccountAdmin | Sandbox project |
| Managing the policy on a service account | roles/iam.serviceAccountAdmin, or Owner | Sandbox project |
| Deny policies (Module 3, optional) | roles/iam.denyAdmin | Sandbox project |
| Workload Identity pools (Module 5) | roles/iam.workloadIdentityPoolAdmin | Sandbox project |
| Reading audit logs | roles/logging.viewer (Admin Activity logs) | Sandbox project |
| Policy Analyzer on the organization | roles/cloudasset.viewer and roles/iam.securityReviewer | Organization or lab folder, if available |
Do not ask for organization-level roles for a course. Never grant Owner to a group that includes other people.
4. A group or a test user
The labs grant roles to GROUP_EMAIL, to stand for a platform team. Pick one of these:
- A Google group in your domain. Create it in the Admin console (Directory, Groups) or through your identity administrator, add yourself and one test user as members, and use
group:GROUP_EMAIL. Group changes may take a few minutes to be visible to IAM. - A second user. Use another account you own with
user:SECOND_ACCOUNT_EMAIL. Everything works the same, except that you cannot test "membership changes access" (Module 6).
Do not use a real production group, and do not add colleagues who did not agree to be part of the lab.
5. Enable the APIs
The IAM commands need a few APIs on the project. All are free to enable.
gcloud services enable \ iam.googleapis.com \ iamcredentials.googleapis.com \ cloudresourcemanager.googleapis.com \ policytroubleshooter.googleapis.com \ cloudasset.googleapis.com \ recommender.googleapis.com \ sts.googleapis.com \ --project=PROJECT_ID
Check gcloud services list --available --filter="name:policytroubleshooter" if an API name is not recognised in your environment. Enabling an API does not create billable resources, but some APIs have usage-based charges when you use them heavily; these labs make a few calls.
6. Check commands
Run these and compare with the expected result.
gcloud --version gcloud auth list gcloud config list gcloud projects describe PROJECT_ID --format="value(projectId,parent.id)" gcloud projects get-iam-policy PROJECT_ID --format="value(etag)" gcloud iam roles describe roles/viewer --format="value(name,stage)"
Google Cloud SDK 5xx.x.x
core 20xx.xx.xx
Credentialed Accounts
ACTIVE ACCOUNT
* you@example.com
[core]
account = you@example.com
project = PROJECT_ID
PROJECT_ID 123456789012
BwYabc123=
roles/viewer GA
Version numbers in the output are placeholders. Any current gcloud release works; if yours is old, run gcloud components update (local install) or open a new Cloud Shell session. A project with no parent prints only the project ID.
- PERMISSION_DENIED on
get-iam-policy. You lackresourcemanager.projects.getIamPolicy. Checkgcloud auth listand ask for Project IAM Admin on the sandbox. - API not enabled. The error names the API and a link; run the enable command in step 5, wait a minute and retry.
- No active account. Run
gcloud auth login(local) or sign in again to Cloud Shell. - Wrong project. Use the
--projectflag in commands so that a default from another environment cannot be used by accident.
7. Variables
Keep your values in one shell file and replace placeholders in the commands. Do not store them in scripts that you copy around.
export PROJECT_ID=my-iam-lab-1234 export GROUP_EMAIL=iam-lab-team@example.com export YOUR_EMAIL=you@example.com echo "$PROJECT_ID $GROUP_EMAIL $YOUR_EMAIL"
8. Cleanup habit
- Every lab ends with a cleanup block that removes its bindings, roles, service accounts and policies. Run it, then confirm with
gcloud projects get-iam-policy PROJECT_ID --format="yaml(bindings)"that no lab binding remains. - Remove impersonation defaults when you finish:
gcloud config unset auth/impersonate_service_account. - Prefix everything you create with
lab-and delete only resources with that prefix. - Deleted custom roles and service accounts can be restored for a limited time, but bindings that named them show as
deleted:until you clean the policy.
Module 1 · The IAM model
- Explain an IAM decision as "who (principal) can do what (permission, grouped in a role) on which resource", and name the parts of an allow policy.
- Read and change a project allow policy with gcloud, and use the etag to avoid overwriting someone else's change.
- Distinguish a principal type (user, group, service account, domain, principal set) and choose groups for people.
The short answer
Identity and Access Management (身份与访问管理, IAM) decides, for each API request, whether a principal (主体) may perform an action on a resource. The rule that grants access is stored as an allow policy (允许策略) on the resource. The allow policy is a list of bindings; each binding gives one role (角色) to one or more principals.
The four parts of every decision
| Part | Question | Example |
|---|---|---|
| Principal | Who is calling? | group:platform-engineers@example.com |
| Permission | What action is requested? | compute.instances.start |
| Role | Which bundle of permissions was granted? | roles/compute.instanceAdmin.v1 |
| Resource | On what, and which policies apply to it? | projects/PROJECT_ID/zones/ZONE/instances/vm-1 |
What: anatomy of an allow policy
{
"version": 1,
"etag": "BwYabc123=",
"bindings": [
{
"role": "roles/viewer",
"members": [
"group:platform-engineers@example.com",
"serviceAccount:ci-reader@PROJECT_ID.iam.gserviceaccount.com"
]
},
{
"role": "roles/storage.objectViewer",
"members": ["user:ana@example.com"],
"condition": {
"title": "expires-end-of-quarter",
"expression": "request.time < timestamp('2027-01-01T00:00:00Z')"
}
}
]
}
- bindings: each has a
role, amemberslist and an optionalcondition. The same role can appear in several bindings only if the conditions differ. - etag: the version token for optimistic concurrency, described above.
- version: 1 is the default; policies that contain conditional bindings need version 3. The gcloud commands for
add-iam-policy-bindingset this for you, but a hand-edited file passed toset-iam-policymust carry the right version (Module 3). - auditConfigs: an optional section that turns on Data Access audit logs for a service (Hour 6).
Principal types
| Prefix | Identity | Use it for |
|---|---|---|
user: | One Google Account or Cloud Identity user | Rare. Prefer groups. Acceptable for a one-off personal sandbox. |
group: | A Google group | People. This is the default choice for all human access. |
serviceAccount: | A workload identity (Module 4) | Applications, pipelines and VMs. |
domain: | Every identity in a Workspace or Cloud Identity domain | Broad read-only access to a shared dataset; use with care. |
principal:// and principalSet:// | Federated identities from Workload Identity Federation, or a workforce pool | CI/CD and external identity providers (Module 5). |
allUsers | Anyone on the internet, no sign-in | Public websites only. Normally blocked by an Organization Policy (Hour 3). |
allAuthenticatedUsers | Any signed-in Google account, including personal Gmail | Almost never. It is not "everyone in my company". |
Why: the reasons behind the model
- Roles, not permissions. Thousands of permissions would be impossible to review. Roles give names that humans can discuss in a change request.
- Policies on resources. Access lives next to the thing it protects, so deleting the resource deletes the access, and the effective access is computed from the hierarchy (Module 3).
- Additive grants. An allow policy can only add access. Anything that removes access (a deny policy, an Organization Policy, a Principal Access Boundary) is a separate control, which keeps each policy easy to reason about.
- Default deny. A request with no matching binding is denied. You never write a rule to say "no" to someone who has nothing.
How it works internally
- A request arrives with a credential: an OAuth access token, a signed JWT, or a federated token. Google Cloud authenticates it and obtains the principal.
- The target service maps the API method to one or more permissions (for example
storage.objects.get). - IAM collects the allow policies on the resource and on every ancestor (project, folders, organization), expands each binding's role into its permissions and checks conditions.
- IAM evaluates deny policies and other overriding controls. If no deny matches and at least one allow binding grants the permission, the request is allowed.
- The call, the decision and the identity are written to Cloud Audit Logs when the corresponding log type is enabled (Admin Activity is always on).
When to use which level for a binding
| If the team needs... | Bind at | Reason |
|---|---|---|
| Read access to one bucket | The bucket | Smallest blast radius; the grant disappears with the bucket. |
| Admin over one application | The application's project | Projects are the natural unit of ownership. |
| Read access to every production project | The production folder | One binding, inherited by new projects automatically. |
| Organization-wide auditing | The organization, for a small security group | Visibility without write rights. |
What IAM is confused with
| Often confused with | The difference |
|---|---|
| Authentication | Authentication proves who you are (sign-in, token, 2-step verification). IAM is authorization: what that identity may do. |
| Organization Policy | IAM controls who can act. Organization Policy controls what configurations are allowed, for everyone, whatever their role (Hour 3). |
| Network firewall rules | Firewalls decide whether packets flow. IAM decides whether API calls are accepted. A VM can be reachable and still have no right to call an API. |
| Google Workspace admin roles | Admin console roles manage users and groups. They are not Google Cloud roles, although a Workspace super admin can grant themselves organization access (Hour 1, Module 4). |
| AWS IAM and Azure RBAC | AWS attaches policies to identities and resources in JSON statements; Azure RBAC assigns roles at a scope. Google Cloud is closest to Azure RBAC, with roles bound on resources and inherited, but the policy is stored on the resource. |
Figure 1. One binding links a principal to a role on a resource. The role is expanded into permissions at request time.
Figure 2. The read-modify-write cycle and the etag. Prefer the single-binding commands in automation; they retry automatically.
Look first at Figure 1: the policy lives on the resource, and the role is only a name for permissions. Then look at Figure 2: every change you make is a replacement of a small document guarded by a version token. That is why two administrators editing the same policy by hand can lock each other out, and why automation should use the narrow commands.
The animation follows one grant from the CLI to the moment the new binding is used. First the policy is read with its etag, then written back with the new binding, and finally a user request is evaluated and the change is recorded in Cloud Audit Logs.
Reading is free and safe. Writing an allow policy costs nothing, but it changes who can act, so use a sandbox project. Replace PROJECT_ID and GROUP_EMAIL with your own values.
gcloud projects get-iam-policy
Purpose. Prints the allow policy attached directly to the project (free, read-only). It does not show inherited bindings from folders or the organization.
gcloud projects get-iam-policy PROJECT_ID
Flags. --format=json or yaml for scripting; --flatten and --filter to search (below); --billing-project to choose the project that is billed for the API call.
bindings: - members: - group:platform-engineers@example.com role: roles/viewer - members: - user:ana@example.com role: roles/owner etag: BwYabc123= version: 1
Common errors. PERMISSION_DENIED: The caller does not have permission means you lack resourcemanager.projects.getIamPolicy. Cloud Resource Manager API has not been used in project ... before means the API is not enabled on the project used for quota (see --billing-project).
Production use. Export the policy on a schedule and compare it with the Terraform plan to catch drift (Hour 7).
gcloud projects add-iam-policy-binding (write, free)
Purpose. Adds one principal to one role in one call, using the read-modify-write loop with retries. It does not remove anything.
gcloud projects add-iam-policy-binding PROJECT_ID \ --member="group:GROUP_EMAIL" \ --role="roles/logging.viewer"
Flags. --member takes type:identifier; --role takes the full role name; --condition adds an IAM Condition (Module 3); --condition=None is required to add an unconditional binding when the same role already has conditional bindings.
Updated IAM policy for project [PROJECT_ID]. bindings: - members: - group:GROUP_EMAIL role: roles/logging.viewer - members: - group:platform-engineers@example.com role: roles/viewer etag: BwYabd456= version: 1
Common errors. INVALID_ARGUMENT: User ... does not exist for a misspelled email; Policy members ... must have a valid domain when an Organization Policy restricts allowed domains (Hour 3, iam.allowedPolicyMemberDomains).
Production use. Applications and humans do not run this by hand: Terraform resources such as google_project_iam_member (additive) or google_project_iam_binding (authoritative for a role) manage the same bindings from code.
gcloud projects remove-iam-policy-binding (write, free)
Purpose. Removes one principal from one role, again with automatic retry.
gcloud projects remove-iam-policy-binding PROJECT_ID \ --member="group:GROUP_EMAIL" \ --role="roles/logging.viewer"
Gotcha. If the same principal is granted the role at the folder or the organization, removing it on the project does not remove access. Check inherited access with Module 3.
Find every role of one principal
Purpose. The allow policy is a list of roles with members. To turn it around into "what does this group have in this project", flatten the bindings and filter on the member (free, read-only).
gcloud projects get-iam-policy PROJECT_ID \ --flatten="bindings[].members" \ --filter="bindings.members:group:GROUP_EMAIL" \ --format="table(bindings.role)"
ROLE roles/logging.viewer roles/viewer
gcloud asset search-all-iam-policies
Purpose. Searches IAM policies across a scope, including bindings on folders and the organization, using Cloud Asset Inventory (free to call; the Cloud Asset API must be enabled). Use it to answer "where does this principal have any access".
gcloud asset search-all-iam-policies \ --scope=projects/PROJECT_ID \ --query="policy:GROUP_EMAIL" \ --format="table(resource,policy.bindings.role)"
Check gcloud asset search-all-iam-policies --help for the flags in your SDK version; results can be a few minutes behind the live policy.
gcloud policy-troubleshoot iam
Purpose. Asks IAM to explain whether a principal has a permission on a resource, and which policies were considered (free). Module 8 uses it as the main diagnostic.
gcloud policy-troubleshoot iam \ //cloudresourcemanager.googleapis.com/projects/PROJECT_ID \ --principal-email=ana@example.com \ --permission=resourcemanager.projects.get
access: GRANTED explainedPolicies: - access: GRANTED fullResourceName: //cloudresourcemanager.googleapis.com/projects/PROJECT_ID ...
The output is long and the exact fields depend on the version. Check gcloud policy-troubleshoot iam --help in your SDK version. The Policy Troubleshooter API must be enabled.
set-iam-policy with a file as a break-glass tool. If you must use it, run get-iam-policy --format=json > policy.json, edit that exact file, and push it back immediately so the etag is fresh.Lab 1: read, grant, verify and revoke a role (about 15 minutes, free)
Goal. Practice the full life cycle of one binding on a sandbox project and see the etag change.
Prerequisites. A sandbox project (not production) where you have roles/owner or roles/resourcemanager.projectIamAdmin; a Google group or a second test user that you can name in GROUP_EMAIL (see the setup page); gcloud authenticated. IDs in the expected output are illustrative.
- Set the project:
gcloud config set project PROJECT_IDand check withgcloud config list project. - Save the current policy as a baseline:
gcloud projects get-iam-policy PROJECT_ID --format=json > before.json. Note theetag. - Grant a read-only role to the test group:
gcloud projects add-iam-policy-binding PROJECT_ID --member="group:GROUP_EMAIL" --role="roles/viewer". - Read the policy again and compare the etag with the baseline:
gcloud projects get-iam-policy PROJECT_ID --format="value(etag)". It must differ from the one inbefore.json. - List the roles of the group with the flatten and filter command from the previous tab. You must see
roles/viewer. - Run the troubleshooter for a member of the group:
gcloud policy-troubleshoot iam //cloudresourcemanager.googleapis.com/projects/PROJECT_ID --principal-email=MEMBER_EMAIL --permission=resourcemanager.projects.get. The result must sayaccess: GRANTED(allow up to a few minutes for propagation). - Revoke:
gcloud projects remove-iam-policy-binding PROJECT_ID --member="group:GROUP_EMAIL" --role="roles/viewer", then repeat step 5. The role must be gone. - Look at who did it in the audit log (Admin Activity is always on):
gcloud logging read 'protoPayload.methodName="SetIamPolicy" AND resource.type="project"' --project=PROJECT_ID --limit=3 --format="table(timestamp,protoPayload.authenticationInfo.principalEmail)".
Expected result.
ROLE roles/viewer TIMESTAMP PRINCIPAL_EMAIL 2026-11-25T09:42:11.531Z you@example.com 2026-11-25T09:38:02.118Z you@example.com
Cost. Free. No billable resources are created.
Cleanup. The revoke in step 7 is the cleanup. Delete before.json if it contains real principal names you do not want to keep.
Lab 2 (optional): a stale etag
Run get-iam-policy --format=json > a.json, then add a binding with add-iam-policy-binding, then try gcloud projects set-iam-policy PROJECT_ID a.json. The write fails with an etag mismatch because a.json is outdated. Read it again and the problem is gone. Remember this when two pipelines manage the same project.
Real cases
- Personal accounts everywhere. A team granted
roles/editorto fifteen individual accounts. When two people left, nobody knew which projects they could still reach. The fix was to move every human binding to groups, owned by the identity team, and to runasset search-all-iam-policiesfor any remaininguser:member. - Hand-edited policy file. An administrator downloaded a policy, spent an hour reviewing it, and uploaded it with
set-iam-policy. In the meantime a pipeline had added a service account, so the upload was refused because of the etag; the administrator then removed the etag from the file and uploaded again, which deleted the pipeline's access. The lesson: never strip the etag, and prefer single-binding commands or Terraform. - Public bucket by
allUsers. A developer boundallUsersto an object viewer role to share a file quickly. The binding stayed for months. An Organization Policy for allowed policy members and a scheduled search forallUsersandallAuthenticatedUsersnow catches this class of mistake.
Practices
- Humans receive access through groups; workloads through service accounts or federated principals. Direct
user:bindings are exceptions that need an owner and an expiry. - Manage allow policies as code. Use additive resources (
iam_member) for shared projects, and authoritative resources only where one pipeline owns the whole role. - Bind at the lowest level that makes sense, and at a folder when many projects share the same need.
- Review who holds
roles/owner,roles/resourcemanager.organizationAdminandroles/iam.securityAdminevery quarter (Module 6 covers reviews).
Security notes
setIamPolicy) is the permission to give yourself everything below that resource. Roles that contain it (Owner, roles/resourcemanager.projectIamAdmin, roles/iam.securityAdmin) must be limited to a small, audited group.SetIamPolicy are in Admin Activity logs, which are always on and cannot be disabled. Create a log-based alert for them on production folders.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
PERMISSION_DENIED on get-iam-policy | Missing resourcemanager.projects.getIamPolicy | gcloud auth list; confirm you are on the right account |
add-iam-policy-binding says the member is invalid | Wrong prefix or a misspelled email | Check user:, group:, serviceAccount: and the exact address |
| Binding added but the user still gets denied | Propagation, a deny policy, or the role lacks the permission | gcloud policy-troubleshoot iam ... |
Etag or ABORTED error on set-iam-policy | Another change happened after you read the policy | Read the policy again and re-apply your edit |
| Binding removed but access remains | Access is inherited from a folder, the organization, or another group | Run asset search-all-iam-policies with the principal as the query |
| Member rejected by an Organization Policy message | iam.allowedPolicyMemberDomains blocks outside identities | gcloud org-policies describe iam.allowedPolicyMemberDomains --project=PROJECT_ID --effective |
Triage order
- Which principal made the call (
gcloud auth list, or theprincipalEmailin the audit log)? - Which permission and which resource (read the exact error text)?
- Run the troubleshooter for that triple.
- Read the allow policy on the resource and each ancestor.
- Only then consider propagation delay, which is the least likely cause.
Videos age quickly; the links below are search pages and official documentation, not pinned videos. Check the publication date against the current IAM documentation.
Official reading: IAM overview · Allow policies · Principal identifiers.
Module 2 · Role types and least privilege
- Compare basic, predefined and custom roles and choose the right type for a given need.
- Inspect a role with gcloud, create a custom role from a list of permissions, and bind it by its full name.
- Use IAM Recommender and Policy Intelligence ideas to remove unused permissions and to review excess grants.
The short answer
A role (角色) is a named bundle of permissions. Google Cloud has three kinds. Basic roles (基本角色) are broad and old. Predefined roles (预定义角色) are maintained by Google for specific jobs. Custom roles (自定义角色) are lists that you maintain. Least privilege (最小权限) means choosing the narrowest role at the lowest level, and shrinking it over time with data.
What: the three role types
| Type | Examples | Who maintains it | Granularity | Use it for |
|---|---|---|---|---|
| Basic | roles/viewer, roles/editor, roles/owner, roles/browser | Very coarse: thousands of permissions across services | Sandboxes and personal projects; roles/browser for read-only hierarchy visibility | |
| Predefined | roles/storage.objectViewer, roles/compute.instanceAdmin.v1, roles/logging.viewer | Per product and per job | Default choice for nearly every grant | |
| Custom | projects/PROJECT_ID/roles/logReader | Your organization | Exactly the permissions you list | When no predefined role is small enough, or when a job needs permissions from several products |
Why: the problem with broad roles
- Blast radius. A stolen credential with Editor can create VMs, read storage, change firewall rules and delete data in a project.
- Audit difficulty. "Editor" tells a reviewer nothing about what the principal actually does.
- Hidden defaults. Several older services grant Editor automatically to their default service accounts (Module 4). A basic role in the wrong place spreads through the system.
How it works: permissions, naming and stages
- Permission names follow
service.resource.verb. Verbs such asget,list,create,update,deleteandsetIamPolicymake a role easy to scan: a role with onlygetandlistverbs is read-only. - Predefined roles change. When Google adds a feature, it can add permissions to a predefined role. This keeps the role useful but means the permission list is not frozen. Custom roles do not change on their own, so you must add new permissions when a product evolves.
- Launch stage. Roles have a stage:
ALPHA,BETA,GA,DEPRECATEDorDISABLED. A disabled role stays in policies but grants nothing, which is a safe way to retire a role before deleting it. - Level. Create a custom role at the organization when many projects need it, and at a project when it is specific to one workload. A role defined in a project cannot be granted in another.
- Not every permission is allowed in a custom role. Some permissions are supported only in predefined roles. If
createsays a permission is not valid, check the "custom role support" column in the permissions reference. - Limits. There are quota limits on the number of custom roles and on permissions per role. Check the current limits in the documentation before you design a role catalogue.
The decision logic: which role?
- Name the task in plain words: "read logs", "deploy to Cloud Run", "manage buckets".
- Search predefined roles for it:
gcloud iam roles list --filter="title:Logs"or the roles reference. - Pick the smallest predefined role that covers the task. Look at
includedPermissionsto confirm. - If the role is too large, or you need a mix from two products, create a custom role with exactly the permissions from the audit log or from the troubleshooter.
- Bind it at the lowest level (resource or project) and to a group or service account.
- After a month, review IAM Recommender and remove what is unused.
When to use each type
| Situation | Choose | Why |
|---|---|---|
| Personal learning project | Owner on the project is acceptable | No other users; the project is disposable |
| Developers deploy an app to Cloud Run | Predefined (Cloud Run Developer, plus Service Account User on the runtime account) | Google updates them with the product |
| Auditors need read access to configuration of everything | Predefined viewer roles such as Security Reviewer | Broad read, no write |
| A pipeline must start and stop VMs with a given label only | Predefined Instance Admin with a condition (Module 3), or a custom role | Predefined roles may include more than needed |
| A job needs three permissions from three products | Custom role | Avoids three broad predefined roles |
What roles are confused with
| Often confused with | The difference |
|---|---|
| Google Workspace admin roles | These manage users and groups in the Admin console. They are separate from Google Cloud IAM roles. |
| Legacy "primitive roles" and "legacy roles" | "Primitive" is the old name for basic roles. Do not mix them with product-specific legacy roles. |
| Groups | A group is a set of principals; a role is a set of permissions. Access is the combination of both in a binding. |
| Organization Policy | It restricts configurations, not people. Even Owner cannot violate a constraint. |
| AWS managed policies and Azure built-in roles | Predefined roles are the equivalent. Custom roles map to AWS customer-managed policies and Azure custom roles, but are listed permissions only, not JSON statements with resources. |
Figure 1. Roles from broad to narrow. Move down the stack as soon as the requirement is known; stop at predefined unless a gap forces a custom role.
Figure 2. Decision logic. The most common mistake is jumping to a custom role before checking the predefined list and conditions.
In Figure 1, see how the stack narrows as you move down; the cost is more upkeep. In Figure 2, notice that a custom role is the last choice, not the first.
The animation shows the lifecycle of a least-privilege role: inspect a predefined role, create a custom one, bind it to a group, and later let IAM Recommender propose a smaller role based on observed use.
All role commands below are metadata operations and are free. Creating or updating roles needs iam.roles.create or iam.roles.update (for example roles/iam.roleAdmin) on the project or organization.
gcloud iam roles list
Purpose. Lists roles. Without a scope it lists predefined roles; with --project or --organization it lists custom roles at that level. Free.
gcloud iam roles list --filter="name:roles/storage" --format="table(name,title,stage)"
Flags. --project=PROJECT_ID or --organization=ORG_ID for custom roles; --show-deleted to include deleted custom roles; --filter and --format for searching.
NAME TITLE STAGE roles/storage.admin Storage Admin GA roles/storage.objectAdmin Storage Object Admin GA roles/storage.objectCreator Storage Object Creator GA roles/storage.objectViewer Storage Object Viewer GA
Production use. Run it in CI to list the custom roles of an organization and compare with the roles declared in Terraform.
gcloud iam roles describe
Purpose. Prints the permissions, stage and etag of one role. Use it before every grant to see exactly what is included. Free.
gcloud iam roles describe roles/storage.objectViewer
description: Grants access to view objects and their metadata, excluding ACLs. etag: AA== includedPermissions: - resourcemanager.projects.get - resourcemanager.projects.list - storage.managedFolders.get - storage.managedFolders.list - storage.objects.get - storage.objects.list name: roles/storage.objectViewer stage: GA title: Storage Object Viewer
The exact permission list changes over time; the output above is illustrative.
Custom roles. Add --project=PROJECT_ID or --organization=ORG_ID and the short ROLE_ID: gcloud iam roles describe logReader --project=PROJECT_ID.
Common errors. NOT_FOUND: The role named roles/... was not found usually means a typo, or a custom role was referenced without its level.
gcloud iam list-testable-permissions
Purpose. Lists the permissions that can be tested on a resource, which helps when you build a custom role. Free.
gcloud iam list-testable-permissions //cloudresourcemanager.googleapis.com/projects/PROJECT_ID \ --filter="name:logging.logEntries" --format="value(name)"
logging.logEntries.create logging.logEntries.list logging.logEntries.route
Check gcloud iam list-testable-permissions --help for flags such as --page-size; the full list is long.
gcloud iam roles create (write, free)
Purpose. Creates a custom role at a project or an organization. A permission list on the command line is fine for small roles; use a YAML file for review and version control.
gcloud iam roles create logReader \ --project=PROJECT_ID \ --title="Log Reader (lab)" \ --description="Read log entries and list log names only" \ --permissions=logging.logEntries.list,logging.logs.list \ --stage=GA
Flags. --permissions is a comma-separated list; --file=role.yaml replaces title, description, permissions and stage with a file; --organization=ORG_ID instead of --project creates it for the whole organization; --stage accepts ALPHA, BETA, GA, DEPRECATED or DISABLED.
Created role [logReader]. description: Read log entries and list log names only etag: BwYabcd1234= includedPermissions: - logging.logEntries.list - logging.logs.list name: projects/PROJECT_ID/roles/logReader stage: GA title: Log Reader (lab)
Common errors. INVALID_ARGUMENT: Permission ... is not valid (typo, or not supported in custom roles); ALREADY_EXISTS when the ID was used by a role that was deleted recently, because deleted role IDs cannot be reused immediately.
Role file form. The same role in a file that you can keep in Git:
title: "Log Reader (lab)" description: "Read log entries and list log names only" stage: "GA" includedPermissions: - logging.logEntries.list - logging.logs.list
gcloud iam roles create logReader --project=PROJECT_ID --file=role.yaml
gcloud iam roles update (write, free)
Purpose. Changes a custom role. Use --add-permissions and --remove-permissions for small edits; they are applied with an etag check.
gcloud iam roles update logReader --project=PROJECT_ID \ --add-permissions=logging.views.list
Check gcloud iam roles update --help for the flags in your SDK version.
Bind the custom role (write, free)
A custom role is referenced by its full name when you bind it.
gcloud projects add-iam-policy-binding PROJECT_ID \ --member="group:GROUP_EMAIL" \ --role="projects/PROJECT_ID/roles/logReader"
gcloud iam roles delete and undelete (write, free)
Purpose. Deleting a custom role stops it from granting permissions, but existing bindings stay in the policy and show as deleted: until you remove them. A deleted role can be restored for a limited time with undelete.
gcloud iam roles delete logReader --project=PROJECT_ID gcloud iam roles undelete logReader --project=PROJECT_ID
The recovery window and the point after which an ID can be reused are documented on the custom roles page; check them before you plan a clean-up job.
gcloud recommender recommendations list
Purpose. Reads IAM Recommender output for a project (free; the Recommender API must be enabled). Each recommendation proposes replacing or removing a role.
gcloud recommender recommendations list \ --project=PROJECT_ID \ --location=global \ --recommender=google.iam.policy.Recommender \ --format="table(name.basename(),stateInfo.state,primaryImpactCategory)"
NAME STATE PRIMARY_IMPACT_CATEGORY 7b0e1f2a-3c4d-4a5e-8f90-1234567890ab ACTIVE SECURITY
The output is illustrative and may be empty when no principal has excess permissions. Check gcloud recommender recommendations --help for the flags in your SDK version.
Production use. Export recommendations to BigQuery or review them monthly. Recommendations are advice: nobody should apply them automatically on a production folder without a human check.
google_organization_iam_custom_role) in Git. A pull request that adds a permission is then a reviewable change with an author and a reason.Lab 2: build and test a custom role (about 15 minutes, free)
Goal. Create a project custom role that can read logs only, compare it with a predefined role, and see what Recommender would say.
Prerequisites. The sandbox project and the test group from Module 1; roles/iam.roleAdmin (or Owner) on the project; the IAM API enabled. IDs in the expected output are illustrative.
- Inspect the predefined role you might use:
gcloud iam roles describe roles/logging.viewer --format="value(includedPermissions)". Count the permissions and note that it includes more than log entries. - Create the YAML file
role.yamlfrom the commands tab and rungcloud iam roles create logReader --project=PROJECT_ID --file=role.yaml. - Verify the role:
gcloud iam roles describe logReader --project=PROJECT_ID --format="value(stage,includedPermissions)". ExpectGAand the two permissions. - List custom roles in the project:
gcloud iam roles list --project=PROJECT_ID --format="table(name,stage)". - Bind the role to the test group with its full name
projects/PROJECT_ID/roles/logReader. - Check the binding:
gcloud projects get-iam-policy PROJECT_ID --flatten="bindings[].members" --filter="bindings.role:logReader" --format="table(bindings.role,bindings.members)". - Add one missing permission and verify:
gcloud iam roles update logReader --project=PROJECT_ID --add-permissions=logging.views.listfollowed by step 3. The list now has three permissions. - Look at recommendations:
gcloud recommender recommendations list --project=PROJECT_ID --location=global --recommender=google.iam.policy.Recommender. A new project usually has no recommendations yet, because the recommender needs usage data. That is expected.
Expected result.
ROLE MEMBERS projects/PROJECT_ID/roles/logReader ['group:GROUP_EMAIL']
Cost. Free. Roles and bindings are metadata.
Cleanup. Remove the binding, then disable and delete the role:
gcloud projects remove-iam-policy-binding PROJECT_ID \ --member="group:GROUP_EMAIL" \ --role="projects/PROJECT_ID/roles/logReader" gcloud iam roles delete logReader --project=PROJECT_ID
Keep the role and the binding for Module 7, where the final lab uses them. Delete them only at the end of the hour.
Lab 2b (optional): compare roles by permission count
Run gcloud iam roles describe roles/viewer --format="value(includedPermissions)", then the same for roles/editor and a predefined role of your choice, and count the entries with | tr ';' '\n' | wc -l. The order of magnitude between a basic and a predefined role is the argument for this whole module.
Real cases
- Editor for the data team. A data team received Editor on every analytics project "to get started". A leaked notebook token could then read unrelated buckets and start VMs. After replacing Editor with BigQuery and Storage roles on specific datasets and buckets, the same token could only touch what the notebooks needed.
- Custom role that rotted. A security team built a custom role for incident responders. Two years later a responder could not use a new logging feature because the role had never been updated. The team moved to predefined roles wherever one existed and kept custom roles only for gaps, with an owner and a quarterly check.
- Recommender clean-up. A platform team reviewed IAM Recommender once per quarter. Most recommendations removed roles from accounts that no longer ran jobs. The team tracked the number of excess-permission recommendations as a security metric and applied changes in a pull request, not in the console.
Practices
- Ban basic roles on production folders and projects. Allow
roles/vieweronly for non-sensitive projects, and consider an Organization Policy or detective control that reports Owner and Editor grants. - Keep a small role catalogue: a handful of custom roles in the organization, each with a description, an owner and a ticket reference.
- Prefer predefined roles first. Add a custom role only after you can state which permission is missing or too much.
- Review IAM Recommender output and Policy Analyzer results on a schedule; keep the decision and the reason.
- Use service accounts per workload so that usage data is clear enough for the recommender (Module 4).
Security notes
iam.serviceAccounts.getAccessToken, iam.serviceAccountKeys.create, resourcemanager.projects.setIamPolicy or iam.roles.update into broad custom roles. They let a principal gain other principals' rights (privilege escalation). Treat them as sensitive and limit them to a small, audited group.logReader, not teamARole), so reuse is natural and reviews are short.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
INVALID_ARGUMENT: Permission ... is not valid on roles create | Typo, or the permission is not supported in custom roles | gcloud iam list-testable-permissions ... and the permissions reference |
ALREADY_EXISTS when creating a role | The ID exists or was deleted recently | gcloud iam roles list --project=PROJECT_ID --show-deleted |
| Custom role binding rejected in another project | The role was created in a project, not the organization | Recreate it with --organization=ORG_ID or define it in each project |
| User has the role but a new feature is denied | The custom role lacks the new permission | Compare with the predefined role's includedPermissions and add the missing one |
Binding shows deleted: in the policy | The principal or role was deleted | Remove the stale binding; recreate the role if needed |
| No recommendations appear | API not enabled, too little usage data, or the principal is new | Enable recommender.googleapis.com; wait for usage history |
Triage order
- Read the error and note the exact permission name.
- Describe the role that should contain it (
gcloud iam roles describe). - If the role lacks it, decide: pick another predefined role, or update the custom role.
- Re-run the troubleshooter after a short wait to confirm the change.
- Record the new permission in the role definition under version control.
Official videos change often. These links are search pages and official documentation, not pinned videos.
Official reading: Roles and permissions · Creating custom roles · Role recommendations · Permissions reference.
Module 3 · Inheritance, IAM Conditions and deny policies
- Calculate effective access for a principal from allow policies on a resource and all of its ancestors.
- Add a conditional binding (time-limited or resource-scoped) with gcloud and explain why conditional policies need version 3.
- Explain how deny policies override allow policies and when to use them instead of removing a role.
The short answer
Every resource sits in the resource hierarchy (organization, folders, projects, resources). IAM looks at the allow policy of the resource and of every ancestor and combines them. This is policy inheritance (策略继承). Two tools refine the picture: an IAM Condition (IAM 条件) narrows a binding, and a deny policy (拒绝策略) blocks permissions even if an allow policy grants them.
What: effective access
effective allow = org allow ∪ folder(s) allow ∪ project allow ∪ resource allow
request is allowed = (no matching deny) AND (some allow binding grants the permission
and its condition, if any, is true)
- Union, not override. A role granted at any level applies to everything below it. A project binding with a smaller role does not "shrink" a folder-level Editor.
- Layers are independent. Each level can be owned by a different team. The platform team owns the organization and folders; an application team owns its project.
- Child resources of a project (buckets, datasets, secrets, service accounts, Pub/Sub topics) often have their own allow policies, which also join the union.
Why: the reasons for inheritance
- One binding on a folder covers every present and future project in it. New projects are governed on day one.
- The platform team can set safe defaults high up (for example, security reviewers read everything) while application teams manage low-level access.
- The cost of this is that a broad grant is hard to see from below. When you look at a project policy, you see only a part of the picture.
How it works: evaluation order
- Principal access boundary (when configured): can limit which resources a principal is even allowed to use. Check the product page if your organization uses it.
- Deny policies on the resource and its ancestors. A matching deny rule stops the evaluation with "denied", unless the principal is in the rule's exception list.
- Allow policies from the resource up to the organization. Each binding's condition is evaluated against the request.
- If no binding grants the permission, the result is the default: denied.
Organization Policy is a separate check on configuration and applies to the action regardless of IAM; it is covered in Hour 3.
IAM Conditions
A condition is a short Common Expression Language (CEL) expression attached to one binding. It has a title (required), a description (optional) and an expression.
| Use | Example expression | Meaning |
|---|---|---|
| Expiry date | request.time < timestamp("2027-01-01T00:00:00Z") | Access ends automatically; no ticket to remember |
| Business hours | request.time.getHours("Europe/London") >= 8 && request.time.getHours("Europe/London") < 18 | Role works only in a time window (check the documentation for the time functions you can use) |
| Resource name prefix | resource.name.startsWith("projects/_/buckets/lab-bucket/objects/reports/") | Role limited to one folder of objects in one bucket |
| Resource type | resource.type == "compute.googleapis.com/Instance" | Role applies only to VMs, not disks |
| Resource tag | resource.matchTag("ORG_ID/environment", "development") | Role applies only to resources that carry the tag; useful for one binding at the folder level |
- Not every service supports conditions on every resource. Check the "resource types that accept IAM Conditions" page; a binding on an unsupported resource is rejected or ignored.
- Version 3. A policy containing conditional bindings must be read and written as version 3. gcloud's
add-iam-policy-bindinghandles the version; the rawset-iam-policyneeds"version": 3in the file, or the conditions may be dropped. - Identity of a binding. A binding is the triple role, member and condition. The same role and member can appear twice with different conditions.
- Expression length and complexity are limited. Keep conditions short; push complicated logic into tags and groups.
Deny policies
A deny policy is attached to an organization, a folder or a project. Each deny rule has the following fields:
| Field | Meaning |
|---|---|
deniedPrincipals | Who is blocked. Uses the principal set syntax: principalSet://goog/group/GROUP_EMAIL, principal://goog/subject/EMAIL, or principalSet://goog/public:all. |
exceptionPrincipals | Principals who are not blocked even if they match a denied principal, for example a break-glass group. |
deniedPermissions | The blocked actions, in the form SERVICE_FQDN/RESOURCE.VERB, for example iam.googleapis.com/serviceAccountKeys.create. |
exceptionPermissions | Permissions that stay allowed when a wildcard in deniedPermissions covers them. |
denialCondition | A condition for when the rule applies. The attributes allowed are more limited than for allow conditions (resource tags are the main use). Check the documentation. |
- Deny policies are a guardrail on who and which permissions, independent of the roles that grant them.
- The role
roles/iam.denyAdminmanages them; it is a very sensitive role. - Not every permission can be denied. The documentation lists supported permissions (many are, but not all).
- Deny policies are inherited downwards like allow policies, so a deny at a folder protects every project below it.
When to use which control
| Need | Use | Why |
|---|---|---|
| Give access for a limited time | Conditional binding with an expiry | Expires by itself; the record stays in the policy |
| Give a role only on some resources of a type | Condition with a tag or a name prefix | One binding, no per-resource grants |
| Nobody except break-glass may delete projects | Deny policy at the organization with exceptions | Overrides Owner and any other role |
| Nobody may create service account keys | Organization Policy iam.disableServiceAccountKeyCreation (Hour 3), possibly with a deny policy | Configuration limit; deny adds a second layer |
| Remove an unneeded role | Remove the binding where it was granted | Deny is for exceptions, not for tidy-up |
What these controls are confused with
| Often confused with | The difference |
|---|---|
| Organization Policy | Checks the configuration of a resource (regions, external IPs, public buckets). Deny policies check the principal and permission. |
| VPC Service Controls | Limits API traffic that crosses a perimeter, based on network context and identity (Hour 3). |
| Firewall rules | Network packets. IAM Conditions do not see ports and IP addresses of a normal request. |
| Azure deny assignments, AWS explicit deny | Similar in effect. In Google Cloud the deny policy is its own object, separate from the allow policy. |
Figure 1. Effective access is a union. Seen from the bucket, only one of four grants is visible in its own policy.
Figure 2. Evaluation order. Deny comes first; the default is denied.
In Figure 1, count how many policies you would have to open to explain one bucket's access; that is why tools such as the troubleshooter and Policy Analyzer exist. In Figure 2, notice that conditions live inside the allow step, while deny is a separate first gate.
The animation traces one request through the evaluation: deny policies first, then the organization, folder and project allow policies, with a condition checked when a binding carries one. The final log line names the role that granted access and the level it came from.
Reads are free. Policy writes are free but change access, so use the sandbox project and a test group. Replace ORG_ID, FOLDER_ID, PROJECT_ID and GROUP_EMAIL.
gcloud resource-manager folders get-iam-policy and organizations get-iam-policy
Purpose. Reads the allow policy of a parent, so you can see what a project inherits (free, read-only).
gcloud resource-manager folders get-iam-policy FOLDER_ID --format="yaml(bindings)" gcloud organizations get-iam-policy ORG_ID --format="yaml(bindings)"
bindings: - members: - group:platform-engineers@example.com role: roles/storage.admin - members: - group:security-reviewers@example.com role: roles/iam.securityReviewer
Common errors. PERMISSION_DENIED for resourcemanager.folders.getIamPolicy; many project admins cannot read the policies above their project, so they cannot see why a user has access. Give security reviewers read access at the organization.
Production use. A scheduled job exports organization and folder policies and lists high-risk roles.
gcloud projects add-iam-policy-binding with --condition (write, free)
Purpose. Adds a role that expires on a date.
gcloud projects add-iam-policy-binding PROJECT_ID \
--member="group:GROUP_EMAIL" \
--role="roles/compute.viewer" \
--condition='expression=request.time < timestamp("2027-01-01T00:00:00Z"),title=lab-expiry,description=Access for the lab, ends on 1 January 2027'
Flags. --condition takes a comma-separated list of expression=…, title=… and optional description=…. If the expression or the description contains a comma, use a custom delimiter (see gcloud topic escaping) or --condition-from-file=condition.yaml. --condition=None adds an unconditional binding.
Updated IAM policy for project [PROJECT_ID].
bindings:
- condition:
description: Access for the lab, ends on 1 January 2027
expression: request.time < timestamp("2027-01-01T00:00:00Z")
title: lab-expiry
members:
- group:GROUP_EMAIL
role: roles/compute.viewer
etag: BwYabe789=
version: 3
Common errors. Adding a binding without specifying a condition to a policy with conditional bindings is prohibited in non-interactive mode: pass --condition=None or a condition. INVALID_ARGUMENT: ... condition ... not supported means the resource type does not accept conditions.
Condition from a file
expression: request.time < timestamp("2027-01-01T00:00:00Z")
title: lab-expiry
description: Access for the lab, ends on 1 January 2027
gcloud projects add-iam-policy-binding PROJECT_ID \ --member="group:GROUP_EMAIL" --role="roles/compute.viewer" \ --condition-from-file=condition.yaml
Remove a conditional binding (write, free)
To remove a conditional binding you must give the same condition, otherwise gcloud will not know which of the bindings to remove.
gcloud projects remove-iam-policy-binding PROJECT_ID \ --member="group:GROUP_EMAIL" --role="roles/compute.viewer" \ --condition-from-file=condition.yaml
gcloud projects get-iam-policy --format=json with the version
Purpose. Makes sure conditions are visible when you read a policy by hand. gcloud requests the version it needs for conditional policies, and the output includes "version": 3. When you call the REST API yourself, set options.requestedPolicyVersion to 3.
gcloud projects get-iam-policy PROJECT_ID --format=json | head -30
gcloud asset analyze-iam-policy
Purpose. Policy Analyzer: answers "who can do this on that resource", including inherited access (free to run, within the quotas of the Cloud Asset API; the API must be enabled).
gcloud asset analyze-iam-policy \ --organization=ORG_ID \ --full-resource-name=//cloudresourcemanager.googleapis.com/projects/PROJECT_ID \ --permissions=compute.instances.delete \ --format="table(analysisResults.iamBinding.role,analysisResults.iamBinding.members)"
Check gcloud asset analyze-iam-policy --help for the flags in your SDK version; the analysis needs an organization scope or a project scope, and the exact options for expanding groups and roles differ across releases.
gcloud iam policies create (deny policy; write, free)
Purpose. Creates a deny policy on a project. Deny policies are a separate resource from the allow policy and are managed with gcloud iam policies. The attachment point is the resource name without the leading double slash.
{
"displayName": "Block service account key creation for lab group",
"rules": [
{
"denyRule": {
"deniedPrincipals": ["principalSet://goog/group/GROUP_EMAIL"],
"deniedPermissions": ["iam.googleapis.com/serviceAccountKeys.create"]
}
}
]
}
gcloud iam policies create lab-deny-keys \ --attachment-point=cloudresourcemanager.googleapis.com/projects/PROJECT_ID \ --kind=denypolicies \ --policy-file=deny-policy.json
Check gcloud iam policies create --help for the flags in your SDK version. You need roles/iam.denyAdmin on the project, and the IAM API enabled. A deny policy takes effect after a short propagation delay.
gcloud iam policies list \ --attachment-point=cloudresourcemanager.googleapis.com/projects/PROJECT_ID \ --kind=denypolicies gcloud iam policies delete lab-deny-keys \ --attachment-point=cloudresourcemanager.googleapis.com/projects/PROJECT_ID \ --kind=denypolicies
Common errors. INVALID_ARGUMENT for a permission that is not supported by deny policies, or a principal in the wrong format; PERMISSION_DENIED without iam.denypolicies.create.
Production use. Keep deny policies in Terraform (google_iam_deny_policy), review each rule with the security team, and always add an exception group for break-glass access.
Lab 3: inheritance, an expiring role and a deny rule (about 20 minutes, free)
Goal. See inherited access, add an expiring conditional binding, and block one action with a deny policy.
Prerequisites. The sandbox project and test group from the setup page. If you have an organization and a lab folder, you can use the folder in steps 1 to 3; without an organization, skip those steps (no folders exist) and run steps 4 onwards. IDs in the expected output are illustrative.
- (With an organization) Grant the group a read role on the lab folder:
gcloud resource-manager folders add-iam-policy-binding FOLDER_ID --member="group:GROUP_EMAIL" --role="roles/browser". - Run the troubleshooter for a member on a project inside the folder:
gcloud policy-troubleshoot iam //cloudresourcemanager.googleapis.com/projects/PROJECT_ID --principal-email=MEMBER_EMAIL --permission=resourcemanager.projects.get. The output must show the access granted through the folder policy. - Confirm the project policy itself has no binding for the group:
gcloud projects get-iam-policy PROJECT_ID --flatten="bindings[].members" --filter="bindings.members:group:GROUP_EMAIL" --format="value(bindings.role)". It must print nothing, which proves access is inherited. - Add the expiring conditional binding from the commands tab (
lab-expiry). - Verify it is conditional:
gcloud projects get-iam-policy PROJECT_ID --format="yaml(bindings)"and look for theconditionblock andversion: 3in the full output. - Test the condition with the troubleshooter for
compute.instances.list. It must report a grant while the date is before the limit. To see the condition fail, create a second binding withexpression=request.time < timestamp("2020-01-01T00:00:00Z")and a different role such asroles/pubsub.viewer, and troubleshootpubsub.topics.list. Expect no access, with a condition that evaluated to false. - Create the deny policy file and the policy from the commands tab, using
GROUP_EMAILfor the test group. - Wait a minute, then run the troubleshooter for
iam.serviceAccountKeys.createfor a member of the group (the deny permission uses the formiam.googleapis.com/serviceAccountKeys.createin the policy, and the troubleshooter takes the plain permission name). Expect the result to mention a deny policy.
Expected result.
access: GRANTED explainedPolicies: - access: GRANTED fullResourceName: //cloudresourcemanager.googleapis.com/projects/PROJECT_ID ... - access: DENIED # for the deny test: the deny policy matched ...
The output is long and format details vary; look for the access lines and which policy they belong to.
Cost. Free. No billable resources are created.
Cleanup. Delete the deny policy and remove the bindings, in this order:
gcloud iam policies delete lab-deny-keys \ --attachment-point=cloudresourcemanager.googleapis.com/projects/PROJECT_ID --kind=denypolicies gcloud projects remove-iam-policy-binding PROJECT_ID \ --member="group:GROUP_EMAIL" --role="roles/compute.viewer" --condition-from-file=condition.yaml gcloud resource-manager folders remove-iam-policy-binding FOLDER_ID \ --member="group:GROUP_EMAIL" --role="roles/browser"
Lab 3b (optional): resource-name condition
Create a Cloud Storage bucket in the sandbox and bind roles/storage.objectViewer to the test group on the project with resource.name.startsWith("projects/_/buckets/BUCKET_NAME/objects/reports/"). Only objects below reports/ become readable. A small bucket costs almost nothing, but delete it afterwards: gcloud storage rm --recursive gs://BUCKET_NAME.
Real cases
- Hidden access from a folder binding. An application team removed a former developer from the project policy, yet the person could still read data. The cause was a folder-level Editor binding that a previous reorganization had left behind. The team added Policy Analyzer to the offboarding checklist.
- Temporary production access. On-call engineers needed read access to production during incidents. Instead of permanent bindings, the platform team used a conditional binding that expires after 8 hours and is created by a ticketed workflow. When the time ends the role stops working with no clean-up step; the expired bindings are removed weekly.
- Deny on destructive actions. A regulated business wanted nobody except a break-glass group to delete projects or change organization policies. An organization-level deny policy covered those permissions, with an exception group of two accounts protected by hardware keys. Owners in the projects could still do their daily work.
Practices
- Grant broad roles at high levels only to small, reviewed groups. Grant job-specific roles at a project or resource.
- Use the same naming for conditions as for tickets (
inc-12345-expires-2027-01-01) so a reviewer finds the reason. - Use tags with conditions to scope a folder-level binding to development resources only, so developers do not get the same role on production resources in the same folder.
- Keep deny policies few and documented. Record the owner, the reason and the exceptions.
- Run Policy Analyzer before removing a binding and after adding a deny policy, so you see the effect.
Security notes
roles/owner or roles/resourcemanager.projectIamAdmin to a principal can create new bindings that last longer than the original condition. Do not rely on a time condition to limit someone who can edit the policy.SetIamPolicy events. Alert on conditions that include very long expiry dates (for example more than a year).Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
| A user has access but the project policy shows nothing for them | Inherited binding from a folder or the organization, or a group membership | gcloud policy-troubleshoot iam ... or gcloud asset analyze-iam-policy ... |
| Role removed from the project but access remains | The same role (or another) is granted above | Read folder and organization policies |
| Access ended unexpectedly at a certain date | An expired conditional binding | Look for condition blocks in get-iam-policy |
Adding a binding without specifying a condition ... is prohibited | The role already has conditional bindings | Pass --condition=None or a condition |
| Conditions disappeared after a script ran | A client read or wrote policy version 1 | Use version 3, or use the single-binding commands |
| User denied although the role is granted | A deny policy at some ancestor | Troubleshooter output (deny section); gcloud iam policies list --kind=denypolicies at each level |
| Deny policy does not take effect | Permission not supported for deny, wrong principal format, or propagation delay | Check the supported permissions page and the principal syntax |
Triage order
- Run the troubleshooter first; it covers allow, deny and conditions in one answer.
- If it is unavailable, read allow policies from the resource upwards.
- List deny policies at the same levels.
- Check conditions, especially time limits and tag matches.
- Last, consider propagation and caching.
These are search pages and official documentation, not pinned videos. Check the publication date.
- YouTube search: IAM Conditions and temporary access
- YouTube search: IAM deny policies
- YouTube search: Policy Analyzer
Official reading: IAM Conditions overview · Deny policies · Policy Troubleshooter · Resource hierarchy.
Module 4 · Service accounts
- Explain a service account as both an identity (a principal) and a resource that has its own allow policy.
- Create a service account, grant it a narrow role, and test it with
--impersonate-service-accountwithout ever creating a key. - Distinguish
roles/iam.serviceAccountUser(attach) fromroles/iam.serviceAccountTokenCreator(impersonate), and contain the default service accounts.
The short answer
A service account (服务账号) is an identity for software, not a person. It has an email such as ci-deployer@PROJECT_ID.iam.gserviceaccount.com. It plays two roles: as a principal it receives roles ("this account may read objects in that bucket"), and as a resource it has its own allow policy ("these people may attach or impersonate this account").
What: kinds of service accounts
| Kind | Example | Who manages it | Notes |
|---|---|---|---|
| User-managed | ci-deployer@PROJECT_ID.iam.gserviceaccount.com | You | The type you create for workloads. One per workload and per environment. |
| Default | PROJECT_NUMBER-compute@developer.gserviceaccount.com, PROJECT_ID@appspot.gserviceaccount.com | Created by Google when a service is first used, then yours to manage | Historically gets Editor. Avoid using it for real workloads. |
| Service agents | service-PROJECT_NUMBER@compute-system.iam.gserviceaccount.com | Used by Google services to act in your project. Do not delete them, and do not grant them roles unless a document says so. |
Why: workloads need an identity
- Code that runs on a VM, in a container or in a pipeline must call Google APIs. Giving it a person's credentials ties the workload to that person and breaks when they leave.
- A dedicated service account carries only the roles for that workload, so the audit log shows exactly what the workload did.
- When the account is attached to a resource, the platform supplies short-lived tokens automatically through the metadata server. The code never handles a secret.
How it works: three ways to use a service account
- Attach it to a resource. A VM, Cloud Run service, Cloud Function, GKE node pool (or Workload Identity binding) runs as the account. The code uses Application Default Credentials (ADC) and receives a token from the metadata server. The deployer needs
iam.serviceAccounts.actAson the account (roles/iam.serviceAccountUser). - Impersonate it. A person or another service account asks for a short-lived token with
--impersonate-service-accountor the IAM Credentials API. The caller needsiam.serviceAccounts.getAccessToken, whichroles/iam.serviceAccountTokenCreatorcontains. Used for deployments, tests and "break-glass as the pipeline" work. - Use a key. A JSON key file is a long-lived secret. Avoid it. Use it only when no other option works, for example some legacy on-premises software, and then restrict, rotate and monitor it.
Roles around service accounts
| Role | Grants the ability to | Typical holder |
|---|---|---|
roles/iam.serviceAccountUser | Attach the account to resources (actAs) | Deployers and pipelines, on the specific accounts they deploy with |
roles/iam.serviceAccountTokenCreator | Impersonate: create access tokens and sign blobs | Platform engineers or a pipeline account that acts as a deploy account |
roles/iam.serviceAccountAdmin | Create, delete and edit service accounts and their policies | Platform team only |
roles/iam.serviceAccountKeyAdmin | Create and delete keys | Nobody by default; sensitive |
roles/iam.workloadIdentityUser | Let a federated identity or a Kubernetes service account use the account (Module 5) | Federated identities |
Grant these on the specific service account (its own policy), not on the whole project. A project-level roles/iam.serviceAccountUser lets the holder act as every service account in the project, including those with powerful roles; this is a classic privilege-escalation path.
Default service accounts and the Editor problem
- When you enable Compute Engine, the Compute Engine default service account is created, and historically it was granted
roles/editoron the project. A VM created without a flag would run as that account with Editor access. - The Organization Policy boolean constraint
constraints/iam.automaticIamGrantsForDefaultServiceAccountsstops that automatic grant when it is enforced. Check whether your organization already enforces it (newer organizations often do):gcloud org-policies describe iam.automaticIamGrantsForDefaultServiceAccounts --project=PROJECT_ID --effective. - The constraint only affects accounts created after it is enforced. Existing Editor grants remain until you remove them.
- Better still: create a dedicated service account per workload and pass
--service-accountwhen you create a VM, instead of relying on the default.
Other relevant constraints (Hour 3 covers them): iam.disableServiceAccountKeyCreation blocks new keys, iam.disableServiceAccountCreation restricts who can create accounts, and iam.serviceAccountKeyExpiryHours sets the lifetime of keys that are allowed.
When to use which approach
| Workload | Identity approach |
|---|---|
| VM, Cloud Run, Cloud Functions, GKE on Google Cloud | Dedicated service account attached to the resource |
| Pipeline on GitHub Actions, GitLab, Azure DevOps | Workload Identity Federation (Module 5), then impersonate a deploy service account |
| Engineer who needs to test what the pipeline can do | Impersonation with Token Creator, time-bound |
| Software that cannot use any of the above | A key, as a documented exception with rotation and an owner |
What service accounts are confused with
| Often confused with | The difference |
|---|---|
| User accounts | Humans sign in interactively with passwords and 2-step verification. Service accounts have no password and cannot sign in to the console. |
| API keys | An API key identifies a project for quota and some public APIs. It is not an identity, and it has no roles. |
| OAuth client IDs | Used when an app asks a user for consent to act as that user. Service accounts act as themselves. |
| Access scopes on VMs | Legacy OAuth scopes that further limit what a VM's token can do. IAM roles are the main control; the common practice is to set cloud-platform scope and use IAM for the narrowing. |
| AWS IAM roles for EC2, Azure managed identities | Closest equivalents. An attached service account is similar to an instance profile or a managed identity. |
Figure 1. Three ways to use a service account. Only the first two avoid a long-lived secret.
Figure 2. One account, two policies. Left: who controls the account. Right: what the account can reach.
In Figure 1 follow the arrows: only the key option leaves a secret behind. In Figure 2 note that the roles on the left and right are independent. A person with Token Creator on the account can do whatever the account can do, so the left side must be as carefully reviewed as the right side.
The animation shows an impersonation call from a test command to the audit log. The token request is checked against the service account's own policy, a short-lived token is returned, and the log entry records both the service account and the person who impersonated it.
Service accounts and their bindings are metadata and free. A VM or other workload that uses them can cost money; this module's lab creates none. Replace PROJECT_ID, SA_NAME and YOUR_EMAIL.
gcloud iam service-accounts create (write, free)
Purpose. Creates a user-managed service account.
gcloud iam service-accounts create SA_NAME \ --project=PROJECT_ID \ --display-name="Lab reader" \ --description="Read-only identity for the IAM lab"
Flags. The ID (SA_NAME) is 6 to 30 characters, lowercase letters, digits and hyphens, and cannot be changed. --display-name is a label for humans; --description records the owner or purpose.
Created service account [SA_NAME].
Common errors. ALREADY_EXISTS for a name that is in use (a deleted account holds its name for a while); INVALID_ARGUMENT for names that break the pattern; PERMISSION_DENIED ... iam.serviceAccounts.create, or the constraint iam.disableServiceAccountCreation.
Production use. Create accounts with Terraform (google_service_account), name them by workload and environment (sa-ci-deploy-prod), and put the owner in the description.
gcloud iam service-accounts list and describe
Purpose. Lists and inspects accounts (free, read-only).
gcloud iam service-accounts list --project=PROJECT_ID \ --format="table(email,displayName,disabled)" gcloud iam service-accounts describe SA_NAME@PROJECT_ID.iam.gserviceaccount.com
EMAIL DISPLAY NAME DISABLED SA_NAME@PROJECT_ID.iam.gserviceaccount.com Lab reader False 123456789012-compute@developer.gserviceaccount.com Compute Engine default service account False
Grant a role to the service account on the project (write, free)
Here the service account is the member of a normal binding.
gcloud projects add-iam-policy-binding PROJECT_ID \ --member="serviceAccount:SA_NAME@PROJECT_ID.iam.gserviceaccount.com" \ --role="roles/browser"
gcloud iam service-accounts add-iam-policy-binding (write, free)
Purpose. Grants a role on the service account, which controls who may use it. Here you allow yourself to impersonate it.
gcloud iam service-accounts add-iam-policy-binding \ SA_NAME@PROJECT_ID.iam.gserviceaccount.com \ --member="user:YOUR_EMAIL" \ --role="roles/iam.serviceAccountTokenCreator"
Updated IAM policy for serviceAccount [SA_NAME@PROJECT_ID.iam.gserviceaccount.com]. bindings: - members: - user:YOUR_EMAIL role: roles/iam.serviceAccountTokenCreator etag: BwYabf012= version: 1
Production use. Use roles/iam.serviceAccountUser in the same way for deployers. Each of these bindings is a trust relationship; review them as carefully as the roles on the account.
Impersonate with --impersonate-service-account
Purpose. Runs any gcloud command as the service account for that single command (free; needs the iamcredentials.googleapis.com API enabled and Token Creator on the account).
gcloud projects describe PROJECT_ID \ --impersonate-service-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com \ --format="value(projectId)"
WARNING: This command is using service account impersonation. All API calls will be executed as [SA_NAME@PROJECT_ID.iam.gserviceaccount.com]. PROJECT_ID
Common errors. Failed to impersonate [...]. Make sure the account that's trying to impersonate it has access to the service account itself and the "roles/iam.serviceAccountTokenCreator" role means the Token Creator binding is missing or has not propagated, or the Credentials API is disabled. HttpError 403 ... PERMISSION_DENIED after the warning line means impersonation worked, but the service account lacks the role for the action.
Flags. To avoid repeating the flag in a session: gcloud config set auth/impersonate_service_account SA_EMAIL. Remove it with gcloud config unset auth/impersonate_service_account. To make client libraries use it too: gcloud auth application-default login --impersonate-service-account=SA_EMAIL.
Attach a service account to a VM (write, costs money when the VM runs)
Purpose. Shows the attach flag. It needs roles/iam.serviceAccountUser on the account and creates a billable VM, so it is not part of the lab.
gcloud compute instances create VM_NAME \ --zone=ZONE \ --service-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com \ --scopes=cloud-platform
Check gcloud compute instances create --help for the flags in your SDK version. Delete the VM when you finish: gcloud compute instances delete VM_NAME --zone=ZONE.
gcloud iam service-accounts disable, enable, delete, undelete (write, free)
Purpose. Retire an account in two steps: disable, observe for errors, delete later.
gcloud iam service-accounts disable SA_NAME@PROJECT_ID.iam.gserviceaccount.com gcloud iam service-accounts enable SA_NAME@PROJECT_ID.iam.gserviceaccount.com gcloud iam service-accounts delete SA_NAME@PROJECT_ID.iam.gserviceaccount.com
To restore a deleted account within the documented window, run gcloud iam service-accounts undelete NUMERIC_ID. The numeric ID is in the audit log of the deletion. Check gcloud iam service-accounts undelete --help.
gcloud iam service-accounts keys list
Purpose. Finds user-managed keys, the ones that are a risk (free, read-only).
gcloud iam service-accounts keys list \ --iam-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com \ --managed-by=user
Listed 0 items.
Production use. A scheduled job lists user-managed keys for every service account and opens a ticket for any key older than your limit. The goal is zero.
Check the default service account grant
gcloud org-policies describe iam.automaticIamGrantsForDefaultServiceAccounts \ --project=PROJECT_ID --effective gcloud projects get-iam-policy PROJECT_ID \ --flatten="bindings[].members" \ --filter="bindings.role:roles/editor AND bindings.members:compute@developer.gserviceaccount.com" \ --format="value(bindings.members)"
The first command shows whether the constraint is enforced; the second looks for the default Compute Engine account holding Editor. An empty result for the second is the target state. Check gcloud org-policies describe --help for the flags in your SDK version.
roles/editor or roles/owner to any serviceAccount: member.Lab 4: a service account without keys (about 20 minutes, free)
Goal. Create a service account, give it one narrow role, impersonate it, prove it can do exactly that, and retire it, without creating a key file.
Prerequisites. The sandbox project from the setup page; roles/iam.serviceAccountAdmin and permission to edit the project policy (Owner works); the IAM Service Account Credentials API enabled: gcloud services enable iamcredentials.googleapis.com --project=PROJECT_ID (free). IDs in the expected output are illustrative.
- Create the account:
gcloud iam service-accounts create lab-reader --project=PROJECT_ID --display-name="Lab reader". - Verify:
gcloud iam service-accounts list --project=PROJECT_ID --format="table(email,disabled)". The new account is listed. - Grant it
roles/browseron the project (command above, withlab-reader). - Check that it has no keys:
gcloud iam service-accounts keys list --iam-account=lab-reader@PROJECT_ID.iam.gserviceaccount.com --managed-by=user. ExpectListed 0 items. - Try to impersonate before you have the right:
gcloud projects describe PROJECT_ID --impersonate-service-account=lab-reader@PROJECT_ID.iam.gserviceaccount.com. Expect the "Failed to impersonate" error (unless you are Owner and have Token Creator through another path). - Grant yourself
roles/iam.serviceAccountTokenCreatoron the service account (command above,YOUR_EMAILis your user). Wait up to a minute. - Repeat step 5. Expect the impersonation warning and the project ID printed.
- Prove the boundary:
gcloud iam service-accounts list --project=PROJECT_ID --impersonate-service-account=lab-reader@PROJECT_ID.iam.gserviceaccount.com. ExpectPERMISSION_DENIEDforiam.serviceAccounts.list. The account can read the project but not list service accounts. - Find the audit record:
gcloud logging read 'protoPayload.authenticationInfo.principalEmail="lab-reader@PROJECT_ID.iam.gserviceaccount.com"' --project=PROJECT_ID --limit=2 --format="table(timestamp,protoPayload.methodName,protoPayload.authenticationInfo.serviceAccountDelegationInfo[0].principalSubject)". Admin Activity entries appear; Data Access entries for reads only appear if enabled. - Retire the account: disable it, then run step 5 again and see that it fails because the account is disabled.
Expected result.
WARNING: This command is using service account impersonation. All API calls will be executed as [lab-reader@PROJECT_ID.iam.gserviceaccount.com]. ERROR: (gcloud.iam.service-accounts.list) PERMISSION_DENIED: Permission 'iam.serviceAccounts.list' denied on resource (or it may not exist).
Cost. Free. No VM, no keys and no billable resources are created.
Cleanup.
gcloud projects remove-iam-policy-binding PROJECT_ID \ --member="serviceAccount:lab-reader@PROJECT_ID.iam.gserviceaccount.com" \ --role="roles/browser" gcloud iam service-accounts delete lab-reader@PROJECT_ID.iam.gserviceaccount.com
If you plan to run the Module 7 lab, keep the service account until then and only disable it.
Lab 4b (optional): audit your default service accounts
Run gcloud iam service-accounts list and the Editor check from the commands tab on one of your existing projects. If the default Compute Engine service account holds Editor, write down what runs as that account (gcloud compute instances list --format="table(name,serviceAccounts[].email)") before you plan its replacement. Do not remove the role in a shared project without that list.
Real cases
- A key in a repository. A team stored a service account key in a private repository. When the repository was mirrored to a less protected location, the key was exposed and used to read data. The recovery was to delete the key, review audit logs for the account, and move the pipeline to Workload Identity Federation. The organization then enforced
iam.disableServiceAccountKeyCreation. - Everything ran as the default account. Dozens of VMs ran as the Compute Engine default service account with Editor. One compromised web server could change firewall rules. The platform team created a dedicated account per application with narrow roles, set
--service-accountin the VM templates, removed Editor in stages, and enforced the default-grant constraint for new projects. - Escalation through Service Account User. A developer group had
roles/iam.serviceAccountUseron the whole project "to deploy functions". One service account in that project had broad rights; a developer deployed a function that ran as that account and used its access. The fix was to grant Service Account User on each deployment account only, and to keep powerful accounts in a separate project that developers cannot use.
Practices
- One service account per workload and per environment. Name by purpose, document the owner and the consumers.
- Put service accounts in a dedicated project when many workloads share them, so that project-level policies stay clean, and avoid cross-project use unless it is needed (the constraint
iam.disableCrossProjectServiceAccountUsagecontrols this). - Grant Token Creator and Service Account User on the account, not at the project, and use groups or pipeline identities as members.
- Disable and observe before delete. Keep the audit log for at least the period in which an unused workload could run (a month-end job needs more than a week).
- Monitor unused accounts with Policy Intelligence service account insights and clean them up regularly.
Security notes
iam.serviceAccounts.actAs, getAccessToken, signBlob or iam.serviceAccountKeys.create on an account can act as it. In a privilege review, treat those permissions as equal to the account's own roles.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Failed to impersonate | Missing Token Creator on the service account, API disabled, or propagation | gcloud iam service-accounts get-iam-policy SA_EMAIL; gcloud services list --enabled | grep iamcredentials |
Permission 'iam.serviceAccounts.actAs' denied when creating a VM or deploying | Deployer lacks Service Account User on the runtime account | Grant roles/iam.serviceAccountUser on that account |
| Impersonation works but the action is denied | The service account lacks the role for the action | Troubleshooter with --principal-email=SA_EMAIL |
Key creation blocked: Key creation is not allowed on this service account | Constraint iam.disableServiceAccountKeyCreation | gcloud org-policies describe iam.disableServiceAccountKeyCreation --project=PROJECT_ID --effective |
| Default account has Editor again in a new project | The automatic grant constraint is not enforced | gcloud org-policies describe iam.automaticIamGrantsForDefaultServiceAccounts --project=PROJECT_ID --effective |
| Workload fails after recreating a service account with the same name | New unique ID: old bindings no longer match | Look for deleted:serviceAccount:... entries in the policy |
| Cannot attach a service account from another project | Cross-project usage is disabled or missing actAs | Check the constraint and the actAs grant |
Triage order
- Who is the caller (person, pipeline, attached account)? Check
principalEmailand the delegation info in the audit log. - Is the problem "may I use this account" (policy on the account) or "may the account do this" (policy on the target)?
- Is the account enabled, and does the Credentials API work?
- Run the troubleshooter for the account and the permission.
- Check Organization Policy constraints on service accounts.
These are search pages and official documentation, not pinned videos. Check the publication date and the product names.
- YouTube search: service account best practices
- YouTube search: service account impersonation
- YouTube search: default service accounts and the Editor role
Official reading: Service accounts overview · Impersonating service accounts · Best practices for service accounts · Restricting service accounts.
Module 5 · Keyless authentication: Workload Identity Federation
- Explain why a service account key file is a standing credential and how Workload Identity Federation replaces it with short-lived tokens.
- Create a workload identity pool and an OIDC provider with an attribute mapping and an attribute condition that trusts only one repository.
- Grant
roles/iam.workloadIdentityUseron a service account and usegoogle-github-actions/authfrom a GitHub Actions workflow.
The short answer
Workload Identity Federation (工作负载身份联合) lets a workload that runs outside Google Cloud prove who it is with a token from its own identity provider, and exchange that token for a short-lived Google Cloud credential. The most common case in a landing zone is a CI/CD system such as GitHub Actions that deploys Terraform, but the same mechanism serves AWS, Azure, any OIDC or SAML provider, and on-premises systems.
Why it is needed
The traditional way to let an outside system call Google Cloud is to create a service account key (a JSON file) and store it as a secret in the CI system. That key has three properties that make it dangerous:
- It does not expire. By default a user-managed key is valid until it is deleted (you can set an expiry through organization policy on newer setups, but that is rarely the case).
- It can be copied. Anyone who reads the CI secret, a log, a laptop backup or a pull request from a fork can use it from anywhere.
- It cannot be attributed to a person or a run. The audit log only shows the service account, not which pipeline run used it.
Federation removes the stored secret. Every run asks its identity provider for a fresh token that proves "I am this repository, on this branch, in this run". Google verifies the signature, checks your conditions, and returns a credential that expires in minutes to an hour.
How it works internally
- Pool and provider. In a Google Cloud project you create a workload identity pool (工作负载身份池) and, inside it, a provider that describes the external system: for GitHub it is an OIDC provider with the issuer
https://token.actions.githubusercontent.com. Pools and providers are global resources. - Attribute mapping. The provider maps claims from the external token to Google attributes.
google.subjectis required and identifies the external user or workload;attribute.NAMEentries are custom attributes you can use in IAM, for exampleattribute.repository. - Attribute condition. A CEL expression, such as
assertion.repository_owner=='acme'. If it evaluates to false the token is rejected. Always set one; it is the guard that stops tokens from the same issuer that belong to someone else's repository. - Token exchange. The workload sends its external token to the Security Token Service (STS) at
sts.googleapis.com. STS validates the signature against the issuer's published keys, applies the mapping and the condition, and returns a federated access token. - Access. Two options. Direct resource access: grant roles straight to the federated principal (
principal://orprincipalSet://) on the resources it needs. Service account impersonation: grantroles/iam.workloadIdentityUseron a service account to the federated principal, and the workload calls the Service Account Credentials API (iamcredentials.googleapis.com) to get a short-lived token for that service account. Impersonation works with every Google Cloud API; direct access is simpler but not supported by every product, so check the support table for the services you use.
Principal identifiers
| Form | Meaning | Example use |
|---|---|---|
principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECT | One exact external subject (matches google.subject) | One specific GitHub ref or environment |
principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/attribute.repository/ORG/REPO | Every identity whose mapped attribute has this value | All runs of one repository |
principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/* | Every identity in the pool | Rarely correct. Avoid in production. |
Pool principals use the project number, not the project ID. This is one of the most common copy-and-paste mistakes.
When to use it, and when not
- Use it for CI/CD pipelines, for workloads in other clouds, for on-premises services that have an OIDC or SAML identity provider, and as the default for any human-free automation outside Google Cloud.
- Do not use it inside Google Cloud for Compute Engine or Cloud Run: attach a service account to the workload (Module 4) and rely on the metadata server. GKE has its own form of Workload Identity for pods, which uses the same pool concept (
PROJECT_ID.svc.id.goog) but a different setup.
What it is confused with
| Mechanism | Credential lifetime | Secret to store | Typical use |
|---|---|---|---|
| Service account key file | Until deleted | Yes (JSON key) | Legacy integrations. Block with iam.disableServiceAccountKeyCreation (Hour 3). |
Impersonation (--impersonate-service-account) | Short (token lifetime) | No, but the caller needs its own identity | Humans and tools acting as a service account |
| Workload Identity Federation | Short | No | Outside workloads: CI/CD, other clouds, on-premises |
| Attached service account (metadata server) | Short, rotated automatically | No | Workloads running on Google Cloud |
| Workload Identity for GKE | Short | No | Pods on GKE accessing Google Cloud APIs |
Common misunderstandings
repository_owner is weaker than one on one repository.Figure 1. The token exchange. Read it left to right: identity from GitHub, trust decision in the pool, permission decision in IAM, access to the API.
Figure 2. Three controls stack: condition, binding, role. Weakness in any one of them is enough to hand out too much access, so review all three.
Look at the first figure for the order of events, and at the second for the question to ask in every review: "which identities can reach this service account, and what can the account do?"
The player shows one GitHub Actions run obtaining credentials. Step 4 is the trust decision (token validity and condition), step 6 is the permission decision (IAM on the service account). A failure in step 4 gives a "credential rejected" error; a failure in step 6 gives a permission error on iam.serviceAccounts.getAccessToken. Knowing which step failed halves the troubleshooting time.
All commands run in Cloud Shell or a terminal where gcloud is authenticated as an administrator of the identity project. Replace placeholders in uppercase. The APIs iam.googleapis.com, iamcredentials.googleapis.com, sts.googleapis.com and cloudresourcemanager.googleapis.com must be enabled in the project (enabling an API is free).
gcloud services enable (write, free)
Purpose. Enables the APIs that federation needs. Without sts.googleapis.com and iamcredentials.googleapis.com the token exchange fails with an API-disabled error.
gcloud services enable iam.googleapis.com iamcredentials.googleapis.com sts.googleapis.com cloudresourcemanager.googleapis.com --project=PROJECT_ID
Operation "operations/acat.p2-123456789012-aaaa1111-bbbb-2222-cccc-333344445555" finished successfully.
Flags. --project selects the project that will own the pool. Common errors. PERMISSION_DENIED: Permission denied to enable service means you lack serviceusage.services.enable (for example roles/serviceusage.serviceUsageAdmin). Production use. Enable the APIs from Terraform in the project factory, not by hand.
gcloud iam workload-identity-pools create (write, free)
Purpose. Creates the pool that will hold external identities. Pools are global, so the location is always global.
gcloud iam workload-identity-pools create gh-pool \ --project=PROJECT_ID \ --location=global \ --display-name="GitHub Actions pool" \ --description="Trust for CI pipelines in the acme organization"
Created workload identity pool [gh-pool].
Flags. The first positional argument is the pool ID (4 to 32 characters, lowercase letters, digits and hyphens; it cannot start with gcp-). --display-name and --description are for humans. Common errors. ALREADY_EXISTS can appear when a pool with that ID was deleted recently, because deleted pools are kept for a period and the ID stays reserved. Production use. One pool per environment (for example gh-prod and gh-nonprod) keeps the blast radius small and makes revocation a single delete.
gcloud iam workload-identity-pools providers create-oidc (write, free)
Purpose. Creates the OIDC provider for GitHub inside the pool, with the attribute mapping and the condition that restricts the trust.
gcloud iam workload-identity-pools providers create-oidc gh-provider \ --project=PROJECT_ID \ --location=global \ --workload-identity-pool=gh-pool \ --display-name="GitHub OIDC" \ --issuer-uri="https://token.actions.githubusercontent.com" \ --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository,attribute.repository_owner=assertion.repository_owner,attribute.ref=assertion.ref" \ --attribute-condition="assertion.repository_owner=='GITHUB_ORG'"
Created workload identity pool provider [gh-provider].
Flags. --issuer-uri is the exact iss claim of the tokens. --attribute-mapping is a comma-separated list of GOOGLE_ATTRIBUTE=CEL_EXPRESSION; google.subject is mandatory. --attribute-condition is a CEL expression that must be true for a token to be accepted. Check gcloud iam workload-identity-pools providers create-oidc --help for the flags in your SDK version (for example for --allowed-audiences and for --jwk-json-path when the issuer does not publish keys). Common errors. INVALID_ARGUMENT: The attribute condition must reference one of the supported claims usually means a typo in a claim name; INVALID_ARGUMENT on the mapping often means an attribute name that is not google.subject or attribute.NAME. Production use. Keep the mapping and condition in Terraform so a change is reviewed. The mapping must expose every attribute you want to bind on later.
gcloud iam workload-identity-pools providers describe (read, free)
Purpose. Prints the full provider resource name, which is the value the GitHub action needs for workload_identity_provider.
gcloud iam workload-identity-pools providers describe gh-provider \ --project=PROJECT_ID --location=global --workload-identity-pool=gh-pool \ --format="value(name)"
projects/123456789012/locations/global/workloadIdentityPools/gh-pool/providers/gh-provider
IDs in the expected output are illustrative. The number in the path is the project number, not the project ID.
gcloud iam service-accounts add-iam-policy-binding (write, free)
Purpose. Lets identities from the pool impersonate the deployer service account. This is the permission decision (step 6 of the animation).
gcloud iam service-accounts add-iam-policy-binding deployer@PROJECT_ID.iam.gserviceaccount.com \ --project=PROJECT_ID \ --role="roles/iam.workloadIdentityUser" \ --member="principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/gh-pool/attribute.repository/GITHUB_ORG/REPO_NAME"
Updated IAM policy for serviceAccount [deployer@PROJECT_ID.iam.gserviceaccount.com]. bindings: - members: - principalSet://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/gh-pool/attribute.repository/acme/infra role: roles/iam.workloadIdentityUser etag: BwYabc123XYZ= version: 1
Flags. --role and --member add exactly one binding. Common errors. INVALID_ARGUMENT: Identity Pool does not exist means the pool or the project number is wrong. Production use. Bind to attribute.repository (or to a principal:// subject for one environment), never to the whole pool.
gcloud iam workload-identity-pools create-cred-config (read-only file output)
Purpose. Generates a credential configuration file for workloads that are not on GitHub, for example an AWS or an OIDC workload. The file contains no secret, only instructions for obtaining the token. Check gcloud iam workload-identity-pools create-cred-config --help for the flags in your SDK version, because they differ by source (AWS, Azure, file-sourced or URL-sourced tokens).
GitHub Actions workflow
Purpose. The consuming side. The auth action requests the GitHub token, performs the exchange and impersonation, and exports credentials for later steps.
name: terraform-plan
on:
pull_request:
branches: [main]
permissions:
id-token: write # required to request the OIDC token
contents: read
jobs:
plan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- id: auth
uses: google-github-actions/auth@v2
with:
workload_identity_provider: projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/gh-pool/providers/gh-provider
service_account: deployer@PROJECT_ID.iam.gserviceaccount.com
- uses: google-github-actions/setup-gcloud@v2
- run: gcloud auth list
- run: gcloud projects describe PROJECT_ID --format="value(projectId)"
Credentialed Accounts ACTIVE ACCOUNT * deployer@PROJECT_ID.iam.gserviceaccount.com
Notes. Pin actions to a full commit SHA in production workflows, and check the current major version of google-github-actions/auth in its README before you copy this. The action's inputs and outputs are documented there; for Terraform it exports Application Default Credentials so the Google provider picks them up without configuration. Cost. The exchange and token creation are free; the resources the pipeline creates are not.
Lab 5: keyless trust for one repository (about 15 minutes, free)
Goal. Create a pool and OIDC provider for GitHub, bind exactly one repository to a service account, and prove the binding is narrow. The lab does not need a GitHub repository to verify the Google side; the optional step 8 uses one.
Prerequisites. A sandbox project PROJECT_ID with a budget alert already set (Hour 1, Module 3), permission to administer IAM and workload identity pools in it (for example roles/iam.workloadIdentityPoolAdmin and roles/iam.serviceAccountAdmin), and, optionally, a private GitHub repository GITHUB_ORG/REPO_NAME that you control. No secrets are used anywhere in this lab. IDs in the expected output are illustrative.
- Set variables.
export PROJECT_ID=PROJECT_ID export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)") echo $PROJECT_NUMBER
123456789012
- Enable the APIs.
gcloud services enable iam.googleapis.com iamcredentials.googleapis.com sts.googleapis.com cloudresourcemanager.googleapis.com --project=$PROJECT_ID. Verify:gcloud services list --enabled --project=$PROJECT_ID --filter="name:(sts OR iamcredentials)"lists both. - Create the service account.
gcloud iam service-accounts create lab-deployer --project=$PROJECT_ID --display-name="Lab deployer (no keys)". Verify:gcloud iam service-accounts list --project=$PROJECT_IDshowslab-deployer@PROJECT_ID.iam.gserviceaccount.com. - Give it a harmless role so there is something to prove later:
gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:lab-deployer@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/browser". Roles/browser lets it read the project hierarchy only. - Create the pool. Use the pool command from the commands tab with ID
gh-lab-pool. Verify:gcloud iam workload-identity-pools describe gh-lab-pool --project=$PROJECT_ID --location=global --format="value(state)"printsACTIVE. - Create the OIDC provider with the mapping and the condition from the commands tab, using
--attribute-condition="assertion.repository=='GITHUB_ORG/REPO_NAME'"so the provider itself accepts only one repository. Verify with theproviders describecommand; the output must show your condition inattributeCondition:gcloud iam workload-identity-pools providers describe gh-provider --project=$PROJECT_ID --location=global --workload-identity-pool=gh-lab-pool --format="value(attributeCondition)"
assertion.repository=='acme/infra'
- Bind the repository to the service account with
roles/iam.workloadIdentityUser, using theprincipalSet://form withattribute.repository/GITHUB_ORG/REPO_NAMEand the project number. Verify:gcloud iam service-accounts get-iam-policy lab-deployer@$PROJECT_ID.iam.gserviceaccount.com --format="table(bindings.role,bindings.members)"
The members column must show the repository-scoped principalSet, not/*. - Prove the binding is narrow (reading). Run the troubleshooter for a different repository's principal; it must report that the access is not granted. Replace the member with
principalSet://iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/gh-lab-pool/attribute.repository/GITHUB_ORG/OTHER_REPOand check the policy output of step 7 again: this principal does not appear, so it has no path to the account. - (Optional) Test from GitHub. In your private repository add the workflow from the commands tab with your provider name and service account, push it to a branch, and open the run. The
authstep must succeed and thegcloud auth liststep must show the service account. Then change the condition to a different repository name withgcloud iam workload-identity-pools providers update-oidc(check--helpfor flags) and re-run: the auth step must fail with an error about the attribute condition. Restore it afterwards.
Expected result. The pool and provider exist, the service account is impersonable only by the named repository, and (optionally) a run succeeds from that repository and fails from any other.
Cost. Free. Pools, providers, service accounts, IAM bindings and token exchanges do not create metered charges. Budgets send alerts and do not cap spend.
Cleanup.
gcloud iam workload-identity-pools providers delete gh-provider --project=$PROJECT_ID --location=global --workload-identity-pool=gh-lab-pool --quiet gcloud iam workload-identity-pools delete gh-lab-pool --project=$PROJECT_ID --location=global --quiet gcloud projects remove-iam-policy-binding $PROJECT_ID --member="serviceAccount:lab-deployer@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/browser" gcloud iam service-accounts delete lab-deployer@$PROJECT_ID.iam.gserviceaccount.com --quiet
Deleted pools and providers are soft-deleted for a period and can be restored with an undelete command; their IDs stay reserved, so use a new ID if you repeat the lab the same day.
Real cases
- Key files in CI secrets. A platform team found service account keys for Terraform stored in six repositories, three of them more than two years old and one used by a contractor who had left. They created one pool per environment, one service account per Terraform layer, replaced the keys in a week, deleted the keys, and then enabled
iam.disableServiceAccountKeyCreationat the organization so new keys could not return. - Owner-level trust in a pool. A pool bound the whole GitHub organization to a production deployer. A developer created a test repository and its workflow could change production firewall rules. The fix was to bind to a repository (and an environment) and to move the deployer's role from editor to the specific roles required.
- Pull requests from forks. A pipeline used the same service account for
planandapply. The plan job ran on pull requests, including ones from forks, and had write permission. Splitting into a read-only planner (any pull request) and an applier (onlyrefs/heads/mainvia a GitHub environment) closed the path.
Practices
- One service account per layer and per environment: bootstrap, organization, network, project factory, application. Each gets only the roles of its layer.
- Condition and binding both: keep an attribute condition on the provider (organization and repository) and a binding scoped to one repository, and where possible to one branch or environment through
google.subject. - Prefer branch protection plus GitHub environments for apply jobs. The environment name appears in the token
subclaim, so Google can bind to it. - Pin the actions by SHA and review updates; the action runs with your credentials.
- Monitor token exchanges: log entries from
sts.googleapis.comandiamcredentials.googleapis.comshow which subject obtained which service account token.
iam.disableServiceAccountKeyCreation exceptions with a reviewed process.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
unable to get OIDC token or ACTIONS_ID_TOKEN_REQUEST_URL empty in the auth step | Workflow lacks permissions: id-token: write (at the workflow or job level), or the job runs from a fork with restricted tokens | Open the workflow file and the run summary; confirm the permissions block applies to this job |
The given credential is rejected by the attribute condition | The token's claims do not satisfy the provider condition (wrong repository, owner or branch) | Compare attributeCondition from providers describe with the repository in the run; check capitalization |
Permission 'iam.serviceAccounts.getAccessToken' denied | No roles/iam.workloadIdentityUser for this principal on the service account, or the member string is wrong | gcloud iam service-accounts get-iam-policy SA_EMAIL; verify project number and attribute path |
Identity Pool does not exist or The audience ... is invalid | Provider path typo, project ID used where the number is needed, or pool deleted | gcloud iam workload-identity-pools describe POOL --location=global |
API [sts.googleapis.com] not enabled or iamcredentials.googleapis.com disabled | Required APIs are not enabled in the project that hosts the service account | gcloud services list --enabled --filter="name:(sts OR iamcredentials)" |
| Auth succeeds, later step returns 403 | The service account lacks the target permission (federation worked, IAM role is missing) | gcloud policy-troubleshoot iam RESOURCE --principal-email=SA_EMAIL --permission=PERMISSION |
| It worked yesterday and fails today after a repository rename or transfer | Bindings and conditions use the old repository name | Compare the current repository claim in the run with the binding; update both |
Triage order
- Which step failed: token request (GitHub), exchange (STS, trust decision), impersonation (IAM Credentials, permission decision), or the target API?
- Read the exact error text; each stage has a distinct message, as in the table.
- Compare the claims in the token (
repository,ref,sub) with the condition and the member string, character by character. - Check the project number, pool ID and provider ID in the resource name.
- Check that APIs are enabled and that the organization policy does not block federation to that provider type (some organizations restrict external identity providers).
- Use the Policy Troubleshooter for the service account on the target resource if the failure is after authentication.
Official videos change often, so the links below are search pages rather than pinned video links. Check the video date against the version of the documentation you use.
- YouTube search: Workload Identity Federation with GitHub Actions
- YouTube search: service account impersonation and keyless access
Official reading: Workload Identity Federation · Federation with deployment pipelines · google-github-actions/auth.
Module 6 · Groups, privileged access and access reviews
- Design group-based access so that roles are bound to groups and people join or leave through group membership.
- Describe how Privileged Access Manager (PAM) turns standing privileged access into time-limited, justified and audited grants.
- Run an access review with Cloud Asset Inventory, IAM Recommender and the Cloud Audit Logs trail of IAM changes.
The short answer
Three practices keep IAM understandable as a company grows. Group-based access (基于群组的访问): bind roles to groups, never to individual people. Just-in-time privileged access: powerful roles are requested, approved and time-limited instead of held permanently. Access reviews (访问权限审查): on a schedule, someone confirms that every binding and group membership is still needed, using data rather than memory.
Why it is needed
The first IAM policy in a project is easy to read. After two years of joiners, movers and leavers it is not. Typical symptoms are users with Owner on a project they left years ago, service accounts with Editor that nobody remembers creating, contractors whose accounts outlive the contract, and the same role granted five times to five people so that nobody can say why. These are not exotic attacks; they are drift, and the only cure is a structure that makes the right state the default.
How it works
1. Group-based RBAC
- Identities in groups live in Cloud Identity or Google Workspace (Hour 1, Module 4). A group has an email address, such as
gcp-prod-network-admins@example.com. - IAM binds the role to
group:GROUP_EMAIL. Everyone who is a member (directly or through nested groups) receives the role on the resource and everything below it. - A common naming pattern makes the group self-explanatory:
gcp-<scope>-<function>, for examplegcp-org-admins,gcp-network-admins,gcp-prod-viewers,gcp-sandbox-developers. - Groups are an identity object. Anybody who can add members to a privileged group effectively holds that privilege. Restrict who can manage the group and who may join it, and consider disallowing external members.
2. Privileged Access Manager (PAM)
- An entitlement is a policy object created on a project, folder or organization. It states who is eligible to request, which roles (and optional IAM conditions) they receive, the maximum duration, whether a justification is required, and the approval workflow (approvers, number of approvals) and notifications.
- A grant is one request against an entitlement. It moves through states: approval awaited, approved (or denied), active, expired or revoked.
- While a grant is active, PAM adds a temporary role binding for the requester; at the end it removes it. Both events are written to audit logs, together with the justification.
- PAM needs the
privilegedaccessmanager.googleapis.comAPI and has its own roles (for example to create entitlements, to request grants, and to approve). Check the current role names in the documentation before you plan the delegation model.
3. Access reviews and the audit trail
- Cloud Asset Inventory can search and analyse IAM policies across an organization (
gcloud asset search-all-iam-policies,gcloud asset analyze-iam-policy), so you can answer "who has access to this resource" and "what can this identity reach". - IAM Recommender (part of Policy Intelligence) proposes removing or replacing roles based on observed permission use, and Policy Analyzer answers access questions at scale.
- Cloud Audit Logs, specifically Admin Activity logs, record every
SetIamPolicycall: who changed which policy, when and from where. Admin Activity logs cannot be disabled. - The review is a recurring process: export, compare with the approved design, ask owners to confirm, remove what is not confirmed, and keep the evidence.
When to use it
| Situation | Preferred approach |
|---|---|
| Day-to-day read access for a team | A group bound to a predefined viewer role on the folder or project |
| A role that can change network, IAM or billing in production | PAM entitlement with approval, short duration and justification |
| Emergency access when identity is broken | Break-glass accounts (Hour 1), monitored and tested, not PAM |
| Contractors and short projects | A dedicated group with a membership expiry, plus a review date |
| Automation | Service accounts and Workload Identity Federation (Module 5), not user accounts |
What it is confused with
| Mechanism | What it does | Not to be confused with |
|---|---|---|
| IAM Conditions | Adds a rule (time, resource name, tag) to a binding | PAM, which uses conditions internally but adds requests, approvals and a lifecycle |
| PAM | Temporary, requestable and auditable access | Break-glass accounts, which exist for when the normal path is unavailable |
| Google Groups for access | People and group nesting | Google Cloud IAM, which decides what the group may do |
| IAM Recommender | Suggestions from observed use | Policy Troubleshooter, which explains one specific allow or deny |
| Access review | Process with evidence | An audit log, which is only one data source of the process |
Common misunderstandings
Figure 1. Access is a path: person, group, role, resource. Only the first two links change often.
Figure 2. Grant lifecycle. The privilege exists only between "approved" and "expired".
In the first figure look at where the policy stops: it ends at the group. In the second, look at the zone text: the value of PAM comes from removing the permanent role as well as adding the request path.
The player follows one privileged change through Privileged Access Manager. Notice that the engineer's action in step 5 is possible only between the approval (step 4) and the revoke (step 7), and that the audit record in step 6 carries the engineer's identity, not a shared admin account.
Run these as a member of an identity or audit group with read access to the resources. Replace uppercase placeholders. Most commands here are read-only; write commands say so and state their cost.
gcloud identity groups memberships list (read, free)
Purpose. Lists the members of a group, the first step of any access review of a group binding. Requires the Cloud Identity API (cloudidentity.googleapis.com) and permission to read the group.
gcloud identity groups memberships list --group-email=GROUP_EMAIL --format="table(preferredMemberKey.id,roles.name)"
ID NAME ana@example.com MEMBER ben@example.com MEMBER lead@example.com OWNER,MEMBER
Flags. --group-email is the group's address; --format selects the fields. IDs in the expected output are illustrative. Common errors. PERMISSION_DENIED or API cloudidentity.googleapis.com has not been used means the API is not enabled in the quota project or you cannot read the group. Production use. Review membership of every privileged group each quarter and alert on additions to the organization admin groups.
gcloud identity groups memberships add (write, free)
Purpose. Adds a person to a group, which is how access is granted in a group-based model.
gcloud identity groups memberships add --group-email=GROUP_EMAIL --member-email=USER_EMAIL
Check gcloud identity groups memberships add --help for the flags in your SDK version (for example for roles and expiry). Production use. Prefer changing membership from your identity provider or from a reviewed automation, so that every change has a ticket.
gcloud asset search-all-iam-policies (read, free)
Purpose. Searches IAM policies across a scope. Use it to answer "where does this group or user have a binding?" without opening every project.
gcloud asset search-all-iam-policies --scope=organizations/ORG_ID --query="policy:GROUP_EMAIL" --format="table(resource,policy.bindings.role)"
RESOURCE ROLE //cloudresourcemanager.googleapis.com/folders/987654321098 ['roles/viewer'] //cloudresourcemanager.googleapis.com/projects/prj-app-a ['roles/logging.viewer']
Flags. --scope is organizations/ID, folders/ID or projects/ID; --query uses the asset search syntax, where policy:VALUE matches members or roles in the policy. Common errors. Cloud Asset API has not been used means enable cloudasset.googleapis.com; no results can also mean the index is slightly behind. Production use. Run it for each leaver and for each group before decommissioning it.
gcloud asset analyze-iam-policy (read, free)
Purpose. Analyses effective access: what an identity can reach on a resource, including access that comes through groups and inheritance.
gcloud asset analyze-iam-policy --organization=ORG_ID --identity="user:USER_EMAIL" --full-resource-name="//cloudresourcemanager.googleapis.com/projects/PROJECT_ID"
Check gcloud asset analyze-iam-policy --help for the flags in your SDK version; options for expanding groups and roles change the size of the result. Use it for "what can this person reach?" questions during offboarding and reviews.
gcloud recommender recommendations list (read, free)
Purpose. Shows IAM Recommender suggestions for removing or reducing roles on a project.
gcloud recommender recommendations list --project=PROJECT_ID --location=global --recommender=google.iam.policy.Recommender --format="table(name.basename(),stateInfo.state,description)"
ID STATE DESCRIPTION a1b2c3d4-0000-1111-2222-333344445555 ACTIVE Replace the current role with a smaller role
Flags. --recommender names the recommender; --location=global is the location for IAM. Common errors. An empty list means no suggestions or not enough usage history (the recommender looks back about 90 days). Enable recommender.googleapis.com if requested. Production use. Review the output monthly and apply accepted changes through code.
gcloud logging read for IAM changes (read, small ingestion cost already incurred)
Purpose. Reads who changed an IAM policy. Reading Admin Activity logs is free; the logs themselves are always on.
gcloud logging read 'logName="projects/PROJECT_ID/logs/cloudaudit.googleapis.com%2Factivity" AND protoPayload.methodName="SetIamPolicy"' --project=PROJECT_ID --freshness=30d --limit=5 --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.resourceName)"
TIMESTAMP PRINCIPAL_EMAIL RESOURCE_NAME 2026-11-20T09:14:03.112Z ana@example.com projects/PROJECT_ID 2026-11-12T15:40:51.874Z deployer@PROJECT_ID.iam.gserviceaccount.com projects/PROJECT_ID
Flags. --freshness limits the time window; --limit caps rows. In the Admin Activity log the method name for projects is SetIamPolicy, for service accounts it is google.iam.admin.v1.SetIAMPolicy; use a filter on protoPayload.serviceName too when you need one service. Production use. Route these entries to a security sink and alert on changes to privileged roles.
gcloud pam entitlements list and gcloud pam grants create (PAM)
Purpose. Lists the entitlements you can use in a project, and requests a time-limited grant. The grant itself is free; the role gives access to resources that may cost money.
gcloud pam entitlements list --project=PROJECT_ID --location=global gcloud pam grants create --entitlement=ENTITLEMENT_ID --requested-duration=1800s --justification="Incident INC-1234: fix firewall" --project=PROJECT_ID --location=global
Flags. --requested-duration must be less than the entitlement maximum; --justification is stored in the audit trail. PAM commands are newer than most IAM commands, so check gcloud pam --help for the flags in your SDK version, and enable privilegedaccessmanager.googleapis.com first. Production use. Make the justification field point to a ticket, and notify an on-call channel on every grant.
gcloud projects get-iam-policy with a filter (read, free)
Purpose. Finds direct user bindings, the items that an access review wants to move to groups.
gcloud projects get-iam-policy PROJECT_ID --flatten="bindings[].members" --filter="bindings.members:user:" --format="table(bindings.role,bindings.members)"
ROLE MEMBERS roles/editor user:old.contractor@example.com roles/owner user:ana@example.com
Lab 6: run a small access review (about 12 minutes, free)
Goal. Produce a one-page review for one sandbox project: direct user bindings, group memberships behind each group binding, unused-role recommendations and recent IAM changes.
Prerequisites. A sandbox project PROJECT_ID and, if available, an organization ORG_ID. Roles that can read the policy (roles/iam.securityReviewer or roles/viewer plus roles/logging.viewer), and, for the optional steps, Cloud Asset and Recommender viewer access. No secrets are needed. IDs in the expected output are illustrative. A budget alert should already exist.
- Export the policy.
gcloud projects get-iam-policy PROJECT_ID --format=json > policy.json. Verify:grep -c '"role"' policy.jsonprints a number greater than zero. - List direct user bindings. Run the flattened command at the end of the commands tab. Write down each
user:member and its role. These are your move-to-group candidates. - List group bindings.
gcloud projects get-iam-policy PROJECT_ID --flatten="bindings[].members" --filter="bindings.members:group:" --format="table(bindings.role,bindings.members)". For each group, rungcloud identity groups memberships list --group-email=GROUP_EMAILif you can read it. Verify: you can name every member of each group. - Check privileged roles. Filter for
roles/owner,roles/editorand any role withadminin its name:gcloud projects get-iam-policy PROJECT_ID --flatten="bindings[].members" --filter="bindings.role:(roles/owner OR roles/editor)" --format="table(bindings.role,bindings.members)"
Expected: ideally empty or only a break-glass or a deployment service account. - Read recommendations. Run the recommender command from the commands tab. If the list is empty because the project is new, record that and move on.
- Read the audit trail. Run the
gcloud logging readcommand forSetIamPolicyover 30 days. Verify: each change has a named principal, and each of them is expected. - Write decisions. For each finding, record keep, change or remove, an owner and a date. For a sandbox you may change one item: bind a role to a group instead of to a user, then verify with the
get-iam-policyfilter that the user binding is gone and that the group binding exists. Do the add before the remove so that no one loses access in between.
Expected result. A table of findings with decisions and at least one verified change. Typical findings in a lab project are a direct user binding, an Editor role on a service account, and an Owner binding without an expiry.
Cost. Free; all calls are metadata reads. Large organizations can see quota errors on Cloud Asset queries; slow down and filter by scope.
Cleanup. Delete policy.json (it can contain real email addresses). If you changed a binding for the exercise, restore it from the exported file or record the final state in the review.
roles/viewer with a 30-minute maximum, request a grant with a justification, and confirm in the audit log that the binding appears and then disappears. Check gcloud pam --help for the flags in your SDK version.Real cases
- Offboarding by group. A company moved all project roles to about 40 functional groups, tied group membership to its identity provider, and removed direct user bindings with a Terraform check in the pipeline. A leaver now loses all Google Cloud access when the account is suspended, and the quarterly review dropped from days to hours.
- Standing network admins. Twelve engineers had Network Admin on production all year but needed it a few times a quarter. The team moved the role to an approval-based entitlement with a 2-hour maximum and a ticket reference in the justification. After the change the number of people holding the role at any moment was typically zero, and the audit log gave a short list of reasons.
- The group nobody owned. A group named for a project had owner-level rights, and anyone in the company could join it. A review that listed group bindings and then group settings found it. The fix was to restrict who can join, name an owner, and enforce domain restrictions on membership.
Practices
- Bind roles to groups at the lowest level that fits the job, normally a folder, and name groups by scope and function.
- Use one group per role set; do not create "all-in-one" groups for convenience.
- Remove standing Owner, Editor and organization-level administration from people. Keep a documented, monitored break-glass path.
- Review privileged groups monthly and the rest quarterly; keep the review output as evidence.
- Send IAM change events to the logging project and alert on changes to the policies of the organization, the billing account and the groups themselves.
roles/owner to a group as a shortcut; use predefined roles for the function.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
A user was added to a group but still gets PERMISSION_DENIED | Membership propagation delay, or the binding is on a different resource or role | Wait a few minutes, then run the Policy Troubleshooter for the user and permission |
| A group binding exists, but the user is not granted | The user is a member of a nested group that is not allowed, or the membership is pending or disabled | gcloud identity groups memberships list --group-email=GROUP_EMAIL |
| PAM grant stays in "approval awaited" | No approver notified, wrong approver group, or approvers were not allowed to approve | Describe the entitlement and check approval workflow and approver principals |
| PAM grant is active but the user is still denied | Propagation delay, or a deny policy or condition blocks the action | Policy Troubleshooter with the exact permission and resource |
| Recommender returns nothing | Project too new, API not enabled, or no data for the period | Check API and project age; repeat later |
search-all-iam-policies returns an empty list for a known binding | Wrong scope, missing cloudasset.assets.searchAllIamPolicies permission, or index delay | Check scope and permission; run gcloud projects get-iam-policy to confirm |
| Cannot see the change that removed a role | Admin Activity log read in the wrong project or with the wrong log name | Use the log name of the project where the policy lives, or the organization or folder name |
Triage order
- Is the principal in the group right now (membership state and type)?
- Is the group bound to the role on a resource that is an ancestor of the target?
- Is the PAM grant in state active, and for which role and condition?
- Is anything denying the action (deny policy, Organization Policy, VPC Service Controls)?
- Is the audit log showing who changed the policy last?
Official videos change often, so the links below are search pages rather than pinned video links. Check the video date against the version of the documentation you use.
- YouTube search: Google Cloud Privileged Access Manager
- YouTube search: IAM Recommender and least privilege
- YouTube search: Cloud Asset Inventory and Policy Analyzer
Official reading: Using IAM securely · IAM Recommender overview · IAM audit logging.
Module 7 · Lab: least-privilege platform team
- Create a custom role with only the permissions a platform task needs, and bind it to a group and to a service account.
- Test access by impersonating the service account, and show one allowed call and one denied call.
- Explain a result with
gcloud policy-troubleshoot iam, then remove every resource and binding in the right order.
What this lab proves
The first five modules explained the pieces: the IAM model, role types, inheritance and conditions, service accounts, federation, groups. This lab puts them together in a sandbox in about ten minutes of focused work, in the way a platform team does for a real layer: a group that humans join, a custom role that holds exactly the permissions of the task, a service account that automation uses, and a test that shows what is not allowed.
Design of the lab
| Element | Choice | Why |
|---|---|---|
| Scope | One sandbox project PROJECT_ID | No organization permissions needed; deletion is easy |
| Role | Custom role platformNetViewer with compute.networks.get, compute.networks.list, compute.subnetworks.get, compute.subnetworks.list | The task is "inspect network configuration", which does not need write or instance permissions |
| Human access | The group GROUP_EMAIL gets the custom role | Group-based access (Module 6) |
| Automation | Service account lab-netview gets the same role | Pipelines act as a service account, not as a person (Module 4) |
| Test method | Impersonation with --impersonate-service-account | Proves the account's permissions without a key file |
| Proof | One allowed call, one denied call, one troubleshooter result | Evidence, not belief |
Expected results matrix
Action as lab-netview | Permission | Expected |
|---|---|---|
gcloud compute networks list | compute.networks.list | Allowed |
gcloud compute networks subnets list | compute.subnetworks.list | Allowed |
gcloud compute instances list | compute.instances.list | Denied (403) |
gcloud compute networks create demo | compute.networks.create | Denied (403) |
gcloud storage buckets list | storage.buckets.list | Denied (403) |
Where people go wrong
Concepts revisited, as decisions
- Predefined or custom? Use a predefined role when one fits. This lab uses custom because the predefined viewer roles for Compute contain many more permissions (instances, disks, firewalls) than the task needs.
- Which scope? The project, since this is a sandbox. A real platform team would bind at the folder that holds the environment, and would put the custom role definition in the organization so that every project can refer to it.
- Which stage? New custom roles start at
GAin most examples; useALPHAorBETAonly to signal that you are still testing, andDISABLEDto turn off a role without deleting it.
Figure 1. The pieces of the lab. The group can act as the service account only because of the token creator binding on that account.
Figure 2. How to read each test result: compare it to the expectation first, and troubleshoot only when it differs.
In the first figure find the two arrows that reach the project. They are the only grants to resources. In the second figure the unexpected allow is the dangerous case, which is why the matrix includes denied calls.
The animation follows the lab from role creation to the troubleshooter. Steps 4 and 5 are the pair that matter: the same service account, the same token, one allowed call and one denied call. The difference is only the permission list of the role.
These are the commands used by the lab, grouped by the step in which they are used, with expected output. Run them in order in Cloud Shell. IDs in the expected output are illustrative.
gcloud services enable (write, free)
Purpose. Enables the APIs the lab uses: IAM, IAM Credentials (for tokens), Resource Manager, Compute Engine (only to list networks), and Policy Troubleshooter. Enabling an API is a metadata change and free; the Compute API creates no resource.
gcloud services enable iam.googleapis.com iamcredentials.googleapis.com cloudresourcemanager.googleapis.com compute.googleapis.com policytroubleshooter.googleapis.com --project=PROJECT_ID
Operation "operations/acat.p2-123456789012-0a1b2c3d-1111-2222-3333-444455556666" finished successfully.
Common errors. Billing must be enabled for Compute: link the sandbox project to the billing account first. Production use. The project factory enables the APIs.
gcloud iam roles create (write, free)
Purpose. Creates the custom role in the project.
gcloud iam roles create platformNetViewer --project=PROJECT_ID \ --title="Platform network viewer" \ --description="Read-only view of VPC networks and subnets" \ --permissions=compute.networks.get,compute.networks.list,compute.subnetworks.get,compute.subnetworks.list \ --stage=GA
Created role [platformNetViewer]. description: Read-only view of VPC networks and subnets etag: BwYabc123XYZ= includedPermissions: - compute.networks.get - compute.networks.list - compute.subnetworks.get - compute.subnetworks.list name: projects/PROJECT_ID/roles/platformNetViewer stage: GA title: Platform network viewer
Flags. The role ID is positional (letters, digits, underscores and dots); --permissions is a comma-separated list; --stage is the lifecycle stage. Check gcloud iam roles create --help for the flags in your SDK version (for example --file to load a YAML definition). Common errors. INVALID_ARGUMENT: Permission X is not valid means a typo or a permission that cannot be used in custom roles. Production use. Define custom roles in Terraform and keep the YAML or HCL in version control.
gcloud iam service-accounts create (write, free)
gcloud iam service-accounts create lab-netview --project=PROJECT_ID --display-name="Lab network viewer"
Created service account [lab-netview].
Purpose. Creates the identity for automation. The ID is 6 to 30 characters. Production use. Create one per layer or function, and never create a key for it.
gcloud projects add-iam-policy-binding (write, free)
Purpose. Adds the custom role to the service account and to the group on the project. Run it twice, once per member.
gcloud projects add-iam-policy-binding PROJECT_ID \ --member="serviceAccount:lab-netview@PROJECT_ID.iam.gserviceaccount.com" \ --role="projects/PROJECT_ID/roles/platformNetViewer" --condition=None gcloud projects add-iam-policy-binding PROJECT_ID \ --member="group:GROUP_EMAIL" \ --role="projects/PROJECT_ID/roles/platformNetViewer" --condition=None
Updated IAM policy for project [PROJECT_ID]. bindings: - members: - group:GROUP_EMAIL - serviceAccount:lab-netview@PROJECT_ID.iam.gserviceaccount.com role: projects/PROJECT_ID/roles/platformNetViewer etag: BwYabc456DEF= version: 1
Flags. A custom role is referenced by its full name projects/PROJECT_ID/roles/ROLE_ID. --condition=None states that the binding has no condition, and avoids the interactive prompt on policies that already contain conditional bindings. Common errors. INVALID_ARGUMENT: ... group:GROUP_EMAIL does not exist when the group address is wrong, or Policy members ... domain restricted when iam.allowedPolicyMemberDomains blocks the domain.
gcloud iam service-accounts add-iam-policy-binding (write, free)
Purpose. Lets the group impersonate the service account.
gcloud iam service-accounts add-iam-policy-binding lab-netview@PROJECT_ID.iam.gserviceaccount.com \ --project=PROJECT_ID \ --member="group:GROUP_EMAIL" \ --role="roles/iam.serviceAccountTokenCreator"
gcloud compute networks list --impersonate-service-account (read, free)
Purpose. The allowed call, executed as the service account.
gcloud compute networks list --project=PROJECT_ID --impersonate-service-account=lab-netview@PROJECT_ID.iam.gserviceaccount.com
WARNING: This command is using service account impersonation. All API calls will be executed as [lab-netview@PROJECT_ID.iam.gserviceaccount.com]. NAME SUBNET_MODE BGP_ROUTING_MODE IPV4_RANGE GATEWAY_IPV4 default AUTO REGIONAL
An empty project prints Listed 0 items., which is also a success.
gcloud compute instances list --impersonate-service-account (read, free)
Purpose. The denied call. The expected error is the proof.
gcloud compute instances list --project=PROJECT_ID --impersonate-service-account=lab-netview@PROJECT_ID.iam.gserviceaccount.com
ERROR: (gcloud.compute.instances.list) Some requests did not succeed: - Required 'compute.instances.list' permission for 'projects/PROJECT_ID'
gcloud policy-troubleshoot iam (read, free)
Purpose. Explains the decision for one principal, one permission and one resource.
gcloud policy-troubleshoot iam //cloudresourcemanager.googleapis.com/projects/PROJECT_ID \ --principal-email=lab-netview@PROJECT_ID.iam.gserviceaccount.com \ --permission=compute.instances.list
access: NOT_GRANTED explainedPolicies: - access: NOT_GRANTED fullResourceName: //cloudresourcemanager.googleapis.com/projects/PROJECT_ID policy: (allow policy of the project, bindings listed) ...
Flags. The positional argument is the full resource name; --principal-email and --permission are required. Check gcloud policy-troubleshoot iam --help for the flags in your SDK version (for example for conditions context). The output is shortened here. Common errors. API policytroubleshooter.googleapis.com has not been used: enable it. Production use. Put this command in the runbook for every "permission denied" ticket (Module 8).
Lab 7: least-privilege platform team (10 minutes, free)
Goal. Build and test the model in the diagrams tab, with one allowed and one denied call, and remove everything afterwards.
Prerequisites.
- A sandbox project
PROJECT_IDlinked to a billing account that has a budget alert (Hour 1). Budgets send alerts and do not cap spend. - Permission to administer IAM in the project (for example
roles/resourcemanager.projectIamAdmin,roles/iam.roleAdmin,roles/iam.serviceAccountAdmin,roles/serviceusage.serviceUsageAdmin) or the Owner role in the sandbox. - A group
GROUP_EMAILthat you can add yourself to and that your organization policy allows. If you have no group, useuser:USER_EMAIL(your own address) wherever the lab saysgroup:GROUP_EMAIL; the model is the same. - No secrets, and no key files. IDs in the expected output are illustrative.
- Set the context.
export PROJECT_ID=PROJECT_ID gcloud config set project $PROJECT_ID gcloud billing projects describe $PROJECT_ID --format="value(billingEnabled)"
True
Verify: the last command printsTrue. If it printsFalse, link billing before you continue. - Enable the APIs with the
gcloud services enablecommand of the previous tab. Verify:gcloud services list --enabled --filter="name:(iam OR iamcredentials OR compute OR policytroubleshooter)" --format="value(name)"lists the four services. - Create the custom role
platformNetViewer. Verify:gcloud iam roles describe platformNetViewer --project=$PROJECT_ID --format="value(includedPermissions)"
compute.networks.get;compute.networks.list;compute.subnetworks.get;compute.subnetworks.list
- Create the service account
lab-netview. Verify:gcloud iam service-accounts describe lab-netview@$PROJECT_ID.iam.gserviceaccount.com --format="value(email,disabled)"prints the email and nothing for disabled (not disabled). - Bind the custom role to the service account and to the group (two
add-iam-policy-bindingcommands). Verify:gcloud projects get-iam-policy $PROJECT_ID --flatten="bindings[].members" --filter="bindings.role:platformNetViewer" --format="table(bindings.role,bindings.members)"
Both members must appear with the custom role. - Allow the group to impersonate the service account with
roles/iam.serviceAccountTokenCreatoron the account. Verify:gcloud iam service-accounts get-iam-policy lab-netview@$PROJECT_ID.iam.gserviceaccount.comlists the group with that role. Wait one minute for propagation. - Allowed call. Run
gcloud compute networks list --impersonate-service-account=...(see the commands tab). Expected: the warning about impersonation and a table, orListed 0 items.. - Subnet call.
gcloud compute networks subnets list --impersonate-service-account=.... Expected: allowed (maybe a long default list). This confirms the second pair of permissions. - Denied call. Run
gcloud compute instances list --impersonate-service-account=.... Expected:Required 'compute.instances.list' permission for 'projects/PROJECT_ID'. If you see a list instead, the account has a broader role from somewhere; go to step 10 and find it. - Explain it. Run the
gcloud policy-troubleshoot iamcommand forcompute.instances.listand then forcompute.networks.list. Expected:NOT_GRANTEDfor the first andGRANTEDfor the second, the latter naming the binding withplatformNetViewer. - Optional: a human test. Add yourself to the group (or use your own user). Wait a minute. Run
gcloud compute networks listwithout impersonation from an account that has only this role. If you are Owner, you will see allowed calls for everything, which is why the service account test is the real proof.
Expected result. Networks and subnets are listed as the service account; instances are denied; the troubleshooter agrees with the observed results.
Cost. Free. Metadata operations only; no Compute resources are created. The default network (if present) is not billed.
Cleanup (in this order).
gcloud iam service-accounts remove-iam-policy-binding lab-netview@$PROJECT_ID.iam.gserviceaccount.com --member="group:GROUP_EMAIL" --role="roles/iam.serviceAccountTokenCreator" gcloud projects remove-iam-policy-binding $PROJECT_ID --member="group:GROUP_EMAIL" --role="projects/$PROJECT_ID/roles/platformNetViewer" --condition=None gcloud projects remove-iam-policy-binding $PROJECT_ID --member="serviceAccount:lab-netview@$PROJECT_ID.iam.gserviceaccount.com" --role="projects/$PROJECT_ID/roles/platformNetViewer" --condition=None gcloud iam service-accounts delete lab-netview@$PROJECT_ID.iam.gserviceaccount.com --quiet gcloud iam roles delete platformNetViewer --project=$PROJECT_ID --quiet
Verify: gcloud iam roles list --project=$PROJECT_ID --show-deleted --format="value(name,deleted)" shows the role as deleted, and the project policy no longer shows the group or the account. Deleted custom roles are kept for a limited time and can be undeleted, so use a new role ID if you repeat the lab immediately. Check gcloud iam roles delete --help for the behavior in your SDK version.
Challenge (optional, 5 extra minutes)
Add a conditional binding that expires: bind roles/viewer to the group with --condition="expression=request.time < timestamp('2027-01-01T00:00:00Z'),title=lab-expiry". Check the policy with --format=json and note the condition and the policy version 3. Remove it afterwards with the same condition flag. Check gcloud projects add-iam-policy-binding --help for the condition flag format in your SDK version.
Real cases
- Platform roles per layer. A team that owns the network layer defined three custom roles at the organization: a viewer (the permissions in this lab, plus firewall reads), an operator (change routes and firewall rules in one folder), and an administrator (create Shared VPC attachments). Humans receive the viewer through a group and the operator through a time-limited PAM grant. The pipeline service account holds the operator role only inside the folder.
- Custom role drift. A custom role created in 2022 stopped working for a new service feature because Google added the permissions to predefined roles but custom roles do not receive them automatically. A monthly check of recommendations and a Terraform test that calls each documented task as the pipeline account caught the gap.
- Testing with the wrong account. A team announced "the new role works" after testing as an Owner. The service account failed in production. They changed the acceptance test: every access change must include at least one allowed and one denied call as the target principal, with the output attached to the pull request.
Practices
- Write the expected-results matrix before you grant anything, and keep it next to the Terraform code.
- Keep custom roles small and named by function; keep their count low, because each one must be maintained.
- Limit who may create custom roles and who may edit them, since a role change affects every binding that uses it.
- Do not bind custom roles at the organization unless they are meant for the whole organization. Scope tightly: folder or project.
- Test impersonation paths: the caller needs token creator rights on the service account, and those rights are themselves privileged.
roles/iam.serviceAccountTokenCreator on a powerful service account is equivalent to holding that account's power; bind it only to groups that are already trusted for that power. (2) Never create a key to test a permission; use impersonation. (3) Do not use roles/iam.serviceAccountUser as a substitute: it allows attaching the service account to resources, which is a different action. (4) Clean up after labs; leftover bindings in sandbox projects become tomorrow's findings.Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
Permission 'iam.serviceAccounts.getAccessToken' denied on the first impersonated call | The caller lacks token creator on the service account, or the binding has not propagated | gcloud iam service-accounts get-iam-policy SA_EMAIL; retry after a minute |
API [iamcredentials.googleapis.com] not enabled | IAM Credentials API not enabled in the project | gcloud services enable iamcredentials.googleapis.com |
compute.networks.list is also denied for the service account | The role binding missed the service account, or the member string is wrong (for example user: instead of serviceAccount:) | The flattened get-iam-policy command from step 5 |
compute.instances.list is unexpectedly allowed | A broader role, for example roles/editor, granted to the account directly or inherited from a folder | gcloud policy-troubleshoot iam and look at the bindings listed under it |
Role ... not found or INVALID_ARGUMENT when binding the custom role | Short role ID used instead of projects/PROJECT_ID/roles/ROLE_ID | gcloud iam roles list --project=PROJECT_ID |
Compute Engine API has not been used or billing required | Compute API not enabled, or the project has no billing account | gcloud billing projects describe PROJECT_ID |
Cannot re-create platformNetViewer after cleanup | Deleted role ID is reserved for a period | Use a new ID, or undelete the role |
Triage order
- Which principal is actually making the call (look for the impersonation warning)?
- Does that principal have a binding with the permission, on the project or an ancestor?
- Does the caller have token creator on the service account?
- Is the API enabled and billing linked?
- Wait one minute; run the troubleshooter; then read the audit log entry for the denied call.
Official videos change often, so the links below are search pages rather than pinned video links. Check the video date against the version of the documentation you use.
- YouTube search: IAM custom roles with gcloud
- YouTube search: Policy Troubleshooter for permission denied
- YouTube search: service account impersonation with gcloud
Official reading: Create and manage custom roles · Service account impersonation · Policy Troubleshooter.
Module 8 · Troubleshooting "permission denied"
- Apply a fixed triage order to any
PERMISSION_DENIEDor 403 error instead of guessing at roles. - Tell apart the six usual causes: wrong principal, missing permission or scope, deny policy, API not enabled, expired condition and propagation delay.
- Use
gcloud policy-troubleshoot iam,gcloud projects get-iam-policyandgcloud logging readto prove the cause before changing IAM.
The short answer
A PERMISSION_DENIED (HTTP 403) error means Google Cloud received the request, knew who sent it, and decided that it was not allowed. It rarely means that "IAM is broken". The cause is almost always one of six, and each has a check that takes under a minute. This module gives the order to run them in, so you stop adding roles at random.
Why it is needed
In an organization with a landing zone, access passes through several layers: identity, IAM allow policies with inheritance, IAM conditions, deny policies, API enablement, Organization Policy and VPC Service Controls. A single "denied" message can come from any of them, and the quick fix (adding Editor) hides the cause and weakens the design. A fixed order of checks keeps incidents short and keeps privileges small.
How the decision is made
- Authentication. Who is the caller? An end user, a service account, an impersonated service account, a federated principal? If this step fails you see 401 or "invalid credentials", not 403.
- API and service state. Is the API enabled in the project that receives the request? If not:
SERVICE_DISABLED(the error text says "has not been used in project ... before or it is disabled"). - Deny policies. IAM deny policies, attached to the organization, folders or projects, are evaluated first. A matching deny stops the request, whatever the allow policy says.
- Allow policies. The policy on the resource and on every ancestor is combined (union). The caller needs at least one binding that includes the permission, through a role, for a member that matches the caller, whose condition (if any) is true.
- Other controls. Organization Policy constraints, VPC Service Controls perimeters and product-specific controls can also stop a request. They produce different error messages (for example
FAILED_PRECONDITIONwith a constraint name, or "Request is prohibited by organization's policy" with a VPC-SC identifier), which is a useful clue.
The six usual causes
| # | Cause | Typical clue in the error or the policy | Fix |
|---|---|---|---|
| 1 | Wrong principal: the call is made as a different account than you think | gcloud auth list shows another ACTIVE account; an --impersonate-service-account flag or config is set; ADC differs from gcloud login | Switch account, unset impersonation, or fix the pipeline identity |
| 2 | Missing permission or wrong scope | The error names the permission; the role is bound on a sibling project, or on a resource that is not an ancestor | Bind a suitable role on the right resource or ancestor |
| 3 | Wrong principal type in the binding | Binding uses user: for a service account or group, a typo in the email, or a group the user is not in | Correct the member prefix (user:, group:, serviceAccount:, principalSet:) and the address |
| 4 | Deny policy | The binding exists, but the Troubleshooter reports a deny; or the error mentions a deny policy | Review the deny rule and its exceptions; change it through the owner of the policy |
| 5 | API not enabled | SERVICE_DISABLED or "has not been used in project N before or it is disabled" | Enable the API in the correct (quota) project |
| 6 | Expired or unmet condition | Binding contains a condition with a past request.time, or a resource-name or tag condition that does not match | Renew, correct or remove the condition deliberately |
| + | Propagation delay | The change is minutes old, and the first call fails, a later call works | Wait and retry; do not add roles |
When to stop guessing and prove it
Use gcloud policy-troubleshoot iam as soon as you know three things: the principal, the permission and the resource. It reads the policies for you and reports granted or not granted, with the bindings it considered. Use the audit log to find the exact permission and caller when the user can only tell you "it says denied".
What it is confused with
| Error | Looks like | Really means |
|---|---|---|
SERVICE_DISABLED or "API has not been used" | Permission denied | Enable the API in the project |
FAILED_PRECONDITION mentioning constraints/... | Permission denied | Organization Policy blocks the operation, even for Owner (Hour 3) |
"Request is prohibited by organization's policy" with vpcServiceControlsUniqueIdentifier | Permission denied | VPC Service Controls perimeter (Hour 3) |
NOT_FOUND or "or it may not exist" | Resource missing | Can also mean the caller cannot see the resource at all; check permissions to get it |
401 UNAUTHENTICATED or "invalid_grant" | Denied | Credentials expired or invalid; log in again or fix federation (Module 5) |
RESOURCE_EXHAUSTED or 429 | Denied | Quota or rate limit; unrelated to IAM |
Common misunderstandings
Figure 1. The triage order. Steps 1 to 3 are about the request, steps 4 to 6 are about policies, step 7 is other guardrails and step 8 is time.
Figure 2. Evaluation in one line: no matching deny, and at least one matching allow with a true condition.
Read the first figure top to bottom as a checklist. In the second, notice that the deny box comes first and that a role visible in the allow policy is not proof of access.
The player follows one denied request. Step 2 is the deny-policy check, step 3 the allow-policy check and step 4 the error the user sees. Steps 5 to 7 are the investigation: the denial is recorded, you find it, and the Troubleshooter explains it. Practice naming which step produced each error message.
All commands are read-only and free unless marked. Replace uppercase placeholders. IDs in the expected output are illustrative.
gcloud auth list and gcloud config list (read, free)
Purpose. Step 1: shows the active account and the project and impersonation settings. Many denials end here.
gcloud auth list gcloud config list
Credentialed Accounts
ACTIVE ACCOUNT
* ana@example.com
deployer@PROJECT_ID.iam.gserviceaccount.com
[auth]
impersonate_service_account = deployer@PROJECT_ID.iam.gserviceaccount.com
[core]
account = ana@example.com
project = PROJECT_ID
Flags. gcloud config list shows only properties that are set. If impersonate_service_account appears, every command runs as that service account. Unset it with gcloud config unset auth/impersonate_service_account. Common errors. Application Default Credentials (used by Terraform and client libraries) are separate from the gcloud login; check them with gcloud auth application-default print-access-token only on a trusted terminal and never paste the token anywhere. Production use. Print the identity at the start of every CI job.
gcloud policy-troubleshoot iam (read, free)
Purpose. Steps 4 to 6: tells you whether a principal has a permission on a resource and why.
gcloud policy-troubleshoot iam //cloudresourcemanager.googleapis.com/projects/PROJECT_ID \ --principal-email=ana@example.com \ --permission=compute.instances.list
access: NOT_GRANTED explainedPolicies: - access: NOT_GRANTED fullResourceName: //cloudresourcemanager.googleapis.com/projects/PROJECT_ID ...
Flags. The positional value is the full resource name. Check gcloud policy-troubleshoot iam --help for the flags in your SDK version. Common errors. PERMISSION_DENIED on the troubleshooter itself means you need roles/iam.securityReviewer or the equivalent permission on the resource. The output shortens in this module. Production use. Make this the first command in a runbook, and attach its output to access tickets.
gcloud projects get-iam-policy with filters (read, free)
Purpose. Step 4: show the bindings for one principal, including conditions.
gcloud projects get-iam-policy PROJECT_ID --flatten="bindings[].members" \ --filter="bindings.members:ana@example.com" \ --format="table(bindings.role,bindings.members,bindings.condition.title,bindings.condition.expression)"
ROLE MEMBERS TITLE EXPRESSION
roles/compute.viewer user:ana@example.com temp-access request.time < timestamp("2026-11-01T00:00:00Z")
Flags. --flatten turns each member into a row, so you can filter by member. Note. This shows only the project's own policy. Inherited bindings come from gcloud resource-manager folders get-iam-policy FOLDER_ID and gcloud organizations get-iam-policy ORG_ID. The troubleshooter combines all of them.
gcloud services list --enabled (read, free)
Purpose. Step 3: confirm that an API is enabled.
gcloud services list --enabled --project=PROJECT_ID --filter="name:compute.googleapis.com" --format="value(name)"
compute.googleapis.com
An empty result means the API is not enabled in that project. Enabling is free and needs serviceusage.services.enable: gcloud services enable compute.googleapis.com --project=PROJECT_ID. Common errors. Mind the project number in the message: with Terraform and client libraries the quota project may be a different project than you expect (look for user_project_override and billing_project in the provider configuration).
gcloud logging read for denied calls (read, free to read)
Purpose. Finds the exact permission and caller of denied requests.
gcloud logging read 'protoPayload.status.code=7' --project=PROJECT_ID --freshness=1h --limit=5 \ --format="table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.methodName,protoPayload.authorizationInfo[0].permission)"
TIMESTAMP PRINCIPAL_EMAIL METHOD_NAME PERMISSION 2026-11-25T10:21:44.120Z ana@example.com v1.compute.instances.aggregatedList compute.instances.list
Flags. Status code 7 is PERMISSION_DENIED. --freshness limits the search window. Which log type holds a denied call depends on the service and the kind of operation (administrative changes, data access and policy-denied entries are separate logs), and data-access logs may need to be enabled, so an empty result does not prove there was no denial. Check the Audit Logs documentation for the service. Production use. Create a log-based alert on spikes of status code 7 for one principal; it is a good early sign of a broken pipeline or of probing.
gcloud iam policies list for deny policies (read, free)
Purpose. Step 6: lists deny policies attached to a project (also folders and the organization).
gcloud iam policies list --kind=denypolicies --attachment-point=cloudresourcemanager.googleapis.com/projects/PROJECT_ID
Check gcloud iam policies list --help for the flags in your SDK version; the attachment point format must follow the documented form for the resource type. Run the same command with the folder and organization attachment points to see inherited denies. An empty result means no deny policy is attached at that level.
gcloud org-policies describe --effective (read, free)
Purpose. Step 7: shows the effective Organization Policy when the error mentions a constraint.
gcloud org-policies describe constraints/iam.allowedPolicyMemberDomains --project=PROJECT_ID --effective
Lab 8: break it, then find it (about 10 minutes, free)
Goal. Create three realistic denials on purpose (missing permission, API disabled, expired condition), and diagnose each with the triage order, before fixing it.
Prerequisites. A sandbox project PROJECT_ID with a budget alert, and rights to administer IAM and enable or disable APIs there. A user account that is not Owner is ideal; otherwise test as an impersonated service account, as in this lab. The Pub/Sub API must not be enabled yet (check in step 2); the lab enables it and disables it again, which is free. No secrets are used. IDs in the expected output are illustrative.
- Create a test identity.
export PROJECT_ID=PROJECT_ID gcloud iam service-accounts create ts-lab --project=$PROJECT_ID --display-name="Troubleshooting lab" gcloud iam service-accounts add-iam-policy-binding ts-lab@$PROJECT_ID.iam.gserviceaccount.com --member="user:USER_EMAIL" --role="roles/iam.serviceAccountTokenCreator"
Verify:gcloud iam service-accounts list --project=$PROJECT_ID --filter="email:ts-lab"shows the account. Wait one minute. - Check that the API is off.
gcloud services list --enabled --project=$PROJECT_ID --filter="name:pubsub.googleapis.com" --format="value(name)"must print nothing. If it prints the name, stop and pick another API your sandbox has not enabled. - Failure 1: missing permission. Run as the service account:
gcloud pubsub topics list --project=$PROJECT_ID --impersonate-service-account=ts-lab@$PROJECT_ID.iam.gserviceaccount.com
Expected: an error. It may be aSERVICE_DISABLEDmessage (the API check can come before IAM) orPERMISSION_DENIEDnamingpubsub.topics.list. Note which one you get; both are valid lessons. Then run the troubleshooter forpubsub.topics.listand the service account:NOT_GRANTED. - Fix the permission only.
gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:ts-lab@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/pubsub.viewer" --condition=None. Wait two minutes. Rerun the troubleshooter:GRANTED. Rerun the list command. - Failure 2: API disabled. The list command still fails, now clearly with
SERVICE_DISABLEDand the API name in the text, even though the permission is granted. Verify: the troubleshooter says GRANTED while the call fails. That contrast is the lesson: roles do not enable APIs. - Fix the API.
gcloud services enable pubsub.googleapis.com --project=$PROJECT_ID. Rerun the list command. Expected:Listed 0 items.. - Failure 3: expired condition. Replace the binding with a conditional one that has already expired:
gcloud projects remove-iam-policy-binding $PROJECT_ID --member="serviceAccount:ts-lab@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/pubsub.viewer" --condition=None gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:ts-lab@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/pubsub.viewer" --condition="expression=request.time < timestamp('2020-01-01T00:00:00Z'),title=expired-lab"Wait two minutes and run the list command. Expected: permission denied. Look at the binding with theget-iam-policyfilter command: the binding is present. Run the troubleshooter: it reports not granted because the condition is false. If your organization rejects a past timestamp, skip to step 9. - Find it in the log. Run the
gcloud logging read 'protoPayload.status.code=7' --freshness=1hcommand. Verify that you can see the denied calls, the principal (the service account) and the permission. If the list is empty, data-access logging may be off for this service; record that as a limitation. - Write the runbook. For each failure write: error text, which triage step found it, the command that proved it, and the fix. This is the content of your team's first permission-denied runbook.
Expected result. Three recorded failures, each with a proof command, and a green call at the end of step 6.
Cost. Free: only metadata operations and an enabled API that holds no resources. Budgets send alerts and do not cap spend.
Cleanup.
gcloud projects remove-iam-policy-binding $PROJECT_ID --member="serviceAccount:ts-lab@$PROJECT_ID.iam.gserviceaccount.com" --role="roles/pubsub.viewer" --condition="expression=request.time < timestamp('2020-01-01T00:00:00Z'),title=expired-lab"
gcloud services disable pubsub.googleapis.com --project=$PROJECT_ID
gcloud iam service-accounts delete ts-lab@$PROJECT_ID.iam.gserviceaccount.com --quiet
Verify that the policy no longer lists the account, and that gcloud services list --enabled no longer shows Pub/Sub. If you skipped step 7, remove the unconditional binding with --condition=None instead.
Real cases
- Pipeline denied after a repository move. A Terraform pipeline failed with
iam.serviceAccounts.getAccessToken deniedafter a repository was renamed. The federation binding still used the old repository name. The team found it with the exact error text, compared therepositoryclaim with the binding, and added a test that fails if the binding and the repository diverge. - The invisible expiry. A contractor lost access to a project on the day a temporary binding expired. Nobody had changed anything, so the on-call engineer lost an hour. The runbook now starts with the Troubleshooter, which shows condition results, and the review job lists conditional bindings that expire in 14 days.
- Owner denied by a deny policy. A security team added a deny policy to stop deletion of log buckets for all but one group. A project owner could not delete a bucket and assumed a platform bug. The troubleshooter output pointed to the deny rule, and the exception process was documented in the error handling page.
Practices
- Keep a one-page runbook with the triage order. Make the Policy Troubleshooter the standard first tool and attach its output to tickets.
- Print the active identity at the start of automation jobs, so that a wrong-principal failure is obvious.
- Give support engineers a read-only role that can use the troubleshooter and read audit logs (
roles/iam.securityReviewer,roles/logging.viewerat the right scope), so they do not need Owner to diagnose. - Alert on spikes of denied calls by principal; investigate before granting.
- Record every fix as code: a Terraform change or a reviewed script, never a console click you cannot repeat.
Symptoms and first checks
| Symptom | Likely cause | First check |
|---|---|---|
| Works in the console, fails in Terraform or CI | Different principal: the pipeline's service account, or ADC differs from gcloud login | Print identity at the start of the job; gcloud auth list; the provider's credentials |
| Fails right after granting the role | Propagation delay | Wait two minutes; retry the same call once |
| Role is visible in the project policy, still denied | Role granted to a different project or resource, a group the user is not in, or a false condition | gcloud policy-troubleshoot iam RESOURCE --principal-email=EMAIL --permission=PERM |
SERVICE_DISABLED or "has not been used in project N" | API disabled in the project that receives the request, which may be a quota or billing project | Project number in the message; gcloud services list --enabled |
| Owner denied on a specific action | Deny policy, Organization Policy constraint or VPC Service Controls | Error text (constraints/, VPC-SC identifier), then gcloud iam policies list |
| Access ended without any change in the policy | Conditional binding with an expiry date, or a PAM grant that ended | get-iam-policy with condition columns; PAM grant state |
iam.serviceAccounts.actAs denied when attaching a service account to a resource | Caller lacks roles/iam.serviceAccountUser on that service account | Bind it on the service account itself, not on the project, when you can |
| Cross-project call fails but both projects have roles | Service account lives in project A but needs roles in B; or Shared VPC and quota project differ | Check where the service account and the target resources live; check bindings in the target project |
Triage order (the whole module in eight lines)
- Name the principal and the permission from the error.
- Confirm the identity (
gcloud auth list, impersonation, ADC). - Confirm the API is enabled in the project that receives the request.
- Check bindings for that principal on the resource and its ancestors (member type, role, scope).
- Check conditions and expiry.
- Check deny policies, then Organization Policy and VPC Service Controls.
- If the change is minutes old, wait and retry once.
- Prove the cause with the Troubleshooter or the audit log, then change one thing and retest.
Official videos change often, so the links below are search pages rather than pinned video links. Check the video date against the version of the documentation you use.
- YouTube search: Google Cloud permission denied troubleshooting
- YouTube search: IAM deny policies
- YouTube search: audit logs and denied requests
Official reading: Troubleshoot permissions · Deny policies · IAM Conditions overview.
Command cheat sheet
Commands used in Hour 2, grouped by task. Replace uppercase placeholders. "Cost" is free for metadata and IAM operations. Check gcloud COMMAND --help for the flags in your SDK version before you use a command in production.
Inspect and troubleshoot access (read-only, free)
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud auth list | Shows which account is active | none | Application Default Credentials (Terraform, client libraries) are separate from this login |
gcloud config list | Shows project, account and auth/impersonate_service_account | none | An impersonation property silently changes the identity of every command |
gcloud projects get-iam-policy PROJECT_ID | Prints the project's allow policy | --flatten="bindings[].members", --filter="bindings.members:EMAIL", --format=... | Shows only the project level; inherited bindings come from folders and the organization |
gcloud resource-manager folders get-iam-policy FOLDER_ID | Prints a folder's allow policy | same as above | Needs permission on the folder |
gcloud organizations get-iam-policy ORG_ID | Prints the organization's allow policy | same as above | Large output; always filter |
gcloud policy-troubleshoot iam RESOURCE | Explains whether a principal has a permission on a resource | --principal-email, --permission | RESOURCE is the full resource name, for example //cloudresourcemanager.googleapis.com/projects/PROJECT_ID; enable policytroubleshooter.googleapis.com |
gcloud iam policies list | Lists deny policies at an attachment point | --kind=denypolicies, --attachment-point=... | Check the attachment point format in --help; run it for the project, folder and organization |
gcloud services list --enabled | Confirms an API is enabled | --project, --filter="name:API" | SERVICE_DISABLED looks like a permission error but needs the API enabled, not a role |
gcloud logging read 'protoPayload.status.code=7' | Finds denied calls in audit logs | --freshness, --limit, --format | Data Access logs may be off; an empty result does not prove there was no denial |
Roles and bindings (write, free)
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud iam roles list | Lists predefined or custom roles | --project or --organization, --show-deleted | Without a scope it lists predefined roles only |
gcloud iam roles describe ROLE | Shows permissions of a role | --project for custom roles | Custom roles need the full name projects/PROJECT_ID/roles/ROLE_ID when bound |
gcloud iam roles create ROLE_ID | Creates a custom role | --project, --title, --permissions, --stage | Custom roles do not receive new permissions automatically; some permissions cannot be used in custom roles |
gcloud iam roles delete ROLE_ID | Soft-deletes a custom role | --project | The ID stays reserved for a period; remove bindings first |
gcloud projects add-iam-policy-binding PROJECT_ID | Adds one member-role binding | --member, --role, --condition or --condition=None | Member prefix must match the type: user:, group:, serviceAccount:, principalSet: |
gcloud projects remove-iam-policy-binding PROJECT_ID | Removes one binding | same flags | With conditional bindings you must pass the same condition, or the binding stays |
gcloud iam service-accounts create NAME | Creates a service account | --project, --display-name | Name is 6 to 30 characters; creating the account grants it no roles |
gcloud iam service-accounts add-iam-policy-binding SA_EMAIL | Grants access ON a service account (who may use it) | --member, --role | serviceAccountTokenCreator is impersonation; serviceAccountUser is attach; do not mix them up |
Impersonation and keyless access
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud COMMAND --impersonate-service-account=SA_EMAIL | Runs one command as a service account, with no key | the flag itself | The caller needs iam.serviceAccounts.getAccessToken on the account; enable iamcredentials.googleapis.com |
gcloud config set auth/impersonate_service_account SA_EMAIL | Impersonates for all later commands | property | Easy to forget; unset it with gcloud config unset auth/impersonate_service_account |
gcloud iam workload-identity-pools create POOL_ID | Creates a Workload Identity pool | --location=global, --display-name, --project | Pool IDs of deleted pools stay reserved for a period |
gcloud iam workload-identity-pools providers create-oidc PROVIDER_ID | Creates an OIDC provider (for example GitHub) | --workload-identity-pool, --issuer-uri, --attribute-mapping, --attribute-condition | Always set an attribute condition; google.subject is required in the mapping |
gcloud iam workload-identity-pools providers describe PROVIDER_ID | Prints the provider resource name and condition | --format="value(name)" | The name uses the project number, not the project ID |
gcloud iam service-accounts add-iam-policy-binding SA_EMAIL --role=roles/iam.workloadIdentityUser | Lets a pool identity impersonate the account | --member="principalSet://iam.googleapis.com/projects/NUMBER/locations/global/workloadIdentityPools/POOL/attribute.repository/ORG/REPO" | Never bind the whole pool or the whole organization for production |
gcloud iam workload-identity-pools create-cred-config | Generates a credential configuration file (no secret in it) for non-GitHub sources | depends on source type | Flags differ by source (AWS, Azure, URL, file); check --help |
Groups, review and privileged access
| Command | Purpose | Key flags | Gotcha |
|---|---|---|---|
gcloud identity groups memberships list | Lists members of a group | --group-email | Needs cloudidentity.googleapis.com and permission to read the group |
gcloud identity groups memberships add | Adds a member to a group | --group-email, --member-email | Prefer changing groups from your identity provider or reviewed automation |
gcloud asset search-all-iam-policies | Finds bindings across a scope | --scope, --query="policy:EMAIL" | Needs cloudasset.googleapis.com; index can lag slightly |
gcloud asset analyze-iam-policy | Analyses effective access of an identity or on a resource | --organization, --identity, --full-resource-name | Output can be large; check --help for group and role expansion flags |
gcloud recommender recommendations list | Lists IAM Recommender suggestions | --recommender=google.iam.policy.Recommender, --location=global, --project | Empty for new projects; suggestions are not applied automatically |
gcloud pam entitlements list | Lists Privileged Access Manager entitlements | --project, --location=global | Enable privilegedaccessmanager.googleapis.com; check gcloud pam --help for your SDK |
gcloud pam grants create | Requests a time-limited grant | --entitlement, --requested-duration, --justification | The grant exists only between approval and expiry; remove the standing binding too |
Conditions snippets
| Goal | Condition expression (CEL) | Gotcha |
|---|---|---|
| Expire a binding | request.time < timestamp('2027-01-01T00:00:00Z') | The binding stays in the policy after expiry; it just stops matching |
| Limit to resources with a name prefix | resource.name.startsWith('projects/_/buckets/lab-') | Only certain services support resource-name conditions |
| Limit by tag | resource.matchTag('ORG_ID/env', 'dev') | Tags must be bound to the resource or an ancestor |
Conditional bindings need a policy version 3. gcloud sets it for you when you pass --condition. Do not edit and re-upload a policy file from an older tool, because it can drop conditions.
Habits
- Name the principal and the permission before you change anything; prove the cause with
gcloud policy-troubleshoot iam. - Test as the target principal (impersonate), and include one denied call in every acceptance test.
- Bind to groups, not users; bind at the lowest scope that works; prefer predefined roles, then small custom roles.
- Never create a service account key; use impersonation or Workload Identity Federation.
- Wait a couple of minutes for propagation before assuming a binding failed.
Capstone lab and final quiz
Capstone lab: a least-privilege automation identity, end to end
Goal. Build and prove the access model for one platform layer in a sandbox project: a group-based human role, a service account with a small custom role, keyless trust for one GitHub repository through Workload Identity Federation, an acceptance test with allowed and denied calls, and a short access review. Then remove everything.
Time. About 40 minutes. Cost. Free: only IAM, Resource Manager and Workload Identity operations; no compute, storage or network resources are created. Budgets send alerts and do not cap spend, so confirm that your sandbox has a budget alert first. IDs in the expected output are illustrative.
Prerequisites
- A sandbox project
PROJECT_ID(not shared with real workloads), linked to a billing account with a budget alert. - Rights in that project to manage IAM, service accounts, custom roles, workload identity pools and APIs (the Owner role in a sandbox is enough; in production use narrower roles).
- A group
GROUP_EMAILyou can add yourself to, or your own addressUSER_EMAILin its place. - Optional: a private GitHub repository
GITHUB_ORG/REPO_NAMEyou control, for step 10. - Cloud Shell or a terminal with the gcloud CLI (current release channel). No key files and no secrets.
Steps
- Set the context and check billing.
export PROJECT_ID=PROJECT_ID gcloud config set project $PROJECT_ID export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)") gcloud billing projects describe $PROJECT_ID --format="value(billingEnabled)"
True
Verify: the last line printsTrueandecho $PROJECT_NUMBERprints a 12-digit number. - Enable the APIs.
gcloud services enable iam.googleapis.com iamcredentials.googleapis.com sts.googleapis.com cloudresourcemanager.googleapis.com compute.googleapis.com policytroubleshooter.googleapis.com
Verify:gcloud services list --enabled --filter="name:(iamcredentials OR sts OR policytroubleshooter)" --format="value(name)"lists three names. - Create the custom role with four read-only network permissions.
gcloud iam roles create capNetViewer --project=$PROJECT_ID --title="Capstone network viewer" --permissions=compute.networks.get,compute.networks.list,compute.subnetworks.get,compute.subnetworks.list --stage=GA
Verify:gcloud iam roles describe capNetViewer --project=$PROJECT_ID --format="value(includedPermissions)"prints the four permissions separated by semicolons. - Create the service account for the pipeline and give it the custom role.
gcloud iam service-accounts create cap-pipeline --display-name="Capstone pipeline (no keys)" gcloud projects add-iam-policy-binding $PROJECT_ID --member="serviceAccount:cap-pipeline@$PROJECT_ID.iam.gserviceaccount.com" --role="projects/$PROJECT_ID/roles/capNetViewer" --condition=None
Verify:gcloud projects get-iam-policy $PROJECT_ID --flatten="bindings[].members" --filter="bindings.role:capNetViewer" --format="table(bindings.role,bindings.members)"shows the service account. - Bind the group for humans to the same role, and let it impersonate the service account.
gcloud projects add-iam-policy-binding $PROJECT_ID --member="group:GROUP_EMAIL" --role="projects/$PROJECT_ID/roles/capNetViewer" --condition=None gcloud iam service-accounts add-iam-policy-binding cap-pipeline@$PROJECT_ID.iam.gserviceaccount.com --member="group:GROUP_EMAIL" --role="roles/iam.serviceAccountTokenCreator"
Verify:gcloud iam service-accounts get-iam-policy cap-pipeline@$PROJECT_ID.iam.gserviceaccount.comlists the group withroles/iam.serviceAccountTokenCreator. Wait one to two minutes. - Acceptance test as the service account.
SA=cap-pipeline@$PROJECT_ID.iam.gserviceaccount.com gcloud compute networks list --impersonate-service-account=$SA gcloud compute instances list --impersonate-service-account=$SA
WARNING: This command is using service account impersonation. All API calls will be executed as [cap-pipeline@PROJECT_ID.iam.gserviceaccount.com]. NAME SUBNET_MODE BGP_ROUTING_MODE default AUTO REGIONAL ERROR: (gcloud.compute.instances.list) Some requests did not succeed: - Required 'compute.instances.list' permission for 'projects/PROJECT_ID'
Verify: the first command succeeds (or printsListed 0 items.) and the second is denied forcompute.instances.list. If the second succeeds, find the broader role with step 7. - Explain the decision with Policy Troubleshooter.
gcloud policy-troubleshoot iam //cloudresourcemanager.googleapis.com/projects/$PROJECT_ID --principal-email=$SA --permission=compute.networks.list gcloud policy-troubleshoot iam //cloudresourcemanager.googleapis.com/projects/$PROJECT_ID --principal-email=$SA --permission=compute.instances.list
Verify: the first printsaccess: GRANTED(naming the custom role binding), the secondaccess: NOT_GRANTED. - Create the keyless trust for GitHub.
gcloud iam workload-identity-pools create cap-pool --location=global --display-name="Capstone pool" gcloud iam workload-identity-pools providers create-oidc cap-github --location=global --workload-identity-pool=cap-pool \ --issuer-uri="https://token.actions.githubusercontent.com" \ --attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository" \ --attribute-condition="assertion.repository=='GITHUB_ORG/REPO_NAME'" gcloud iam service-accounts add-iam-policy-binding $SA --role="roles/iam.workloadIdentityUser" \ --member="principalSet://iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/cap-pool/attribute.repository/GITHUB_ORG/REPO_NAME"
Verify:gcloud iam workload-identity-pools providers describe cap-github --location=global --workload-identity-pool=cap-pool --format="value(name,attributeCondition)"prints the provider path (with the project number) and your condition. The service account's policy must contain aprincipalSetmember ending in your repository, not/*. - Run the access review. Export the policy and look for direct users and broad roles:
gcloud projects get-iam-policy $PROJECT_ID --flatten="bindings[].members" --filter="bindings.members:user:" --format="table(bindings.role,bindings.members)" gcloud projects get-iam-policy $PROJECT_ID --flatten="bindings[].members" --filter="bindings.role:(roles/owner OR roles/editor)" --format="table(bindings.role,bindings.members)"
Verify: you can write one line for every row: keep, move to a group, or remove, with an owner. The capstone identities (cap-pipelineand the group) must not appear in the broad-role list. - (Optional) Prove federation from GitHub. In your repository add this workflow, push to a branch and run it:
name: capstone-auth on: workflow_dispatch permissions: id-token: write contents: read jobs: whoami: runs-on: ubuntu-latest steps: - id: auth uses: google-github-actions/auth@v2 with: workload_identity_provider: projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/cap-pool/providers/cap-github service_account: cap-pipeline@PROJECT_ID.iam.gserviceaccount.com - uses: google-github-actions/setup-gcloud@v2 - run: gcloud auth list - run: gcloud compute networks list --project=PROJECT_IDVerify: the run succeeds and the log shows the service account. Check the current major version of the action in its README before you copy this. To prove the condition, run the same workflow from a different repository: it must fail with an error that the credential is rejected by the attribute condition.
Expected result
- The custom role has four permissions; the service account and the group hold it on the project, and nothing broader.
- The group can impersonate the service account; nobody holds a key.
- Network listing succeeds as the service account, instance listing is denied, and the Troubleshooter agrees.
- The pool and provider accept tokens only from one repository, and the service account can be impersonated only from that repository.
- You have a short written review with a decision for each finding.
If a step fails
| Symptom | Likely cause | First check |
|---|---|---|
Impersonated call: iam.serviceAccounts.getAccessToken denied | Missing token creator binding or propagation | Step 5 verification; wait two minutes |
| Network call denied for the service account | Custom role not bound, or wrong member prefix | Step 4 verification |
The given credential is rejected by the attribute condition | Repository name in condition does not match the run | Provider attributeCondition and the repository path |
API ... has not been used in project | API not enabled | Step 2 verification |
Identity Pool does not exist | Project ID used where the number is required | echo $PROJECT_NUMBER |
Cleanup (in this order)
gcloud iam service-accounts remove-iam-policy-binding $SA --role="roles/iam.workloadIdentityUser" --member="principalSet://iam.googleapis.com/projects/$PROJECT_NUMBER/locations/global/workloadIdentityPools/cap-pool/attribute.repository/GITHUB_ORG/REPO_NAME" gcloud iam workload-identity-pools providers delete cap-github --location=global --workload-identity-pool=cap-pool --quiet gcloud iam workload-identity-pools delete cap-pool --location=global --quiet gcloud iam service-accounts remove-iam-policy-binding $SA --member="group:GROUP_EMAIL" --role="roles/iam.serviceAccountTokenCreator" gcloud projects remove-iam-policy-binding $PROJECT_ID --member="group:GROUP_EMAIL" --role="projects/$PROJECT_ID/roles/capNetViewer" --condition=None gcloud projects remove-iam-policy-binding $PROJECT_ID --member="serviceAccount:$SA" --role="projects/$PROJECT_ID/roles/capNetViewer" --condition=None gcloud iam service-accounts delete $SA --quiet gcloud iam roles delete capNetViewer --project=$PROJECT_ID --quiet
Verify the cleanup. gcloud iam service-accounts list no longer shows cap-pipeline; the project policy has no capNetViewer bindings; gcloud iam workload-identity-pools list --location=global does not list cap-pool (deleted pools may appear with --show-deleted). Deleted pools, providers and roles are kept for a period and their IDs are reserved, so use new IDs if you repeat the lab. Delete the GitHub workflow file and the local variables. Keep the written review.
iam.disableServiceAccountKeyCreation (Hour 3) guarantee that nobody falls back to key files.Knowledge check
Sources and versions
Official documentation used in Hour 2
Tools and versions used
| Tool | Version used in the course | Note |
|---|---|---|
Google Cloud CLI (gcloud) | current release channel | Check with gcloud version and update with gcloud components update (not available in Cloud Shell, which is kept current for you). Some commands, such as gcloud pam, are newer than the core IAM commands. |
| Cloud Shell | managed by Google | Always has a current gcloud and is free of key files |
google-github-actions/auth | current major version (the course examples use v2) | Read the README for the current major version and pin to a full commit SHA in production |
google-github-actions/setup-gcloud | current major version (the examples use v2) | Used only to install the CLI in a job |
| Terraform (for later hours) | 1.x with the Google provider | Pin the major version in required_providers |
| Google Cloud APIs | iam, iamcredentials, sts, cloudresourcemanager, policytroubleshooter, cloudasset, recommender, cloudidentity, privilegedaccessmanager | Enabling an API is free; enable only what the lab needs |
gcloud COMMAND --help. Before you use a command or a Terraform snippet in production, check it against the current documentation and the SDK version you run, test it in a sandbox, and review the plan or the diff. Do not depend on the exact text of error messages or expected output; IDs and wording in this course are illustrative.Related reading in the course
- Hour 1: resource hierarchy, billing and identity foundation (organization, folders, groups, break-glass accounts).
- Hour 3: Organization Policy constraints that support IAM, for example
iam.disableServiceAccountKeyCreationandiam.allowedPolicyMemberDomains. - Hour 6: audit logs and log routing for IAM changes.
- Hour 7: Terraform and CI/CD with Workload Identity Federation, one service account per layer.
Documentation links point to cloud.google.com and github.com and were chosen for stable section names. If a page has moved, search the title on the Google Cloud documentation site.