Hour 2: Identity and access management (IAM)

Allow policies, predefined and custom roles, service accounts, Workload Identity Federation, IAM Conditions and privileged access.
Hour 2IAMService accountsWorkload Identity Federation

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 gcloud without 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)

#ModuleMinutes
1The IAM model6
2Role types and least privilege7
3Inheritance, IAM Conditions and deny policies7
4Service accounts8
5Keyless authentication: Workload Identity Federation8
6Groups, privileged access and access reviews7
7Lab: least-privilege platform team10
8Troubleshooting "permission denied"7
Total60

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

ModuleResources createdCost class
1One binding on a sandbox project for a test group, removed at the endFree
2One project custom role (logReader) and a bindingFree
3A conditional binding with an expiry, an optional folder binding, and one deny policyFree
4One service account without keys, and an impersonation bindingFree
5 and 6A workload identity pool and provider (configuration only), and read-only reviews of existing accessFree
7A group binding, a custom role, a service account and an impersonation test, all in the sandbox project, then cleanupFree
8Read-only diagnosticsFree

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.

Cost. The IAM labs create roles, bindings, service accounts and pool configuration. These are metadata and free. They do not cap spend: if you also use your project for other work, a budget sends alerts only and does not stop charges, so set a budget first (Hour 1, Module 3) and run the cleanup at the end of each lab.
Safety. Do this hour in a sandbox, not a production organization. Access changes are powerful: a wrong binding on a production folder is an incident. Use placeholders such as 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

Identity and access management (IAM)
Hour 2

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

OptionWhat worksWhat does not
Sandbox organization with a lab folder (recommended)Everything: folder and project bindings, groups, deny policies, Policy Analyzer at organization scope, access reviewsNothing is missing. You need admin help to create groups unless you are the administrator.
Company organization with a delegated sandbox projectProject-level bindings, custom roles in the project, service accounts, Workload Identity Federation (if allowed), troubleshooterOrganization-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 FederationFolders, organization policies and organization-level roles or policies; Google groups through your own domain
What to do without an organization. Use a personal project for every lab that names 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:

ForRoleScope
Reading and changing the project policyroles/resourcemanager.projectIamAdminSandbox project
Creating custom rolesroles/iam.roleAdminSandbox project
Creating service accountsroles/iam.serviceAccountAdminSandbox project
Managing the policy on a service accountroles/iam.serviceAccountAdmin, or OwnerSandbox project
Deny policies (Module 3, optional)roles/iam.denyAdminSandbox project
Workload Identity pools (Module 5)roles/iam.workloadIdentityPoolAdminSandbox project
Reading audit logsroles/logging.viewer (Admin Activity logs)Sandbox project
Policy Analyzer on the organizationroles/cloudasset.viewer and roles/iam.securityReviewerOrganization 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 lack resourcemanager.projects.getIamPolicy. Check gcloud auth list and 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 --project flag 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.
Security. Never create service account keys in these labs, and do not paste tokens, keys or passwords into commands or chat. You use your own identity, impersonation and, in Module 5, federation with short-lived tokens only.

Module 1 · The IAM model

00–06 · Principals, roles, permissions and allow policies on a resource
PrincipalRoleAllow policy6 min
Learning objectives
  • 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

PartQuestionExample
PrincipalWho is calling?group:platform-engineers@example.com
PermissionWhat action is requested?compute.instances.start
RoleWhich bundle of permissions was granted?roles/compute.instanceAdmin.v1
ResourceOn 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, a members list and an optional condition. 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-binding set this for you, but a hand-edited file passed to set-iam-policy must carry the right version (Module 3).
  • auditConfigs: an optional section that turns on Data Access audit logs for a service (Hour 6).

Principal types

PrefixIdentityUse it for
user:One Google Account or Cloud Identity userRare. Prefer groups. Acceptable for a one-off personal sandbox.
group:A Google groupPeople. 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 domainBroad read-only access to a shared dataset; use with care.
principal:// and principalSet://Federated identities from Workload Identity Federation, or a workforce poolCI/CD and external identity providers (Module 5).
allUsersAnyone on the internet, no sign-inPublic websites only. Normally blocked by an Organization Policy (Hour 3).
allAuthenticatedUsersAny signed-in Google account, including personal GmailAlmost 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

  1. 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.
  2. The target service maps the API method to one or more permissions (for example storage.objects.get).
  3. 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.
  4. 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.
  5. 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 atReason
Read access to one bucketThe bucketSmallest blast radius; the grant disappears with the bucket.
Admin over one applicationThe application's projectProjects are the natural unit of ownership.
Read access to every production projectThe production folderOne binding, inherited by new projects automatically.
Organization-wide auditingThe organization, for a small security groupVisibility without write rights.

What IAM is confused with

Often confused withThe difference
AuthenticationAuthentication proves who you are (sign-in, token, 2-step verification). IAM is authorization: what that identity may do.
Organization PolicyIAM controls who can act. Organization Policy controls what configurations are allowed, for everyone, whatever their role (Hour 3).
Network firewall rulesFirewalls 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 rolesAdmin 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 RBACAWS 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.
Common misunderstanding 1. "The project owner can always do everything." Owner is just a basic role. A deny policy or an Organization Policy can still block an action, and some actions need permissions the role does not contain.
Common misunderstanding 2. "I granted the role a minute ago, so it must work." Changes to an allow policy are eventually consistent. Usually they take effect within seconds, but allow up to several minutes before you debug (Module 8 shows how to prove it).
Common misunderstanding 3. "A group in a binding means everyone in the group has a copy of the role." The role is bound to the group principal; membership is resolved at request time. Add a person to the group and access follows. Remove them and it stops, with the same short delay.
Principal group:platform-engineers Binding in the allow policy role: roles/compute.viewer members: group:…, condition: optional policy has an etag Resource projects/PROJECT_ID Role = set of permissions compute.instances.get, .list, compute.zones.list … Request: principal calls an API method → service maps it to a permission → IAM looks for a binding whose role contains that permission, on the resource or any ancestor. No binding means denied (default deny).

Figure 1. One binding links a principal to a role on a resource. The role is expanded into permissions at request time.

1. get-iam-policy returns bindings + etag A 2. edit locally add or remove a binding 3. set-iam-policy sends bindings + etag A etag still A write accepted, new etag B etag changed 409 ABORTED, read again add-iam-policy-binding performs this loop for you and retries on conflict; set-iam-policy replaces the whole policy, so use it only with a file you just read.

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.

Production use. Treat 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.

  1. Set the project: gcloud config set project PROJECT_ID and check with gcloud config list project.
  2. Save the current policy as a baseline: gcloud projects get-iam-policy PROJECT_ID --format=json > before.json. Note the etag.
  3. Grant a read-only role to the test group: gcloud projects add-iam-policy-binding PROJECT_ID --member="group:GROUP_EMAIL" --role="roles/viewer".
  4. 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 in before.json.
  5. List the roles of the group with the flatten and filter command from the previous tab. You must see roles/viewer.
  6. 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 say access: GRANTED (allow up to a few minutes for propagation).
  7. 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.
  8. 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/editor to 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 run asset search-all-iam-policies for any remaining user: 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 bound allUsers to 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 for allUsers and allAuthenticatedUsers now 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.organizationAdmin and roles/iam.securityAdmin every quarter (Module 6 covers reviews).

Security notes

Warning. The permission to change an allow policy (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.
Tip. Audit log entries for 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

SymptomLikely causeFirst check
PERMISSION_DENIED on get-iam-policyMissing resourcemanager.projects.getIamPolicygcloud auth list; confirm you are on the right account
add-iam-policy-binding says the member is invalidWrong prefix or a misspelled emailCheck user:, group:, serviceAccount: and the exact address
Binding added but the user still gets deniedPropagation, a deny policy, or the role lacks the permissiongcloud policy-troubleshoot iam ...
Etag or ABORTED error on set-iam-policyAnother change happened after you read the policyRead the policy again and re-apply your edit
Binding removed but access remainsAccess is inherited from a folder, the organization, or another groupRun asset search-all-iam-policies with the principal as the query
Member rejected by an Organization Policy messageiam.allowedPolicyMemberDomains blocks outside identitiesgcloud org-policies describe iam.allowedPolicyMemberDomains --project=PROJECT_ID --effective

Triage order

  1. Which principal made the call (gcloud auth list, or the principalEmail in the audit log)?
  2. Which permission and which resource (read the exact error text)?
  3. Run the troubleshooter for that triple.
  4. Read the allow policy on the resource and each ancestor.
  5. 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.

or score ≥ 70% on the quiz

Module 2 · Role types and least privilege

06–13 · Basic, predefined and custom roles, and how IAM Recommender shrinks access
BasicPredefinedCustomRecommender7 min
Learning objectives
  • 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

TypeExamplesWho maintains itGranularityUse it for
Basicroles/viewer, roles/editor, roles/owner, roles/browserGoogleVery coarse: thousands of permissions across servicesSandboxes and personal projects; roles/browser for read-only hierarchy visibility
Predefinedroles/storage.objectViewer, roles/compute.instanceAdmin.v1, roles/logging.viewerGooglePer product and per jobDefault choice for nearly every grant
Customprojects/PROJECT_ID/roles/logReaderYour organizationExactly the permissions you listWhen 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 as get, list, create, update, delete and setIamPolicy make a role easy to scan: a role with only get and list verbs 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, DEPRECATED or DISABLED. 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 create says 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?

  1. Name the task in plain words: "read logs", "deploy to Cloud Run", "manage buckets".
  2. Search predefined roles for it: gcloud iam roles list --filter="title:Logs" or the roles reference.
  3. Pick the smallest predefined role that covers the task. Look at includedPermissions to confirm.
  4. 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.
  5. Bind it at the lowest level (resource or project) and to a group or service account.
  6. After a month, review IAM Recommender and remove what is unused.

When to use each type

SituationChooseWhy
Personal learning projectOwner on the project is acceptableNo other users; the project is disposable
Developers deploy an app to Cloud RunPredefined (Cloud Run Developer, plus Service Account User on the runtime account)Google updates them with the product
Auditors need read access to configuration of everythingPredefined viewer roles such as Security ReviewerBroad read, no write
A pipeline must start and stop VMs with a given label onlyPredefined Instance Admin with a condition (Module 3), or a custom rolePredefined roles may include more than needed
A job needs three permissions from three productsCustom roleAvoids three broad predefined roles

What roles are confused with

Often confused withThe difference
Google Workspace admin rolesThese 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.
GroupsA group is a set of principals; a role is a set of permissions. Access is the combination of both in a binding.
Organization PolicyIt restricts configurations, not people. Even Owner cannot violate a constraint.
AWS managed policies and Azure built-in rolesPredefined 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.
Common misunderstanding 1. "Custom roles are always better because they are smaller." Each custom role is something you must maintain. When Google adds permissions to a predefined role you receive them automatically; a custom role will quietly break a new feature until you update it.
Common misunderstanding 2. "Viewer is harmless." The Viewer role can read configuration and data in many services, including metadata that may expose network layout and secret names. Treat it as sensitive for production.
Common misunderstanding 3. "A custom role at the project is visible everywhere." It exists only in that project. To share, create it at the organization or duplicate it as code.
Basic roles: Owner · Editor · Viewer · Browser thousands of permissions across almost all services · sandbox only Predefined roles: per product and per job roles/storage.objectViewer · roles/compute.instanceAdmin.v1 · maintained by Google Custom roles: your list of permissions projects/PROJECT_ID/roles/… or organizations/ORG_ID/roles/… After IAM Recommender only what was used in the last 90 days narrower, more to maintain, less blast radius

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.

Task described in words Predefined role small enough? yes Bind it at lowest level no Limit with a Condition? Otherwise: custom role yes → Module 3

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.

Production use. Keep custom role definitions as YAML or Terraform (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.

  1. 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.
  2. Create the YAML file role.yaml from the commands tab and run gcloud iam roles create logReader --project=PROJECT_ID --file=role.yaml.
  3. Verify the role: gcloud iam roles describe logReader --project=PROJECT_ID --format="value(stage,includedPermissions)". Expect GA and the two permissions.
  4. List custom roles in the project: gcloud iam roles list --project=PROJECT_ID --format="table(name,stage)".
  5. Bind the role to the test group with its full name projects/PROJECT_ID/roles/logReader.
  6. Check the binding: gcloud projects get-iam-policy PROJECT_ID --flatten="bindings[].members" --filter="bindings.role:logReader" --format="table(bindings.role,bindings.members)".
  7. Add one missing permission and verify: gcloud iam roles update logReader --project=PROJECT_ID --add-permissions=logging.views.list followed by step 3. The list now has three permissions.
  8. 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/viewer only 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

Warning. Do not put permissions such as 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.
Tip. Name custom roles for the task, not the team (logReader, not teamARole), so reuse is natural and reviews are short.

Symptoms and first checks

SymptomLikely causeFirst check
INVALID_ARGUMENT: Permission ... is not valid on roles createTypo, or the permission is not supported in custom rolesgcloud iam list-testable-permissions ... and the permissions reference
ALREADY_EXISTS when creating a roleThe ID exists or was deleted recentlygcloud iam roles list --project=PROJECT_ID --show-deleted
Custom role binding rejected in another projectThe role was created in a project, not the organizationRecreate it with --organization=ORG_ID or define it in each project
User has the role but a new feature is deniedThe custom role lacks the new permissionCompare with the predefined role's includedPermissions and add the missing one
Binding shows deleted: in the policyThe principal or role was deletedRemove the stale binding; recreate the role if needed
No recommendations appearAPI not enabled, too little usage data, or the principal is newEnable recommender.googleapis.com; wait for usage history

Triage order

  1. Read the error and note the exact permission name.
  2. Describe the role that should contain it (gcloud iam roles describe).
  3. If the role lacks it, decide: pick another predefined role, or update the custom role.
  4. Re-run the troubleshooter after a short wait to confirm the change.
  5. 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.

or score ≥ 70% on the quiz

Module 3 · Inheritance, IAM Conditions and deny policies

13–20 · How access flows down the hierarchy, how to make it conditional, and how to override it with deny
InheritanceIAM ConditionsDeny policies7 min
Learning objectives
  • 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

  1. 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.
  2. 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.
  3. Allow policies from the resource up to the organization. Each binding's condition is evaluated against the request.
  4. 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.

UseExample expressionMeaning
Expiry daterequest.time < timestamp("2027-01-01T00:00:00Z")Access ends automatically; no ticket to remember
Business hoursrequest.time.getHours("Europe/London") >= 8 && request.time.getHours("Europe/London") < 18Role works only in a time window (check the documentation for the time functions you can use)
Resource name prefixresource.name.startsWith("projects/_/buckets/lab-bucket/objects/reports/")Role limited to one folder of objects in one bucket
Resource typeresource.type == "compute.googleapis.com/Instance"Role applies only to VMs, not disks
Resource tagresource.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-binding handles the version; the raw set-iam-policy needs "version": 3 in 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:

FieldMeaning
deniedPrincipalsWho is blocked. Uses the principal set syntax: principalSet://goog/group/GROUP_EMAIL, principal://goog/subject/EMAIL, or principalSet://goog/public:all.
exceptionPrincipalsPrincipals who are not blocked even if they match a denied principal, for example a break-glass group.
deniedPermissionsThe blocked actions, in the form SERVICE_FQDN/RESOURCE.VERB, for example iam.googleapis.com/serviceAccountKeys.create.
exceptionPermissionsPermissions that stay allowed when a wildcard in deniedPermissions covers them.
denialConditionA 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.denyAdmin manages 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

NeedUseWhy
Give access for a limited timeConditional binding with an expiryExpires by itself; the record stays in the policy
Give a role only on some resources of a typeCondition with a tag or a name prefixOne binding, no per-resource grants
Nobody except break-glass may delete projectsDeny policy at the organization with exceptionsOverrides Owner and any other role
Nobody may create service account keysOrganization Policy iam.disableServiceAccountKeyCreation (Hour 3), possibly with a deny policyConfiguration limit; deny adds a second layer
Remove an unneeded roleRemove the binding where it was grantedDeny is for exceptions, not for tidy-up

What these controls are confused with

Often confused withThe difference
Organization PolicyChecks the configuration of a resource (regions, external IPs, public buckets). Deny policies check the principal and permission.
VPC Service ControlsLimits API traffic that crosses a perimeter, based on network context and identity (Hour 3).
Firewall rulesNetwork packets. IAM Conditions do not see ports and IP addresses of a normal request.
Azure deny assignments, AWS explicit denySimilar in effect. In Google Cloud the deny policy is its own object, separate from the allow policy.
Common misunderstanding 1. "A project-level role is stronger than a folder-level role." There is no strength ordering among allow grants; they are all added together. Only a deny policy (or a different control such as Organization Policy) can subtract.
Common misunderstanding 2. "An expired conditional binding is deleted." It stays in the policy, harmless but noisy. Clean it up as part of a review.
Common misunderstanding 3. "Deny policies are the way to implement least privilege." Least privilege is built with narrow allow grants. Use deny sparingly for a few high-risk actions, because many deny rules become hard to explain.
Organization group:security-reviewers: Security Reviewer Folder: production group:platform-engineers: Storage Admin Project: prj-app-a user:ana@example.com: Storage Object Viewer Bucket: lab-bucket group:app-a-devs: Storage Object Admin Effective allow policy of the bucket Security Reviewer (from organization) Storage Admin (from folder) Storage Object Viewer (from project) Storage Object Admin (on bucket) = union; a deny policy can still block

Figure 1. Effective access is a union. Seen from the bucket, only one of four grants is visible in its own policy.

Request principal, permission Deny policies resource + ancestors match means denied Allow policies union up the hierarchy conditions evaluated Allowed grant found Denied by policy Denied: no grant Organization Policy and VPC Service Controls are separate checks that can still block the call after IAM allows it.

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.

Careful. A deny rule that matches your own administrators can lock you out of the very action needed to remove the rule. Always include an exception principal, and test on a sandbox project first.

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.

  1. (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".
  2. 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.
  3. 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.
  4. Add the expiring conditional binding from the commands tab (lab-expiry).
  5. Verify it is conditional: gcloud projects get-iam-policy PROJECT_ID --format="yaml(bindings)" and look for the condition block and version: 3 in the full output.
  6. 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 with expression=request.time < timestamp("2020-01-01T00:00:00Z") and a different role such as roles/pubsub.viewer, and troubleshoot pubsub.topics.list. Expect no access, with a condition that evaluated to false.
  7. Create the deny policy file and the policy from the commands tab, using GROUP_EMAIL for the test group.
  8. Wait a minute, then run the troubleshooter for iam.serviceAccountKeys.create for a member of the group (the deny permission uses the form iam.googleapis.com/serviceAccountKeys.create in 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

Warning. A binding that grants 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.
Tip. Audit logs record the full condition in SetIamPolicy events. Alert on conditions that include very long expiry dates (for example more than a year).

Symptoms and first checks

SymptomLikely causeFirst check
A user has access but the project policy shows nothing for themInherited binding from a folder or the organization, or a group membershipgcloud policy-troubleshoot iam ... or gcloud asset analyze-iam-policy ...
Role removed from the project but access remainsThe same role (or another) is granted aboveRead folder and organization policies
Access ended unexpectedly at a certain dateAn expired conditional bindingLook for condition blocks in get-iam-policy
Adding a binding without specifying a condition ... is prohibitedThe role already has conditional bindingsPass --condition=None or a condition
Conditions disappeared after a script ranA client read or wrote policy version 1Use version 3, or use the single-binding commands
User denied although the role is grantedA deny policy at some ancestorTroubleshooter output (deny section); gcloud iam policies list --kind=denypolicies at each level
Deny policy does not take effectPermission not supported for deny, wrong principal format, or propagation delayCheck the supported permissions page and the principal syntax

Triage order

  1. Run the troubleshooter first; it covers allow, deny and conditions in one answer.
  2. If it is unavailable, read allow policies from the resource upwards.
  3. List deny policies at the same levels.
  4. Check conditions, especially time limits and tag matches.
  5. Last, consider propagation and caching.

These are search pages and official documentation, not pinned videos. Check the publication date.

Official reading: IAM Conditions overview · Deny policies · Policy Troubleshooter · Resource hierarchy.

or score ≥ 70% on the quiz

Module 4 · Service accounts

20–28 · Identities for workloads: create, attach, impersonate, and contain the default accounts
Service accountImpersonationactAsDefault accounts8 min
Learning objectives
  • 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-account without ever creating a key.
  • Distinguish roles/iam.serviceAccountUser (attach) from roles/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

KindExampleWho manages itNotes
User-managedci-deployer@PROJECT_ID.iam.gserviceaccount.comYouThe type you create for workloads. One per workload and per environment.
DefaultPROJECT_NUMBER-compute@developer.gserviceaccount.com, PROJECT_ID@appspot.gserviceaccount.comCreated by Google when a service is first used, then yours to manageHistorically gets Editor. Avoid using it for real workloads.
Service agentsservice-PROJECT_NUMBER@compute-system.iam.gserviceaccount.comGoogleUsed 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

  1. 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.actAs on the account (roles/iam.serviceAccountUser).
  2. Impersonate it. A person or another service account asks for a short-lived token with --impersonate-service-account or the IAM Credentials API. The caller needs iam.serviceAccounts.getAccessToken, which roles/iam.serviceAccountTokenCreator contains. Used for deployments, tests and "break-glass as the pipeline" work.
  3. 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

RoleGrants the ability toTypical holder
roles/iam.serviceAccountUserAttach the account to resources (actAs)Deployers and pipelines, on the specific accounts they deploy with
roles/iam.serviceAccountTokenCreatorImpersonate: create access tokens and sign blobsPlatform engineers or a pipeline account that acts as a deploy account
roles/iam.serviceAccountAdminCreate, delete and edit service accounts and their policiesPlatform team only
roles/iam.serviceAccountKeyAdminCreate and delete keysNobody by default; sensitive
roles/iam.workloadIdentityUserLet 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/editor on the project. A VM created without a flag would run as that account with Editor access.
  • The Organization Policy boolean constraint constraints/iam.automaticIamGrantsForDefaultServiceAccounts stops 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-account when 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

WorkloadIdentity approach
VM, Cloud Run, Cloud Functions, GKE on Google CloudDedicated service account attached to the resource
Pipeline on GitHub Actions, GitLab, Azure DevOpsWorkload Identity Federation (Module 5), then impersonate a deploy service account
Engineer who needs to test what the pipeline can doImpersonation with Token Creator, time-bound
Software that cannot use any of the aboveA key, as a documented exception with rotation and an owner

What service accounts are confused with

Often confused withThe difference
User accountsHumans sign in interactively with passwords and 2-step verification. Service accounts have no password and cannot sign in to the console.
API keysAn API key identifies a project for quota and some public APIs. It is not an identity, and it has no roles.
OAuth client IDsUsed when an app asks a user for consent to act as that user. Service accounts act as themselves.
Access scopes on VMsLegacy 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 identitiesClosest equivalents. An attached service account is similar to an instance profile or a managed identity.
Common misunderstanding 1. "Giving the pipeline Service Account User on the project is fine." It lets the pipeline run code as every service account in the project, so it inherits the strongest one. Grant it on one service account.
Common misunderstanding 2. "Deleting a service account is safe because I can recreate it with the same name." A recreated account has a new unique ID, so existing bindings to the old one do not apply. Google keeps a deleted account for a limited time during which it can be undeleted; check the documentation for the window.
Common misunderstanding 3. "Impersonation needs the key." It does not. It needs Token Creator on the account and the IAM Service Account Credentials API enabled.
Deployer (person or pipeline) needs serviceAccountUser VM or Cloud Run service runs as the service account Metadata server short-lived tokens, no key 1. Attach: the workload gets tokens automatically through Application Default Credentials. Engineer or pipeline needs serviceAccountTokenCreator IAM Credentials API generateAccessToken Google API sees the service account 2. Impersonate: a short-lived token, audit log records both identities, still no key. Key file (JSON) long-lived secret Anywhere laptop, CI log, Git history Google API valid until deleted 3. Key: avoid. A copy of the file is a copy of the identity. Block key creation with an Organization Policy and use federation for external systems.

Figure 1. Three ways to use a service account. Only the first two avoid a long-lived secret.

Service account ci-deployer@PROJECT_ID .iam.gserviceaccount.com Policy ON the account who may attach or impersonate it Policies ON other resources what the account may do serviceAccountUser serviceAccountTokenCreator granted to people and pipelines storage.objectViewer, run.developer granted to the account itself

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.

Production use. Add a Terraform or CI check that fails when a project policy grants 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.

  1. Create the account: gcloud iam service-accounts create lab-reader --project=PROJECT_ID --display-name="Lab reader".
  2. Verify: gcloud iam service-accounts list --project=PROJECT_ID --format="table(email,disabled)". The new account is listed.
  3. Grant it roles/browser on the project (command above, with lab-reader).
  4. Check that it has no keys: gcloud iam service-accounts keys list --iam-account=lab-reader@PROJECT_ID.iam.gserviceaccount.com --managed-by=user. Expect Listed 0 items.
  5. 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).
  6. Grant yourself roles/iam.serviceAccountTokenCreator on the service account (command above, YOUR_EMAIL is your user). Wait up to a minute.
  7. Repeat step 5. Expect the impersonation warning and the project ID printed.
  8. Prove the boundary: gcloud iam service-accounts list --project=PROJECT_ID --impersonate-service-account=lab-reader@PROJECT_ID.iam.gserviceaccount.com. Expect PERMISSION_DENIED for iam.serviceAccounts.list. The account can read the project but not list service accounts.
  9. 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.
  10. 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-account in 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.serviceAccountUser on 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.disableCrossProjectServiceAccountUsage controls 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

Warning. Anyone with 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.
Tip. Use a separate "deployer" identity with Token Creator on application accounts for pipelines. People impersonate for tests only, with a short time condition (Module 3).

Symptoms and first checks

SymptomLikely causeFirst check
Failed to impersonateMissing Token Creator on the service account, API disabled, or propagationgcloud iam service-accounts get-iam-policy SA_EMAIL; gcloud services list --enabled | grep iamcredentials
Permission 'iam.serviceAccounts.actAs' denied when creating a VM or deployingDeployer lacks Service Account User on the runtime accountGrant roles/iam.serviceAccountUser on that account
Impersonation works but the action is deniedThe service account lacks the role for the actionTroubleshooter with --principal-email=SA_EMAIL
Key creation blocked: Key creation is not allowed on this service accountConstraint iam.disableServiceAccountKeyCreationgcloud org-policies describe iam.disableServiceAccountKeyCreation --project=PROJECT_ID --effective
Default account has Editor again in a new projectThe automatic grant constraint is not enforcedgcloud org-policies describe iam.automaticIamGrantsForDefaultServiceAccounts --project=PROJECT_ID --effective
Workload fails after recreating a service account with the same nameNew unique ID: old bindings no longer matchLook for deleted:serviceAccount:... entries in the policy
Cannot attach a service account from another projectCross-project usage is disabled or missing actAsCheck the constraint and the actAs grant

Triage order

  1. Who is the caller (person, pipeline, attached account)? Check principalEmail and the delegation info in the audit log.
  2. Is the problem "may I use this account" (policy on the account) or "may the account do this" (policy on the target)?
  3. Is the account enabled, and does the Credentials API work?
  4. Run the troubleshooter for the account and the permission.
  5. Check Organization Policy constraints on service accounts.
or score ≥ 70% on the quiz

Module 5 · Keyless authentication: Workload Identity Federation

28–36 · Let GitHub Actions and other outside workloads call Google Cloud without a service account key file
Workload Identity FederationOIDCNo keys8 min
Learning objectives
  • 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.workloadIdentityUser on a service account and use google-github-actions/auth from 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

  1. 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.
  2. Attribute mapping. The provider maps claims from the external token to Google attributes. google.subject is required and identifies the external user or workload; attribute.NAME entries are custom attributes you can use in IAM, for example attribute.repository.
  3. 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.
  4. 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.
  5. Access. Two options. Direct resource access: grant roles straight to the federated principal (principal:// or principalSet://) on the resources it needs. Service account impersonation: grant roles/iam.workloadIdentityUser on 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

FormMeaningExample use
principal://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/subject/SUBJECTOne 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/REPOEvery identity whose mapped attribute has this valueAll runs of one repository
principalSet://iam.googleapis.com/projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/POOL_ID/*Every identity in the poolRarely 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

MechanismCredential lifetimeSecret to storeTypical use
Service account key fileUntil deletedYes (JSON key)Legacy integrations. Block with iam.disableServiceAccountKeyCreation (Hour 3).
Impersonation (--impersonate-service-account)Short (token lifetime)No, but the caller needs its own identityHumans and tools acting as a service account
Workload Identity FederationShortNoOutside workloads: CI/CD, other clouds, on-premises
Attached service account (metadata server)Short, rotated automaticallyNoWorkloads running on Google Cloud
Workload Identity for GKEShortNoPods on GKE accessing Google Cloud APIs

Common misunderstandings

"Federation is secure by itself." It is only as strict as your condition and binding. A pool that trusts the GitHub issuer with no condition lets any GitHub repository in the world obtain a token from STS. IAM bindings then decide whether that token can do anything, which is why a binding on repository_owner is weaker than one on one repository.
"The pool belongs to the workload's project." The pool lives in the project where you create it. Choose a dedicated identity or automation project, not an application project, so that application teams cannot edit the trust configuration.
"Impersonation needs a key somewhere." It does not. The caller authenticates with its own credential (a federated token in this case) and asks IAM for a token for the target service account. No key for the target exists.
GitHub Actions job repo acme/infra · ref main permissions: id-token: write google-github-actions/auth terraform plan / apply GitHub OIDC issuer token.actions.githubusercontent.com Google Cloud (identity project) Security Token Service validates JWT signature Pool and provider mapping + attribute condition IAM Credentials API generateAccessToken Service account workloadIdentityUser binding Target APIs: Storage · Compute · Resource Manager 1 The job requests an OIDC token from GitHub (no secret involved). 2 STS checks the signature, applies the mapping and the attribute condition. 3 The federated token is used to impersonate the service account, which returns a short-lived access token. 4 The pipeline calls the target APIs as the service account. Nothing long-lived is stored in GitHub.

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.

Too broad attribute.repository_owner/acme Better attribute.repository/acme/infra Best for production repository + branch or environment Narrowing path: each step removes identities that can obtain the service account token. Attribute condition: rejects foreign issuers' tokens before IAM is evaluated. IAM binding: decides which accepted identities may impersonate which service account. Service account roles: decide what the impersonated account can do. Use one account per layer. A pull request from a fork has a different sub and repository, and should never match a production binding.

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.

Production use. Define the pool, provider, service accounts and bindings in the bootstrap layer of your Terraform (Hour 7). Everything in this tab is the manual equivalent, useful for learning and for an emergency rebuild.

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.

  1. Set variables.
    export PROJECT_ID=PROJECT_ID
    export PROJECT_NUMBER=$(gcloud projects describe $PROJECT_ID --format="value(projectNumber)")
    echo $PROJECT_NUMBER
    123456789012
  2. 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.
  3. 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_ID shows lab-deployer@PROJECT_ID.iam.gserviceaccount.com.
  4. 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.
  5. 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)" prints ACTIVE.
  6. 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 the providers describe command; the output must show your condition in attributeCondition:
    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'
  7. Bind the repository to the service account with roles/iam.workloadIdentityUser, using the principalSet:// form with attribute.repository/GITHUB_ORG/REPO_NAME and 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 /*.
  8. 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_REPO and check the policy output of step 7 again: this principal does not appear, so it has no path to the account.
  9. (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 auth step must succeed and the gcloud auth list step must show the service account. Then change the condition to a different repository name with gcloud iam workload-identity-pools providers update-oidc (check --help for 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.disableServiceAccountKeyCreation at 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 plan and apply. 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 (only refs/heads/main via 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 sub claim, 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.com and iamcredentials.googleapis.com show which subject obtained which service account token.
Security notes. (1) Never create a key to "work around" a federation problem; fix the condition or binding. (2) Do not trust self-hosted runners that other teams can use, since any job on them can request the same token. (3) Treat the pool project like a security project: restrict who can create or edit providers, because a new provider with a loose condition is a back door. (4) Disable iam.disableServiceAccountKeyCreation exceptions with a reviewed process.

Symptoms and first checks

SymptomLikely causeFirst check
unable to get OIDC token or ACTIONS_ID_TOKEN_REQUEST_URL empty in the auth stepWorkflow lacks permissions: id-token: write (at the workflow or job level), or the job runs from a fork with restricted tokensOpen the workflow file and the run summary; confirm the permissions block applies to this job
The given credential is rejected by the attribute conditionThe 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' deniedNo roles/iam.workloadIdentityUser for this principal on the service account, or the member string is wronggcloud iam service-accounts get-iam-policy SA_EMAIL; verify project number and attribute path
Identity Pool does not exist or The audience ... is invalidProvider path typo, project ID used where the number is needed, or pool deletedgcloud iam workload-identity-pools describe POOL --location=global
API [sts.googleapis.com] not enabled or iamcredentials.googleapis.com disabledRequired APIs are not enabled in the project that hosts the service accountgcloud services list --enabled --filter="name:(sts OR iamcredentials)"
Auth succeeds, later step returns 403The 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 transferBindings and conditions use the old repository nameCompare the current repository claim in the run with the binding; update both

Triage order

  1. Which step failed: token request (GitHub), exchange (STS, trust decision), impersonation (IAM Credentials, permission decision), or the target API?
  2. Read the exact error text; each stage has a distinct message, as in the table.
  3. Compare the claims in the token (repository, ref, sub) with the condition and the member string, character by character.
  4. Check the project number, pool ID and provider ID in the resource name.
  5. Check that APIs are enabled and that the organization policy does not block federation to that provider type (some organizations restrict external identity providers).
  6. 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.

Official reading: Workload Identity Federation · Federation with deployment pipelines · google-github-actions/auth.

or score ≥ 70% on the quiz

Module 6 · Groups, privileged access and access reviews

36–43 · Grant roles to groups, make powerful access temporary, and review who has what on a schedule
Group-based accessPrivileged Access ManagerAccess reviews7 min
Learning objectives
  • 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 example gcp-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.com API 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 SetIamPolicy call: 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

SituationPreferred approach
Day-to-day read access for a teamA group bound to a predefined viewer role on the folder or project
A role that can change network, IAM or billing in productionPAM entitlement with approval, short duration and justification
Emergency access when identity is brokenBreak-glass accounts (Hour 1), monitored and tested, not PAM
Contractors and short projectsA dedicated group with a membership expiry, plus a review date
AutomationService accounts and Workload Identity Federation (Module 5), not user accounts

What it is confused with

MechanismWhat it doesNot to be confused with
IAM ConditionsAdds a rule (time, resource name, tag) to a bindingPAM, which uses conditions internally but adds requests, approvals and a lifecycle
PAMTemporary, requestable and auditable accessBreak-glass accounts, which exist for when the normal path is unavailable
Google Groups for accessPeople and group nestingGoogle Cloud IAM, which decides what the group may do
IAM RecommenderSuggestions from observed usePolicy Troubleshooter, which explains one specific allow or deny
Access reviewProcess with evidenceAn audit log, which is only one data source of the process

Common misunderstandings

"A group binding is slower to review than a user binding." It is the opposite for the policy, but you must also review who is in the group. A group with fifty members and Owner on the organization is not better than fifty Owner bindings.
"PAM stops all standing privilege." It only controls roles that you put under entitlements. If the same people still hold the role through a group, the entitlement adds nothing. The plan must include removing the permanent binding.
"Recommender will clean up by itself." It does not apply changes. Treat the output like a pull request: read it, test the impact, then apply it through Terraform or a controlled command.
Joiner HR process Cloud Identity user account gcp-prod-viewers group (membership) roles/viewer predefined role Folder: prod all projects below The binding is created once: group:gcp-prod-viewers@example.com + roles/viewer on folders/FOLDER_ID. Joiner: add to the group. Mover: change groups. Leaver: disable the account, memberships end with it. The IAM policy does not change when people change. Reviews look at group membership and at group bindings. Anyone who can edit the group's membership can grant its privilege, so protect group management.

Figure 1. Access is a path: person, group, role, resource. Only the first two links change often.

Request justification Approval 1..n approvers Active temporary binding Expired binding removed Audit log + justification An entitlement defines: eligible principals, roles, maximum duration, approval rules, notifications. The permanent binding for the same role must be removed, otherwise the entitlement protects nothing. Every state change is recorded, so a reviewer can answer who asked, who approved, why, and for how long. Break-glass accounts remain outside PAM, because PAM depends on identity and IAM being available. Use short durations: minutes to a few hours, matched to the task.

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.

  1. Export the policy. gcloud projects get-iam-policy PROJECT_ID --format=json > policy.json. Verify: grep -c '"role"' policy.json prints a number greater than zero.
  2. 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.
  3. 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, run gcloud identity groups memberships list --group-email=GROUP_EMAIL if you can read it. Verify: you can name every member of each group.
  4. Check privileged roles. Filter for roles/owner, roles/editor and any role with admin in 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.
  5. 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.
  6. Read the audit trail. Run the gcloud logging read command for SetIamPolicy over 30 days. Verify: each change has a named principal, and each of them is expected.
  7. 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-policy filter 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.

Optional extension. If your organization has Privileged Access Manager enabled in a sandbox, create one entitlement for 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.
Security notes. (1) Do not let a group be both the approver and the requester in PAM. (2) Treat the right to manage group membership as a privileged role. (3) Do not store exported IAM policies in public places; they list your people and your structure. (4) Do not grant roles/owner to a group as a shortcut; use predefined roles for the function.

Symptoms and first checks

SymptomLikely causeFirst check
A user was added to a group but still gets PERMISSION_DENIEDMembership propagation delay, or the binding is on a different resource or roleWait a few minutes, then run the Policy Troubleshooter for the user and permission
A group binding exists, but the user is not grantedThe user is a member of a nested group that is not allowed, or the membership is pending or disabledgcloud 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 approveDescribe the entitlement and check approval workflow and approver principals
PAM grant is active but the user is still deniedPropagation delay, or a deny policy or condition blocks the actionPolicy Troubleshooter with the exact permission and resource
Recommender returns nothingProject too new, API not enabled, or no data for the periodCheck API and project age; repeat later
search-all-iam-policies returns an empty list for a known bindingWrong scope, missing cloudasset.assets.searchAllIamPolicies permission, or index delayCheck scope and permission; run gcloud projects get-iam-policy to confirm
Cannot see the change that removed a roleAdmin Activity log read in the wrong project or with the wrong log nameUse the log name of the project where the policy lives, or the organization or folder name

Triage order

  1. Is the principal in the group right now (membership state and type)?
  2. Is the group bound to the role on a resource that is an ancestor of the target?
  3. Is the PAM grant in state active, and for which role and condition?
  4. Is anything denying the action (deny policy, Organization Policy, VPC Service Controls)?
  5. 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.

Official reading: Using IAM securely · IAM Recommender overview · IAM audit logging.

or score ≥ 70% on the quiz

Module 7 · Lab: least-privilege platform team

43–53 · Build a custom role, a group binding and an impersonated service account, then prove what is allowed and what is denied
Hands-on labCustom roleImpersonationPolicy Troubleshooter10 min
Learning objectives
  • 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

ElementChoiceWhy
ScopeOne sandbox project PROJECT_IDNo organization permissions needed; deletion is easy
RoleCustom role platformNetViewer with compute.networks.get, compute.networks.list, compute.subnetworks.get, compute.subnetworks.listThe task is "inspect network configuration", which does not need write or instance permissions
Human accessThe group GROUP_EMAIL gets the custom roleGroup-based access (Module 6)
AutomationService account lab-netview gets the same rolePipelines act as a service account, not as a person (Module 4)
Test methodImpersonation with --impersonate-service-accountProves the account's permissions without a key file
ProofOne allowed call, one denied call, one troubleshooter resultEvidence, not belief

Expected results matrix

Action as lab-netviewPermissionExpected
gcloud compute networks listcompute.networks.listAllowed
gcloud compute networks subnets listcompute.subnetworks.listAllowed
gcloud compute instances listcompute.instances.listDenied (403)
gcloud compute networks create democompute.networks.createDenied (403)
gcloud storage buckets liststorage.buckets.listDenied (403)

Where people go wrong

Testing as yourself. If you test with your own account you may be Owner and see everything allowed. The test must run as the service account, or as a user who has only the group role.
Skipping the negative test. A permission model is only proven when something is denied. Always include at least one denied call in an acceptance test.
Propagation. IAM changes usually take effect within seconds, but can take a few minutes to be consistent everywhere. If the first call fails right after a binding, wait one minute and retry before you change anything.

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 GA in most examples; use ALPHA or BETA only to signal that you are still testing, and DISABLED to turn off a role without deleting it.
Platform engineer member of GROUP_EMAIL Group GROUP_EMAIL Custom role platformNetViewer 4 compute network permissions Service account lab-netview@PROJECT_ID Project PROJECT_ID networks: allowed subnets: allowed instances: denied buckets: denied Group: roles/iam.serviceAccountTokenCreator on the service account (may impersonate it). Both the group and the service account hold the custom role on the project. Nothing else is granted.

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.

Call fails 403 or denied Expected? in the matrix Yes: pass record as proof No: troubleshoot which step failed? policy-troubleshoot fix binding, retest An expected denial is a pass. An unexpected denial means a missing permission, a wrong principal or a wrong scope. An unexpected allow is worse: find which broader binding gives it, usually a basic role on a parent.

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_ID linked 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_EMAIL that you can add yourself to and that your organization policy allows. If you have no group, use user:USER_EMAIL (your own address) wherever the lab says group:GROUP_EMAIL; the model is the same.
  • No secrets, and no key files. IDs in the expected output are illustrative.
  1. 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 prints True. If it prints False, link billing before you continue.
  2. Enable the APIs with the gcloud services enable command 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.
  3. 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
  4. 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).
  5. Bind the custom role to the service account and to the group (two add-iam-policy-binding commands). 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.
  6. Allow the group to impersonate the service account with roles/iam.serviceAccountTokenCreator on the account. Verify: gcloud iam service-accounts get-iam-policy lab-netview@$PROJECT_ID.iam.gserviceaccount.com lists the group with that role. Wait one minute for propagation.
  7. Allowed call. Run gcloud compute networks list --impersonate-service-account=... (see the commands tab). Expected: the warning about impersonation and a table, or Listed 0 items..
  8. Subnet call. gcloud compute networks subnets list --impersonate-service-account=.... Expected: allowed (maybe a long default list). This confirms the second pair of permissions.
  9. 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.
  10. Explain it. Run the gcloud policy-troubleshoot iam command for compute.instances.list and then for compute.networks.list. Expected: NOT_GRANTED for the first and GRANTED for the second, the latter naming the binding with platformNetViewer.
  11. Optional: a human test. Add yourself to the group (or use your own user). Wait a minute. Run gcloud compute networks list without 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.
Security notes. (1) 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

SymptomLikely causeFirst check
Permission 'iam.serviceAccounts.getAccessToken' denied on the first impersonated callThe caller lacks token creator on the service account, or the binding has not propagatedgcloud iam service-accounts get-iam-policy SA_EMAIL; retry after a minute
API [iamcredentials.googleapis.com] not enabledIAM Credentials API not enabled in the projectgcloud services enable iamcredentials.googleapis.com
compute.networks.list is also denied for the service accountThe 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 allowedA broader role, for example roles/editor, granted to the account directly or inherited from a foldergcloud policy-troubleshoot iam and look at the bindings listed under it
Role ... not found or INVALID_ARGUMENT when binding the custom roleShort role ID used instead of projects/PROJECT_ID/roles/ROLE_IDgcloud iam roles list --project=PROJECT_ID
Compute Engine API has not been used or billing requiredCompute API not enabled, or the project has no billing accountgcloud billing projects describe PROJECT_ID
Cannot re-create platformNetViewer after cleanupDeleted role ID is reserved for a periodUse a new ID, or undelete the role

Triage order

  1. Which principal is actually making the call (look for the impersonation warning)?
  2. Does that principal have a binding with the permission, on the project or an ancestor?
  3. Does the caller have token creator on the service account?
  4. Is the API enabled and billing linked?
  5. 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.

Official reading: Create and manage custom roles · Service account impersonation · Policy Troubleshooter.

or score ≥ 70% on the quiz

Module 8 · Troubleshooting "permission denied"

53–60 · A fixed triage order for 403 errors: identity, permission, scope, deny, API, conditions and propagation
PERMISSION_DENIEDPolicy TroubleshooterTriage order7 min
Learning objectives
  • Apply a fixed triage order to any PERMISSION_DENIED or 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-policy and gcloud logging read to 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

  1. 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.
  2. 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").
  3. 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.
  4. 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.
  5. 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_PRECONDITION with 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

#CauseTypical clue in the error or the policyFix
1Wrong principal: the call is made as a different account than you thinkgcloud auth list shows another ACTIVE account; an --impersonate-service-account flag or config is set; ADC differs from gcloud loginSwitch account, unset impersonation, or fix the pipeline identity
2Missing permission or wrong scopeThe error names the permission; the role is bound on a sibling project, or on a resource that is not an ancestorBind a suitable role on the right resource or ancestor
3Wrong principal type in the bindingBinding uses user: for a service account or group, a typo in the email, or a group the user is not inCorrect the member prefix (user:, group:, serviceAccount:, principalSet:) and the address
4Deny policyThe binding exists, but the Troubleshooter reports a deny; or the error mentions a deny policyReview the deny rule and its exceptions; change it through the owner of the policy
5API not enabledSERVICE_DISABLED or "has not been used in project N before or it is disabled"Enable the API in the correct (quota) project
6Expired or unmet conditionBinding contains a condition with a past request.time, or a resource-name or tag condition that does not matchRenew, correct or remove the condition deliberately
+Propagation delayThe change is minutes old, and the first call fails, a later call worksWait 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

ErrorLooks likeReally means
SERVICE_DISABLED or "API has not been used"Permission deniedEnable the API in the project
FAILED_PRECONDITION mentioning constraints/...Permission deniedOrganization Policy blocks the operation, even for Owner (Hour 3)
"Request is prohibited by organization's policy" with vpcServiceControlsUniqueIdentifierPermission deniedVPC Service Controls perimeter (Hour 3)
NOT_FOUND or "or it may not exist"Resource missingCan also mean the caller cannot see the resource at all; check permissions to get it
401 UNAUTHENTICATED or "invalid_grant"DeniedCredentials expired or invalid; log in again or fix federation (Module 5)
RESOURCE_EXHAUSTED or 429DeniedQuota or rate limit; unrelated to IAM

Common misunderstandings

"I have Owner, so it must be a bug." Owner is an allow role. It does not override a deny policy, an Organization Policy constraint or a VPC Service Controls perimeter, and it does not enable APIs for you in every case.
"The group has the role, so every member has it." Only members whose membership is active, who are in the right group (not a similar-named one), and whose account is not suspended. Check the membership list.
"Add a bigger role to see if it works." That tells you nothing about the cause and leaves the larger role behind. Ask the Troubleshooter which permission is missing, and add the smallest role that includes it.
1 Who is calling? gcloud auth list · impersonation · ADC 2 Which permission? read it in the error text 3 API enabled? SERVICE_DISABLED means no 4 Binding present? member type · role · scope 5 Condition true? expiry · resource name · tag 6 Deny policy? evaluated before allow 7 Other guardrails? Organization Policy · VPC Service Controls 8 Propagation wait a few minutes, retry once Prove each step before you change anything: gcloud policy-troubleshoot iam RESOURCE --principal-email=EMAIL --permission=PERMISSION gcloud logging read 'protoPayload.status.code=7' --freshness=1h (find the exact denied call) gcloud projects get-iam-policy PROJECT_ID --flatten=... --filter=... (find the binding) Then change one thing, wait, retest the same call, and record the cause in the ticket.

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.

Deny policies org · folder · project any match: denied Allow policies resource + all ancestors (union) member · role · condition true Result allowed only if no deny and at least one allow matches Allow policies are additive: a binding on a parent cannot be removed by a child, only blocked by a deny. A conditional binding that is false grants nothing but still shows in the policy. Organization Policy and VPC Service Controls are separate checks that can fail even when IAM allows. So "I see the role in the policy" is never enough proof; ask the Troubleshooter.

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.

  1. 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.
  2. 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.
  3. 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 a SERVICE_DISABLED message (the API check can come before IAM) or PERMISSION_DENIED naming pubsub.topics.list. Note which one you get; both are valid lessons. Then run the troubleshooter for pubsub.topics.list and the service account: NOT_GRANTED.
  4. 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.
  5. Failure 2: API disabled. The list command still fails, now clearly with SERVICE_DISABLED and 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.
  6. Fix the API. gcloud services enable pubsub.googleapis.com --project=$PROJECT_ID. Rerun the list command. Expected: Listed 0 items..
  7. 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 the get-iam-policy filter 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.
  8. Find it in the log. Run the gcloud logging read 'protoPayload.status.code=7' --freshness=1h command. 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.
  9. 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 denied after a repository was renamed. The federation binding still used the old repository name. The team found it with the exact error text, compared the repository claim 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.viewer at 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.
Security notes. (1) Do not respond to a denied pipeline by granting Owner or Editor. (2) Do not create service account keys to get around identity problems. (3) Treat a sudden increase of 403 errors for one principal as a possible security event, not only a configuration error. (4) Remove temporary diagnostic access when the incident closes.

Symptoms and first checks

SymptomLikely causeFirst check
Works in the console, fails in Terraform or CIDifferent principal: the pipeline's service account, or ADC differs from gcloud loginPrint identity at the start of the job; gcloud auth list; the provider's credentials
Fails right after granting the rolePropagation delayWait two minutes; retry the same call once
Role is visible in the project policy, still deniedRole granted to a different project or resource, a group the user is not in, or a false conditiongcloud 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 projectProject number in the message; gcloud services list --enabled
Owner denied on a specific actionDeny policy, Organization Policy constraint or VPC Service ControlsError text (constraints/, VPC-SC identifier), then gcloud iam policies list
Access ended without any change in the policyConditional binding with an expiry date, or a PAM grant that endedget-iam-policy with condition columns; PAM grant state
iam.serviceAccounts.actAs denied when attaching a service account to a resourceCaller lacks roles/iam.serviceAccountUser on that service accountBind it on the service account itself, not on the project, when you can
Cross-project call fails but both projects have rolesService account lives in project A but needs roles in B; or Shared VPC and quota project differCheck where the service account and the target resources live; check bindings in the target project

Triage order (the whole module in eight lines)

  1. Name the principal and the permission from the error.
  2. Confirm the identity (gcloud auth list, impersonation, ADC).
  3. Confirm the API is enabled in the project that receives the request.
  4. Check bindings for that principal on the resource and its ancestors (member type, role, scope).
  5. Check conditions and expiry.
  6. Check deny policies, then Organization Policy and VPC Service Controls.
  7. If the change is minutes old, wait and retry once.
  8. 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.

Official reading: Troubleshoot permissions · Deny policies · IAM Conditions overview.

or score ≥ 70% on the quiz

Command cheat sheet

Identity and access management (IAM)
Hour 2

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)

CommandPurposeKey flagsGotcha
gcloud auth listShows which account is activenoneApplication Default Credentials (Terraform, client libraries) are separate from this login
gcloud config listShows project, account and auth/impersonate_service_accountnoneAn impersonation property silently changes the identity of every command
gcloud projects get-iam-policy PROJECT_IDPrints 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_IDPrints a folder's allow policysame as aboveNeeds permission on the folder
gcloud organizations get-iam-policy ORG_IDPrints the organization's allow policysame as aboveLarge output; always filter
gcloud policy-troubleshoot iam RESOURCEExplains whether a principal has a permission on a resource--principal-email, --permissionRESOURCE is the full resource name, for example //cloudresourcemanager.googleapis.com/projects/PROJECT_ID; enable policytroubleshooter.googleapis.com
gcloud iam policies listLists 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 --enabledConfirms 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, --formatData Access logs may be off; an empty result does not prove there was no denial

Roles and bindings (write, free)

CommandPurposeKey flagsGotcha
gcloud iam roles listLists predefined or custom roles--project or --organization, --show-deletedWithout a scope it lists predefined roles only
gcloud iam roles describe ROLEShows permissions of a role--project for custom rolesCustom roles need the full name projects/PROJECT_ID/roles/ROLE_ID when bound
gcloud iam roles create ROLE_IDCreates a custom role--project, --title, --permissions, --stageCustom roles do not receive new permissions automatically; some permissions cannot be used in custom roles
gcloud iam roles delete ROLE_IDSoft-deletes a custom role--projectThe ID stays reserved for a period; remove bindings first
gcloud projects add-iam-policy-binding PROJECT_IDAdds one member-role binding--member, --role, --condition or --condition=NoneMember prefix must match the type: user:, group:, serviceAccount:, principalSet:
gcloud projects remove-iam-policy-binding PROJECT_IDRemoves one bindingsame flagsWith conditional bindings you must pass the same condition, or the binding stays
gcloud iam service-accounts create NAMECreates a service account--project, --display-nameName is 6 to 30 characters; creating the account grants it no roles
gcloud iam service-accounts add-iam-policy-binding SA_EMAILGrants access ON a service account (who may use it)--member, --roleserviceAccountTokenCreator is impersonation; serviceAccountUser is attach; do not mix them up

Impersonation and keyless access

CommandPurposeKey flagsGotcha
gcloud COMMAND --impersonate-service-account=SA_EMAILRuns one command as a service account, with no keythe flag itselfThe caller needs iam.serviceAccounts.getAccessToken on the account; enable iamcredentials.googleapis.com
gcloud config set auth/impersonate_service_account SA_EMAILImpersonates for all later commandspropertyEasy to forget; unset it with gcloud config unset auth/impersonate_service_account
gcloud iam workload-identity-pools create POOL_IDCreates a Workload Identity pool--location=global, --display-name, --projectPool IDs of deleted pools stay reserved for a period
gcloud iam workload-identity-pools providers create-oidc PROVIDER_IDCreates an OIDC provider (for example GitHub)--workload-identity-pool, --issuer-uri, --attribute-mapping, --attribute-conditionAlways set an attribute condition; google.subject is required in the mapping
gcloud iam workload-identity-pools providers describe PROVIDER_IDPrints 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.workloadIdentityUserLets 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-configGenerates a credential configuration file (no secret in it) for non-GitHub sourcesdepends on source typeFlags differ by source (AWS, Azure, URL, file); check --help

Groups, review and privileged access

CommandPurposeKey flagsGotcha
gcloud identity groups memberships listLists members of a group--group-emailNeeds cloudidentity.googleapis.com and permission to read the group
gcloud identity groups memberships addAdds a member to a group--group-email, --member-emailPrefer changing groups from your identity provider or reviewed automation
gcloud asset search-all-iam-policiesFinds bindings across a scope--scope, --query="policy:EMAIL"Needs cloudasset.googleapis.com; index can lag slightly
gcloud asset analyze-iam-policyAnalyses effective access of an identity or on a resource--organization, --identity, --full-resource-nameOutput can be large; check --help for group and role expansion flags
gcloud recommender recommendations listLists IAM Recommender suggestions--recommender=google.iam.policy.Recommender, --location=global, --projectEmpty for new projects; suggestions are not applied automatically
gcloud pam entitlements listLists Privileged Access Manager entitlements--project, --location=globalEnable privilegedaccessmanager.googleapis.com; check gcloud pam --help for your SDK
gcloud pam grants createRequests a time-limited grant--entitlement, --requested-duration, --justificationThe grant exists only between approval and expiry; remove the standing binding too

Conditions snippets

GoalCondition expression (CEL)Gotcha
Expire a bindingrequest.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 prefixresource.name.startsWith('projects/_/buckets/lab-')Only certain services support resource-name conditions
Limit by tagresource.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

Identity and access management (IAM)
Hour 2

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_EMAIL you can add yourself to, or your own address USER_EMAIL in its place.
  • Optional: a private GitHub repository GITHUB_ORG/REPO_NAME you control, for step 10.
  • Cloud Shell or a terminal with the gcloud CLI (current release channel). No key files and no secrets.

Steps

  1. 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 prints True and echo $PROJECT_NUMBER prints a 12-digit number.
  2. 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.
  3. 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.
  4. 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.
  5. 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.com lists the group with roles/iam.serviceAccountTokenCreator. Wait one to two minutes.
  6. 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 prints Listed 0 items.) and the second is denied for compute.instances.list. If the second succeeds, find the broader role with step 7.
  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 prints access: GRANTED (naming the custom role binding), the second access: NOT_GRANTED.
  8. 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 a principalSet member ending in your repository, not /*.
  9. 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-pipeline and the group) must not appear in the broad-role list.
  10. (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_ID
    Verify: 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

SymptomLikely causeFirst check
Impersonated call: iam.serviceAccounts.getAccessToken deniedMissing token creator binding or propagationStep 5 verification; wait two minutes
Network call denied for the service accountCustom role not bound, or wrong member prefixStep 4 verification
The given credential is rejected by the attribute conditionRepository name in condition does not match the runProvider attributeCondition and the repository path
API ... has not been used in projectAPI not enabledStep 2 verification
Identity Pool does not existProject ID used where the number is requiredecho $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.

Next step. Put these resources in Terraform (Hour 7) and let the organization policy iam.disableServiceAccountKeyCreation (Hour 3) guarantee that nobody falls back to key files.

Knowledge check

Sources and versions

Identity and access management (IAM)
Hour 2

Official documentation used in Hour 2

TopicReference
IAM overviewIdentity and Access Management overview
Roles and permissionsRoles and permissions · Understanding roles (reference)
Custom rolesCreate and manage custom roles
Allow policies and inheritanceAllow policies · Resource hierarchy
IAM ConditionsIAM Conditions overview
Deny policiesDeny policies
Service accountsService accounts overview · Best practices for using and managing service accounts
ImpersonationService account impersonation
Workload Identity FederationWorkload Identity Federation · Federation with deployment pipelines (GitHub, GitLab)
GitHub Actions authenticationgoogle-github-actions/auth · google-github-actions/setup-gcloud
Policy TroubleshooterTroubleshoot access with Policy Troubleshooter
IAM Recommender and Policy IntelligencePolicy Intelligence overview · IAM Recommender overview
Privileged Access ManagerPrivileged Access Manager overview
Audit logsIAM audit logging · Cloud Audit Logs overview
Using IAM securelyUsing IAM securely
Landing zone contextEnterprise foundations blueprint (security foundations) · terraform-example-foundation
gcloud referencegcloud iam · gcloud policy-troubleshoot iam · gcloud asset

Tools and versions used

ToolVersion used in the courseNote
Google Cloud CLI (gcloud)current release channelCheck 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 Shellmanaged by GoogleAlways has a current gcloud and is free of key files
google-github-actions/authcurrent 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-gcloudcurrent major version (the examples use v2)Used only to install the CLI in a job
Terraform (for later hours)1.x with the Google providerPin the major version in required_providers
Google Cloud APIsiam, iamcredentials, sts, cloudresourcemanager, policytroubleshooter, cloudasset, recommender, cloudidentity, privilegedaccessmanagerEnabling an API is free; enable only what the lab needs
Check before production use. Flags, role names, command groups and product limits change. Every command in this course was written from the documented form, and where a flag could differ between SDK versions the text says to run 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.disableServiceAccountKeyCreation and iam.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.