Prepare and test your skills

Prepare and test your skills

An allow policy is a YAML or JSON object attached to a Google Cloud resource that grants access through role bindings. Each role binding connects three parts: a principal, a role, and the resource where the policy is attached. A principal is an authenticated identity such as a user, Google group, service account (opens in a new tab), or federated identity, a role is a collection of permissions in the form service.resource.verb such as pubsub.topics.publish, and the resource is the project, folder, organization, or service resource.
When a principal calls an API, Identity and Access Management (IAM) checks the allow policy on the target resource and on its ancestors in the resource hierarchy (opens in a new tab). The hierarchy flows from organization at the root, to folders, to projects, to service resources such as Compute Engine instances, Pub/Sub topics, and Cloud Storage buckets. If a binding includes both the principal and a role with the required permission, the request is allowed. Permissions are never granted directly, so a principal receives permissions only by being included in a role binding.
Policy inheritance means a grant on a parent also applies to every descendant resource. Effective permissions are the union of the resource policy plus all inherited parent policies, so a child policy adds access but never removes access granted higher up. For example, granting Logs Bucket Writer (roles/logging.bucketWriter) on a project allows writing to a log bucket inside it, even when the bucket has no policy of its own.
A hierarchy from organization to folder to project to service resources showing that a grant on a parent flows to all descendants and effective permissions are the union of direct and inherited policies.
Viewing effective access means looking at both direct grants on a resource and inherited grants from its ancestors. The Google Cloud console IAM page shows effective access in list form for a selected project, folder, or organization, including principals who inherit roles from parents. To see role grants for Google-managed service agents, select the Include Google-provided role grants checkbox.
The gcloud CLI get-iam-policy command shows only the direct policy on one resource, not inherited roles. The command has the form gcloud RESOURCE_TYPE get-iam-policy RESOURCE_ID --format=FORMAT > PATH, where FORMAT is json or yaml. For example, gcloud projects get-iam-policy my-project --format=json > ~/policy.json saves the direct policy for my-project. The resource type and ID values differ by level:
| Level | Resource type value | ID format |
|---|---|---|
| Project | projects | Alphanumeric, like my-project |
| Folder | resource-manager folders | Numeric, like 123456789012 |
| Organization | organizations | Numeric, like 123456789012 |
Viewing requires getIamPolicy permission and changing requires setIamPolicy permission at the same level, such as resourcemanager.projects.getIamPolicy and resourcemanager.projects.setIamPolicy. Inherited roles cannot be edited at the child level and must be changed where they were granted. To see complete access, review the resource policy plus the parent project, folder, and organization policies, which requires getIamPolicy on each ancestor.
Exam tip: The console IAM list includes inherited roles, while gcloud get-iam-policy shows only the direct policy on that resource.
Policy Analyzer is the auditing tool that verifies which principals have what access to which resources across the hierarchy. Policy Analyzer depends on the Cloud Asset API, so analysis starts by enabling cloudasset.googleapis.com. It can be used in the console, through APIs, or by exporting results to BigQuery for large or periodic compliance reviews.
Policy Analyzer answers questions such as:
To certify access for one user, follow an ordered workflow where each step depends on the previous one:
cloudasset.googleapis.com for the project because Policy Analyzer depends on it.gcloud asset analyze-iam-policy --organization="YOUR_ORG_ID" --identity="user:USERNAME_TO_CERTIFY".Cloud Audit Logs record how access changes over time and support compliance review. Every setIamPolicy() call is logged, group membership changes appear in Activity logs, and service account creation appears with methods such as google.iam.admin.v1.CreateServiceAccount and google.iam.admin.v1.CreateServiceAccountKey. Just-in-time privileged access with Privileged Access Manager (PAM) lets principals request elevated access only when needed, creates an audit trail for why access was activated, and supports expiration and periodic review. Revoking access typically takes effect in about a minute, although metadata updates appear immediately.
Basic, predefined, and custom roles differ in breadth of access, who manages them, and when to choose them. Basic roles grant broad access across many Google Cloud resources, such as Owner (roles/owner), and do not follow least privilege. Predefined roles are granular roles managed by Google Cloud for a specific service and job, such as Pub/Sub Publisher (roles/pubsub.publisher). Custom roles are granular roles you define with only the permissions you list.
| Role type | Who defines permissions | Scope of access |
|---|---|---|
| Basic roles | Google Cloud | Broad access across many Google Cloud resources |
| Predefined roles | Google Cloud | Granular access for a specific service and common use case |
| Custom roles | You, from a user-specified permission list | Tailored access limited to the organization or project where created |
Predefined roles are preferred when one matches the task because Google Cloud maintains them and can add new permissions as services grow. Custom roles are useful when predefined roles are too broad, too narrow, or must stay unchanged over time, because Google Cloud does not automatically add permissions to a custom role. Basic roles are useful for testing or development but should not be used in production unless there is no alternative.
A custom role definition is the set of fields that identify the role, describe its purpose, and control its behavior. The title is the human-readable name in the console, the name is the full identifier used in allow policies such as projects/PROJECT_ID/roles/IDENTIFIER, and the ID is the unique part after roles/ that cannot be changed after creation. Other fields include description, stage, permissions list, and ETag:
roles/ in the name, which is immutable after creation.SERVICE.RESOURCE.VERB format.Selecting permissions for least privilege means using only permissions supported in custom roles and valid at the role scope. An organization-level custom role can include any supported permission, while a project-level custom role cannot include permissions that only work at organization or folder level, such as resourcemanager.organizations.get. Each custom role can contain up to 3,000 permissions, and the combined size of title, description, and permission names cannot exceed 64 KB. A custom role can only be granted within the same organization or project where it was created, and custom roles cannot be defined at the folder level.
To create a custom role from scratch in the console, follow this order:
Managing project roles requires Role Administrator (roles/iam.roleAdmin) on that project, while managing organization roles requires Organization Role Administrator (roles/iam.organizationRoleAdmin). Granting roles with least privilege means placing each grant at the lowest resource level that still lets the workload succeed. A role granted on an organization, folder, or project is inherited by all descendant resources, while a grant on one dataset, table, topic, or virtual machine (VM) instance limits access to only that resource. Programmatic changes follow a read-modify-write order: get the current allow policy with getIamPolicy, modify bindings locally, then write it back with setIamPolicy, while quick single grants can use add-iam-policy-binding and removals can use remove-iam-policy-binding.
Continue with this study guide: 4.1 Managing Identity and Access Management (IAM)
A service account (opens in a new tab) in Google Cloud is both a principal that can be granted access and a resource that belongs to a project and must be protected. As a principal, the service account can receive Identity and Access Management (IAM) roles on resources such as a Cloud Storage bucket or a project. As a resource, the service account has its own allow policy that controls who can impersonate it, attach it to resources, or manage it. Service accounts have no password, cannot be used for browser sign-in, and belong to a Google Cloud project.
Because the account has two sides, defense must address both sides together. Because the service account is a principal, its roles must follow least privilege so compromise causes less harm. Because the service account is also a resource, access to impersonate or attach it must be restricted with roles such as Service Account User and Service Account Admin.
Secure creation starts with single-purpose, user-managed accounts and the minimum permissions needed for creation. Permission to create accounts comes from the Create Service Accounts role (roles/iam.serviceAccountCreator) on the project, while granting the new account access to the project also requires the Project IAM Admin role (roles/resourcemanager.projectIamAdmin). The service account ID must be 6 to 30 characters, use only lowercase letters, numbers, and dashes, and cannot be changed after creation. The ID becomes part of the email address in the format SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com, while Google Cloud also assigns a permanent numeric ID that IAM uses internally for role bindings.
Creating a service account in the console follows an ordered workflow that collects identity first and access second:
After creation, wait 60 seconds or more before using the account because reads are eventually consistent, retry with exponential backoff on errors, and check the Service Account Count quota if a project needs many accounts. Use a naming convention such as a vm-, wlif-, or onprem- prefix plus the application name, and use the display name and description for owner, purpose, and documentation links.
Choosing safer authentication means using short-lived, automatically managed credentials instead of creating a downloadable service account key whenever possible. Service account keys are long-lived private keys that let an application sign a JSON Web Token (JWT) and exchange it for an OAuth 2.0 access token in any environment. Because anyone who holds the private key file can authenticate as the service account, a leaked key creates lasting exposure through privilege escalation, spoofing, and hard-to-trace actions.
The following options show where each authentication path applies and how credentials flow from identity to workload:
| Authentication option | Where it applies | How credentials flow |
|---|---|---|
| Attached service account | Code running in Google Cloud on Compute Engine or similar resources | Workload authenticates as the attached account with Google-managed short-lived tokens |
| Workload Identity Federation for GKE | Containers in Google Kubernetes Engine (GKE) | Federation links Kubernetes pods to service accounts without keys |
| Workload Identity Federation | Workloads on-premises or on another cloud | External identity is federated to impersonate a service account |
| Service account impersonation | Single-user development on a workstation or Cloud Shell | Developer signs in as a user, then impersonates the account temporarily |
| Service account key | Only when no federated or attached option works | App uses the downloaded key to sign a JWT and must secure the key |
The Google Cloud CLI creates the same account with gcloud iam service-accounts create SERVICE_ACCOUNT_NAME --display-name="DISPLAY_NAME" --description="DESCRIPTION", followed by gcloud projects add-iam-policy-binding to grant each project role. Attachment to Compute Engine then lets code on the virtual machine (VM) call APIs as that identity, subject to both IAM roles and access scopes.
Exam tip: Service account keys are the last choice; if key creation fails, key creation is likely disabled by organization policy and you should use an attached service account or Workload Identity Federation instead.
Using service accounts in IAM policies with minimum permissions means giving a workload identity only the permissions it needs at the lowest resource level that still works. Every request follows the same relationship: a principal requests an operation on a resource, IAM checks whether an allow policy grants that principal a role with the required permission, and IAM allows the action only when the permission is present. Roles differ in breadth and maintenance, so choosing the right type controls blast radius when code or credentials are compromised.
Choosing the smallest IAM role starts by listing required permissions and flagging high-risk permissions for extra review. High-risk permissions include creating and deleting resources, accessing sensitive data such as encryption keys, setting allow or deny policies, and updating organizations, folders, and projects. Low-risk permissions include listing resources, reading non-sensitive data, and updating limited settings such as minimum CPU platform. After identifying permissions, search the IAM roles and permissions index for each permission to build a short list of predefined roles that contain it.
First eliminate basic roles and service-agent roles whose names end in serviceAgent, because service-agent roles are intended for Google-managed accounts and often span unneeded services. Then compare the remaining predefined roles and prefer service-level Admin, Editor, and Viewer roles that match the use case, or the role with the fewest permissions for strict least privilege. Create a custom role when every predefined role that contains a needed permission also contains unwanted permissions, remembering that custom roles hold up to 3,000 permissions, cannot be defined at the folder level, and do not gain new permissions automatically. In production, grant only the most limited predefined role or custom role that meets the workload need and reserve basic roles for test or development.
Where to grant roles in the hierarchy determines how broadly a service account can act, because child resources inherit allow policies from their parents. Granting a role on a project therefore implicitly grants it on every VM in that project, while granting Publisher on one Pub/Sub topic limits access to that topic. Least privilege narrows scope by granting at the smallest level that still lets the workload function, and by validating the change before and after it is applied. Create a separate service account for each application component as its own trust boundary, avoid basic roles in production, and use role recommendations, Policy Analyzer, Policy Troubleshooter, and Policy Simulator to verify the effect.
Assigning service accounts to resources gives code running on Google Cloud a workload identity without storing user passwords or long-lived keys. A service account attached to a compute resource becomes the default identity for that resource, so any workload on the resource presents the service account credentials when it calls Google Cloud APIs. IAM then checks the service account permissions, not the developer who deployed the code.
Service account types differ by who creates them, who maintains them, and whether workloads can use them directly:
| Type | Created and managed by | Can be attached to a VM | Intended use |
|---|---|---|---|
| User-managed service account | Created and managed by you | Yes | Dedicated identity for one application with only needed roles |
| Default service account | Created automatically, then managed by you | Yes | Quick start for App Engine or Compute Engine; replace for production |
| Service agent | Created and managed by Google Cloud | No | Lets a Google service act on your behalf for internal processes |
The App Engine default account uses project-id@appspot.gserviceaccount.com and the Compute Engine default uses PROJECT_NUMBER-compute@developer.gserviceaccount.com. Depending on organization policy, a default account might automatically receive the Editor role on the project, so best practice is to disable that grant with the iam.automaticIamGrantsForDefaultServiceAccounts constraint and use dedicated accounts instead. This constraint is enforced by default for organizations created after May 3, 2024.
How attached accounts are authorized depends on two controls that must both allow access: IAM roles on the service account and access scopes on the instance. IAM roles define the maximum permissions available everywhere the account is used, while access scopes define the default OAuth scopes for requests from the gcloud CLI and client libraries on that VM. A narrow scope can block an API even when the IAM role allows it, but a broad scope never adds permissions beyond IAM. Best practice is to set the full cloud-platform scope on the instance and then control access with IAM roles.
Attaching an account securely defines what the identity can access, who can use the identity, and which resource uses it as its default identity. The person who will attach it needs the Service Account User role (roles/iam.serviceAccountUser) with iam.serviceAccounts.actAs on that specific account. For most services the account must be attached when the resource is created, while Compute Engine is the exception that allows attaching or changing the account later. The creation and attachment workflow runs in this order:
gcloud init and sign in, using a federated identity first when required.gcloud iam service-accounts create SERVICE_ACCOUNT_NAME in the project.gcloud projects add-iam-policy-binding with --member="serviceAccount:EMAIL" and --role=ROLE for each needed role.gcloud iam service-accounts add-iam-policy-binding with --member="user:USER_EMAIL" and --role=roles/iam.serviceAccountUser.gcloud compute instances create INSTANCE_NAME --service-account=SERVICE_ACCOUNT_EMAIL or the equivalent creation command for the target service.Managing service account impersonation means letting an authorized identity temporarily act as a service account without sharing passwords or downloading key files. Impersonation always involves two identities: the authenticated principal who starts the request and the target service account that is impersonated. The secure pattern is consistent: the principal first gets a short-lived token for the service account, then uses that token to authenticate as the service account to access what the account can access.
Setting up impersonation for an external workload follows an ordered workflow:
The project needs the IAM, Security Token Service, and Service Account Credentials APIs enabled, and cross-project use requires the organization policy iam.disableCrossProjectServiceAccountUsage to be unenforced. Roles required for impersonation control whether the principal attaches the account or mints tokens directly. The Service Account User role (roles/iam.serviceAccountUser) contains iam.serviceAccounts.actAs and lets a principal attach the account to a resource such as a Compute Engine instance, Cloud Run service, or Cloud Build deployment. The Service Account Token Creator role (roles/iam.serviceAccountTokenCreator) lets a principal create short-lived access tokens to authenticate directly as the account without attaching it.
Short-lived service account credentials are temporary OAuth 2.0 access tokens that prove a service account identity for a short time, by default expiring after 1 hour. The Service Account Credentials API creates them using a Google-owned key pair whose private key is held in escrow and never exposed to users. The API can create OAuth 2.0 access tokens, OpenID Connect (OIDC) ID tokens, self-signed JSON Web Tokens (JWTs), and self-signed binary blobs. User-managed keys are different because the customer holds the private key, each account can have up to 10 keys, and keys have no expiry unless one is configured.
Direct access, impersonation, and keys differ in who acts as principal and where access is granted:
| Access method | Who is the principal on the resource | Where access is granted |
|---|---|---|
| Direct resource access | Federated user from the workload identity pool | Federated principal receives roles on the bucket or resource |
| Service account impersonation | Service account acting as the identity | Service account receives roles on the resource; federated identity receives Workload Identity User on the account |
| Downloaded service account key | Service account using a key file | Service account receives roles on the resource; key file is stored as GOOGLE_APPLICATION_CREDENTIALS |
Expiration, rotation, and revocation limit risk by setting a hard end to how long a stolen credential can be abused. Rotation replaces an existing key with a new key and then invalidates the old key, shrinking the window in which a leak remains valid. Revocation moves a key in order from active to disabled to deleted, where disabling allows fast re-enabling if a dependency appears and deleting is irreversible. Principals obtain short-lived tokens through the gcloud CLI with --impersonate-service-account, through the Service Account Credentials API directly, or through Workload Identity Federation with a credential configuration file.
Using a Google Cloud service account with a GKE application gives pods a Google identity for calling Google Cloud APIs without storing long-lived keys. GKE workloads use two identities together: a Google Cloud service account that IAM recognizes for Google APIs, and a Kubernetes service account that is recognized only inside the cluster. Workload Identity Federation for GKE links the two identities so a pod can act with the Google account permissions.
Kubernetes and Google Cloud identities in GKE divide responsibility by trust boundary. A Kubernetes service account authenticates a pod to the Kubernetes API inside its own cluster without configuring certificates, but it is not recognized by any Google Cloud API. A Google Cloud service account is recognized by Google Cloud APIs and carries IAM roles that control what the workload can read, write, or administer. A workload that only manages cluster objects needs only the first identity, while a workload that reads buckets, writes metrics, or calls other Google APIs also needs the second identity.
How Workload Identity Federation for GKE links identities provides fine-grained, per-application permissions through two access paths. With direct resource access, IAM roles are granted to the Kubernetes service account identity directly on the Google resource, so no intermediate service account is used. With service account impersonation, the Kubernetes ServiceAccount is bound to an IAM service account that serves as the identity for Google API calls, which is the alternative when direct federation is not supported. Secure use favors federation and short-lived tokens over attached node identities and long-lived keys, because a compromised pod does not then expose other applications or the underlying node.
How to configure least-privilege access for GKE workloads links the deployment to the correct Kubernetes identity and grants only required Google roles. Configuring impersonation between the accounts runs in this order:
kubectl create namespace.kubectl create serviceaccount.gcloud iam service-accounts create, or reuse an existing account.roles/spanner.viewer on the target project or resource.roles/iam.workloadIdentityUser on the IAM account for serviceAccount:PROJECT_ID.svc.id.goog[NAMESPACE/KSA_NAME].kubectl annotate serviceaccount with iam.gke.io/gcp-service-account=IAM_SA_NAME@PROJECT_ID.iam.gserviceaccount.com.Then set .spec.serviceAccountName in the Deployment YAML so pods use the linked KSA. If access breaks, a wrong service account name uses the wrong identity, a missing IAM grant causes permission-denied errors, and cluster service account and scope settings cannot be changed after creation.
Continue with this study guide: 4.2 Managing service accounts
get-iam-policy command shows only the direct policy on the requested resource.cloud-platform scope and restricts with IAM roles.The Google Cloud console Identity and Access Management (IAM) list shows effective access including inherited roles, while the gcloud get-iam-policy command shows only the direct policy on the requested resource. Effective permissions are the union of the direct policy plus all grants inherited from parent projects, folders, and organizations, so complete review requires checking the resource policy plus the parent project, folder, and organization policies.
Use a predefined role when one matches the task because Google Cloud maintains predefined roles and can add new permissions as services grow. Use a custom role when every predefined role is too broad, too narrow, or must stay unchanged over time, and reserve basic roles for testing or development because basic roles grant broad access across many resources and do not follow least privilege.
Access from a Compute Engine virtual machine (VM) succeeds only when both the Identity and Access Management (IAM) roles on the attached service account and the virtual machine access scopes allow the request. Identity and Access Management roles define the maximum permissions available everywhere the account is used, while access scopes define the default OAuth scopes for requests from that virtual machine, so a narrow scope can block an API even when the role allows it but a broad scope never adds permissions beyond Identity and Access Management. The secure pattern is to set the full cloud-platform scope on the instance and then control access with Identity and Access Management roles.
Workload Identity Federation with short-lived credentials is preferred over long-lived service account keys, which are the last authentication choice for workloads. Service account keys are long-lived private keys that let an application authenticate from any environment, so anyone who holds the private key file can authenticate as the service account and create lasting exposure through privilege escalation, spoofing, and hard-to-trace actions.
Last updated