Prepare and test your skills

Prepare and test your skills

Creating service accounts is the process of creating a non-human workload identity and giving it only the access it needs to operate. A service account (opens in a new tab) is identified by a unique email address and lets an application make authorized API calls as itself. The most common pattern is to attach the account to the resource running the workload, then grant Identity and Access Management (IAM) roles to the account so the workload inherits that access.
A service account 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 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 of service accounts (opens in a new tab) 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. 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.
Creating a service account in the console (opens in a new tab) follows an ordered workflow that collects identity first and access second:
The Google Cloud CLI (opens in a new tab) creates the same resource 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 (opens in a new tab) then lets code on the virtual machine (VM) call APIs as that identity, subject to both IAM roles and access scopes.
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.
A decision tree branching on workload location to pick attached service account, Workload Identity Federation for GKE, Workload Identity Federation, impersonation, or service account key as last resort.
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 |
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.
Continue with this study guide: Creating service accounts
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. A service account is a workload principal for applications and automated processes, while user principals represent people and groups. 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.
How service accounts receive access (opens in a new tab) depends on role bindings in an allow policy, which attach a role containing permissions to a principal on a specific resource. Roles differ in breadth and maintenance, so choosing the right type controls blast radius when code or credentials are compromised:
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. A separate control governs who can use the identity itself, because users granted the Service Account User role (roles/iam.serviceAccountUser) can access all resources that the service account can access.
Choosing the smallest IAM role (opens in a new tab) 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.
Where to grant roles in the resource hierarchy (opens in a new tab) determines how broadly a service account can act, because child resources inherit allow policies from their parents. Google Cloud resources are organized from organization to folder to project to service-specific resources such as Compute Engine instances and Pub/Sub topics. 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. IAM Conditions can further narrow a higher-level grant to specific resources, and different roles can be granted at different levels for the same account.
Exam tip: Granting a role on a parent container grants access to all of its children, so choose a resource-level grant when the workload needs access to only one topic, instance, or other child resource.
Continue with this study guide: Using service accounts in IAM policies with minimum permissions
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 (opens in a new tab) 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 (opens in a new tab) differ by who creates them, who maintains them, and whether workloads can use them directly. User-managed accounts are created and fully managed by you, default accounts are created automatically and then managed by you, and service agents are created and managed by Google so Google services can act on your behalf.
| 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.
How attached accounts are authorized (opens in a new tab) 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, and to reuse the same account on multiple VMs only when those VMs truly need identical permissions. For example, a VM with only Cloud Storage read-only scope cannot manage objects even if the account holds Storage Object Admin, because the scope does not authorize writes. Access scopes apply per VM for the life of the VM and do not apply to gRPC calls.
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 creating the account needs the Create Service Accounts role and the Project IAM Admin role, while 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.Exam tip: Only user-managed service accounts, including default service accounts, can be attached to a VM; service agents are Google-managed and cannot be attached.
Continue with this study guide: Assigning service accounts to resources
Managing IAM permissions of a service account means controlling both what the account can access and who can use the account itself. Identity and Access Management (opens in a new tab) treats a service account as a principal that can be listed in an allow policy, so an application running as that account receives only the authorization conferred by its granted roles. At the same time, the service account is a resource with its own allow policy that controls who can attach, impersonate, or manage it.
Role types for service accounts trade breadth for precision, which determines how much damage a compromised workload can cause. Basic roles are broad legacy roles across a project, predefined roles are Google-managed roles for a specific service or task, and custom roles are customer-defined sets for one specific job. Common focused examples include roles/compute.instanceAdmin.v1 for managing instances, roles/storage.objectViewer for reading objects, and roles/compute.networkAdmin for managing networks and firewall rules.
| Role type | Scope of permissions | Use for a service account when |
|---|---|---|
| Basic | Very broad access across a project | Only in development or test, never for production least privilege |
| Predefined | Focused capabilities for a service or task | A Google-managed role matches the workload |
| Custom | Exact set chosen by the administrator | No predefined role matches and a smaller set is needed |
Do not grant Owner, Editor, or Viewer in production; grant a predefined or custom role that contains only required permissions. To prevent broad defaults, enforce the iam.automaticIamGrantsForDefaultServiceAccounts organization policy constraint, which is enforced by default for organizations created after May 3, 2024.
Why both IAM and scopes must allow access (opens in a new tab) is that they limit different layers of a Compute Engine request. IAM roles granted to the attached service account define what the identity is allowed to do, while instance access scopes define which OAuth methods the VM can call through client libraries and the gcloud CLI. The request succeeds only when both layers allow it, so a broad scope does not override narrow IAM roles and a broad IAM role does not override a narrow scope.
| Control | What it controls | Where and how it applies |
|---|---|---|
| IAM roles | Which APIs and resources the account can use | Applies to the account everywhere; inherited by all workloads using it |
| Access scopes | Which OAuth methods the VM can call | Applies per VM; further limits OAuth but does not extend to gRPC |
The secure pattern for scopes (opens in a new tab) is to set the full cloud-platform scope (https://www.googleapis.com/auth/cloud-platform) and restrict with IAM roles. If a restrictive scope is used instead, such as Cloud Storage read-only, requests cannot manage objects even with Storage Object Admin. Creation of least-privilege accounts (opens in a new tab) follows the same idea: create a dedicated user-managed account, attach it to the resource, and grant only needed roles.
How to control who can use an account (opens in a new tab) reflects its dual nature as principal and resource. As a principal, the account receives workload roles such as Storage Object Viewer on a bucket or project. As a resource, the account grants usage roles such as Service Account User (roles/iam.serviceAccountUser) to developers who may attach it, and Service Account Admin to those who may view, edit, disable, or delete it.
IAM access is changed by editing the allow policy on the target resource, either in the console by selecting the principal and adding another role, or with gcloud by binding the member to the role on the destination. To give a service account access to a project, bind the service account as member on the project; to let a user attach an account, bind the user as member on the service account itself. REST API changes follow a read-edit-write flow: call getIamPolicy on the resource, edit the bindings in a text editor, then call setIamPolicy with the full updated policy.
Exam tip: Access succeeds only when both IAM and access scopes allow it, so set the broad cloud-platform scope and restrict with IAM roles.
Continue with this study guide: Managing IAM permissions of a service account
Managing service account impersonation means letting an authorized identity temporarily act as a service account (opens in a new tab) 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.
How impersonation works reflects that a service account is both an identity and a resource that accepts IAM policies. Permissions flow in two layers: the service account is granted roles on target resources such as buckets or projects, and then selected users or federated identities are granted permission to use that service account. The request flows from the original identity to the service account, and then from the service account to the target resource.
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. Common uses include CI/CD pipelines from GitHub or another cloud, cross-project automation, temporary privileged admin access, API compatibility when an endpoint does not support federation, and service-to-service invocation such as triggering a workflow.
Roles required for impersonation control which identities can act as which service accounts and whether they attach the account or mint 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.
For example, Cloud Build needs a resource admin or developer role on the target service plus Service Account User on the specific managed account it will impersonate during deployment. Least privilege means granting impersonation on a single service account, not on a whole project or folder, because a project-level grant would let the holder impersonate every account in that project. Avoid letting users impersonate accounts more privileged than themselves, and enforce checks with constraints such as constraints/appengine.enforceServiceAccountActAsCheck where available.
How to request impersonated credentials securely depends on short-lived tokens that expire in a few hours or less and are not automatically refreshed. Principals obtain them 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. Application Default Credentials (ADC) can also carry impersonation for local development, and most audit logs record both the caller identity and the impersonated account.
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 |
Exam tip: Choose Service Account User when the task attaches a service account to a resource, and choose Service Account Token Creator when the task creates short-lived tokens to act as the account.
Continue with this study guide: Managing service account impersonation
Creating and managing short-lived service account credentials means issuing temporary tokens that expire quickly and reflect only the permissions of the impersonated account. Short-lived service account credentials (opens in a new tab) 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.
How short-lived credentials are created (opens in a new tab) always involves a trusted identity asking the Service Account Credentials API to mint them on demand. The flow runs from the API to the requesting workload, and the workload then presents the credential to Google Cloud APIs. 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.
Key types behind these credentials determine who must protect a private key:
| Key type | Who holds private key | How it is used |
|---|---|---|
| Google-owned and managed key pair | Google holds the key in escrow; never accessible | API, App Engine, and Compute Engine generate short-lived credentials and sign blobs; Google rotates keys regularly |
| User-managed key pair | Customer holds the private service account key | Customer signs a JWT and exchanges it for a token; each account can have up to 10 keys |
Protecting developer credentials (opens in a new tab) favors the Google-managed path because no key file is distributed. The public key for a Google-owned pair is verifiable through X.509, JSON Web Key (JWK), and raw endpoints, with cache lifetimes of at most 24 hours.
How expiration, rotation, and revocation limit risk sets a hard end to how long a stolen credential can be abused. Short-lived tokens expire by default after 1 hour, while user-managed keys have no expiry unless one is configured at the project, folder, or organization level or by uploading a key with a Valid To date. Expiry fits temporary non-production use or third-party tools that only accept keys, but expiry should be avoided where it causes outages, such as production workloads, long-lived CI pipelines, or systems that already rotate keys.
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. Google Cloud can automatically disable publicly exposed keys when the Key Exposure Response constraint is set to DISABLE_KEY, and the iam.disableServiceAccountKeyCreation constraint can block new long-lived keys entirely.
How workloads get short-lived credentials without keys depends on where the workload runs and what identity it starts with. Attached service accounts let code on a Compute Engine VM request tokens from the metadata server through Application Default Credentials, while Workload Identity Federation lets external workloads exchange an external identity provider token for Google credentials. Service account impersonation lets an already authenticated caller exchange its own identity for a token for a target account that holds needed permissions.
| Mechanism | Where workload runs | How short-lived credential is issued |
|---|---|---|
| Attached service account | Google Cloud compute resource such as a VM | Workload requests a token from the metadata server for the attached account |
| Service account impersonation | Local workstation, Cloud Shell, or authenticated workload | Caller with Token Creator permission requests a token for the target email from the Credentials API |
| Workload Identity Federation | GKE, on-premises, AWS, Azure, or GitHub | Workload presents external identity and IAM exchanges it for a short-lived token |
Scoped least privilege still applies: grant only predefined or custom roles, apply IAM Conditions and VPC Service Controls where needed, and use dedicated accounts and keys per application and machine for traceability. The Credentials API also blocks self-impersonation that would let a stolen token refresh itself forever, failing with FAILED_PRECONDITION when the same account token tries to mint another token for itself.
Exam tip: Use different credentials to mint a token for a service account; using that same service account's short-lived credential to mint another token for itself is blocked as self-impersonation.
Continue with this study guide: Creating and managing short-lived service account credentials
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 (opens in a new tab) 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.
| Identity | Recognized by | Used for |
|---|---|---|
| Kubernetes service account | Kubernetes API inside one cluster | Authenticating a pod to the cluster API server |
| Google Cloud service account | Google Cloud APIs and IAM | Authenticating a GKE workload to storage, monitoring, translation, and other services |
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. Authentication to the Kubernetes API server (opens in a new tab) therefore remains separate from authorization to Google Cloud, which flows from the workload to the Google API with the Google service account identity.
How Workload Identity Federation for GKE links identities (opens in a new tab) 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.
Service accounts in GKE (opens in a new tab) support least privilege because each application can receive a different Google account with only minimal roles. Secure use of service accounts (opens in a new tab) 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. Development that relies on the shared Compute Engine default account with full API access overprovisions permissions and should not be used for production.
How to configure least-privilege access for GKE workloads links the deployment to the correct Kubernetes identity and grants only required Google roles. The deployment depends on the Kubernetes service account reference, and the Kubernetes service account depends on its link to the Google Cloud service account. Grant roles such as Translation API User on the project or Secret Manager Secret Accessor on a specific secret, as determined by the API the workload calls.
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.
Exam tip: Impersonation requires both the roles/iam.workloadIdentityUser binding and the iam.gke.io/gcp-service-account annotation; configuring only one side does not complete the link.
Continue with this study guide: Using a Google Cloud service account with a GKE application
A service account in Google Cloud is both a principal that can receive Identity and Access Management roles on resources and a resource with its own allow policy that controls who can impersonate, attach, or manage it. Roles granted to the account must follow least privilege to limit harm if compromised, while impersonation and attachment must be restricted with roles such as Service Account User and Service Account Admin.
Service account keys are long-lived private keys and are the last authentication choice because anyone holding the key file can authenticate as the account. An attached service account should be used for code running in Google Cloud on Compute Engine or similar resources with Google-managed short-lived tokens, while Workload Identity Federation should be used for Google Kubernetes Engine containers and for on-premises or other-cloud workloads to impersonate a service account without keys.
Identity and Access Management roles on the attached service account 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 virtual machine. 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, so best practice is to set the full cloud-platform scope and control access with roles.
Impersonation requires both granting the roles/iam.workloadIdentityUser binding on the Google Cloud service account to the Kubernetes service account identity and annotating the Kubernetes service account with the Google account email, because configuring only one side does not complete the link. After the link is complete, pods use the linked identity by setting the service account name in the Deployment, and the workload then calls Google Cloud APIs with the Google account permissions.
Last updated