Study Guide4,531 words

Unit 5.2 study guide — Managing service accounts

Associate Cloud Engineer › Unit 5 › Topic 2

Managing service accounts

Study guide for Associate Cloud Engineer, Unit 5 · Topic 2. This is the topic's lecture in reading form — every slide's teaching, figures and worked examples, in order — followed by the official Google Cloud pages its claims rest on.

What the exam guide asks, quoted. Managing service accounts. Considerations include:

  1. Creating service accounts
  2. Using service accounts in IAM policies with minimum permissions
  3. Assigning service accounts to resources
  4. Managing IAM of a service account
  5. Managing service account impersonation
  6. Creating and managing short-lived service account credentials

Managing service accounts

One identity for a workload, from creation to a short-lived token

Make it — create the service account and grant it only what it needs. Use it — attach it to the resource that runs as it. Guard it — decide who may use it, and who may act as it. Borrow it — impersonation and short-lived credentials instead of keys.

This is the last topic of the Associate Cloud Engineer guide, and its six objectives follow one service account through its life. Google defines a service account as a special kind of account typically used by an application or compute workload, such as a Compute Engine instance, rather than a person. First you create it. Then you grant it permissions in identity and access management (IAM) policies — only the permissions it needs. Then you assign it to the resource that runs as it. Then you manage its own IAM: who may use it, and who may manage it. Then impersonation, where a person or another service account acts as it. And finally short-lived credentials, which are how that borrowing happens without a long-lived key. One idea runs under all six, and Google states it plainly: service accounts are both resources that other principals can be granted access to, and principals that can be granted access to other resources. Keep asking which of the two a question is about, and most of this topic's traps disappear.

Creating service accounts

An identity for a workload, named by an email address

  • gcloud iam service-accounts create NAME --display-name=...
  • Its email is NAME@PROJECT_ID.iam.gserviceaccount.com; a numeric ID is permanent
  • No password, no browser sign-in — it is not a person
  • Needs Create Service Accounts on the project; allow time before first use

Worked example (synthetic). A team creates report-writer for a nightly export job, then a script uses it one second later and fails. Nothing is wrong with the account: new service accounts take time to become visible, so the script retries with backoff.

The first objective is creation, and on the command line it is one command: gcloud iam service-accounts create, followed by a name. Google's reference says this command creates a service account with the provided name, and the display name flag is simply a textual name to display for the account. What you get back matters more than what you typed. The service account's name appears in its email address, in the format name at project identifier dot iam dot gserviceaccount dot com, and Google's reference says to use that email in subsequent identity and access management (IAM) commands. Each service account also has a permanent, unique numeric identifier, generated automatically. A service account is not a person: it has no password and can't be used for browser-based sign-in. To create one you need the Create Service Accounts role on the project. And there is one operational detail the exam likes: after creating a service account you might need to wait sixty seconds or more before using it, because read operations are eventually consistent — if you get an error immediately after creation, retry with exponential backoff.

Three kinds of service account

Who creates it decides who must look after it

KindWho creates itWho manages it
User-managedYou, in your own projectsYou
Default service accountCreated automatically when you enable or use certain servicesYou — it is still user-managed
Service agentGoogle Cloud, so a service can act on your behalfGoogle Cloud

Worked example (synthetic). A new project enables Compute Engine and a default service account appears. Nobody on the team created it, but Google is clear that the team is responsible for managing it from then on.

Google sorts service accounts into two categories: user-managed service accounts, which you create and manage yourself, and service agents, which Google Cloud creates and manages. The middle row of this table is the one that catches people. Default service accounts are user-managed service accounts that are created automatically when you enable or use certain Google Cloud services — so they arrive without anyone creating them, yet Google says you are responsible for managing default service accounts after they are created. Service agents are different: some Google Cloud services need access to your resources so they can act on your behalf, and those service accounts are known as service agents. So when a scenario asks who is responsible for a default service account's permissions, the answer is the customer, even though the customer never ran a create command.

Service accounts in IAM policies, with minimum permissions

As a principal, a service account gets only what its job needs

  • A compromised service account can do whatever it was granted — so grant little
  • One single-purpose service account per workload
  • Default service accounts may get Editor automatically; switch that off
  • Access scopes are not the control — fine-grained allow policies are

Worked example (synthetic). A report job needs to read one bucket. The team creates a dedicated service account and grants it a read role on that bucket alone, rather than running the job as a default service account that holds Editor on the project.

The second objective treats the service account as a principal — something that receives roles in identity and access management (IAM) policies. Google's reasoning for minimum permissions is about damage: because a service account is a principal, you must limit its privileges to reduce the potential harm that can be done by a compromised service account. Two practices follow. Create single-purpose service accounts, so each workload holds only its own permissions. And watch the default service accounts: depending on your organization policy configuration, a default service account might automatically be granted the Editor role on your project, and Google strongly recommends disabling that automatic grant by enforcing the iam dot automaticIamGrantsForDefaultServiceAccounts organization policy constraint. Granting a role to the default service account also affects every virtual machine (VM) running as it. The last trap is access scopes. A scope such as Cloud Storage read-only restricts operations but can't restrict access to specific buckets, so Google's advice is to create a dedicated service account and use fine-grained allow policies instead.

The default service account's Editor grant

The constraint stops new grants; it does not undo old ones

SituationWhat happensWhat to do
No constraint enforcedA default service account may be granted Editor on the projectEnforce the constraint
Constraint enforcedNew default service accounts don't get Editor automaticallyGrant the roles they need yourself
Existing default service account already holds EditorStill holds it — the constraint doesn't remove itReplace Editor with less permissive roles

Worked example (synthetic). Security enforces the constraint across the organization, then an audit still finds Editor on an old project's default service account. Expected: the fix for existing accounts is to replace the role, by hand.

This table is the part of the objective an exam question is built from. Without the constraint, depending on organization policy configuration, a default service account might automatically be granted the Editor role on the project. Enforcing the constraint stops that for new default service accounts — and Google adds that if you disable the automatic grant, you must decide which roles to grant them and grant those roles yourself. The third row is the trap: applying the constraint doesn't remove the Editor role from existing default service accounts. For those, Google recommends replacing the Editor role with less permissive roles. So an audit that still finds Editor after the constraint was enforced has not found a failure of the constraint; it has found an account created before it, which still needs its roles replaced.

Assigning service accounts to resources

Attach it, and the code on the resource runs as it

Figure. Four cards: the Service Account User role on the service account is needed to attach it; a new VM gets a service account with gcloud compute instances create and the service-account and scopes flags; an existing VM must be stopped before set-service-account; and a service account from another project needs that project's organization policies updated.

Worked example (synthetic). A developer's instances create --service-account=etl@… is refused although the developer is a Compute Admin. The missing grant is Service Account User on the etl service account itself.

The third objective is assignment, which Google calls attaching. For some Google Cloud resources, you can specify a user-managed service account that the resource uses as its default identity, and the effect is automatic: if you attach a service account to a Compute Engine instance and the applications on it use a client library to call Google Cloud application programming interfaces (APIs), those applications automatically use the attached service account. Attaching needs its own permission. The Service Account User role on the service account contains the iam dot serviceAccounts dot actAs permission, which is required to attach a service account to a resource — so being allowed to create virtual machines (VMs) is not enough. For a new VM, Google's command is gcloud compute instances create with the service account's email and the cloud-platform access scope, which can be written with the alias cloud-platform. For an existing VM the order matters: to change a VM's service account and access scopes you must first stop the VM, then run set-service-account with the VM name, the email and the scopes. And a service account from a different project needs that project's organization policies updated before it can be attached.

Which way to give a workload an identity

Google's own decision order — keys come last

Loading Diagram...
Figure 1 — Mermaid diagram

Figure: A decision flow: a workload in Google Kubernetes Engine uses Workload Identity Federation for GKE; a workload on another Google Cloud resource gets an attached user-managed service account; a workload outside Google Cloud whose identity provider supports federation uses Workload Identity Federation; only otherwise does it fall back to a service account key.

Worked example (synthetic). Three workloads: pods in a GKE cluster, a batch job on a VM, and a build server in another cloud. The pods use Workload Identity Federation for GKE, the VM gets an attached service account, the build server uses Workload Identity Federation — and none of them holds a key.

Attaching is one answer to a bigger question — how should a workload get an identity at all — and Google's best-practices page walks it as a sequence. If the workload is containers in Google Kubernetes Engine (GKE), use Workload Identity Federation for GKE to attach service accounts to Kubernetes pods; Google calls it, in most cases, the recommended way for workloads on GKE to access Google Cloud services, and it gives each application in the cluster a distinct, fine-grained identity. If the workload runs on another Google Cloud resource, attach a service account to the resource — and Google's Compute Engine guidance adds to create a new user-managed service account rather than using the default one, granted only what it needs. If the workload runs outside Google Cloud with an identity provider that supports it, configure Workload Identity Federation, which gives on-premises or multicloud workloads access by using federated identities instead of a service account key. Only when none of those applies does the chart end at a key — which is why a key is the wrong first answer on the exam.

Managing IAM of a service account

The service account as a resource, with its own allow policy

  • Grant on the account: gcloud iam service-accounts add-iam-policy-binding
  • Grant per service account — not at the project or folder level
  • Service Account Admin manages access; Service Account User only attaches
  • Disable before you delete; a re-created name is a new identity

Worked example (synthetic). Two teams share a project with twenty service accounts. Granting a developer Service Account User on the project would let them attach all twenty; granting it on etl alone lets them attach exactly one.

The fourth objective flips the service account over. Google's page on it says it treats service accounts as resources and describes how to grant other principals access to them. A service account has its own allow policy: you read it with get-iam-policy for the service account, and to quickly grant a role to a principal you run add-iam-policy-binding — gcloud iam service-accounts add-iam-policy-binding, the service account, the member and the role. Two cautions come with it. A resource's allow policy doesn't show roles gained through inheritance, and setting a whole new policy permanently overwrites the existing one, where add-iam-policy-binding only adds. The level of the grant matters most. Managing access at the project level can over-grant, so Google says don't manage access to service accounts at the project or folder level; instead, individually manage access for each service account. Managing access itself takes the Service Account Admin role. And the account's lifecycle is part of its management: disabling it cuts off applications but can easily be reversed, whereas a deleted and re-created service account with the same name is treated as a separate identity that does not inherit the old one's roles — only an undelete, within thirty days, keeps them.

Roles granted ON a service account

Each one lets a principal do something different with it

Role on the service accountLets the principalDoes NOT let it
Service Account User roles/iam.serviceAccountUserAttach it to a resource (actAs)Create short-lived credentials, or use --impersonate-service-account
Service Account Token Creator roles/iam.serviceAccountTokenCreatorCreate short-lived credentials — and impersonateManage who else has access
Service Account Admin roles/iam.serviceAccountAdminManage access to the service account—
Workload Identity User roles/iam.workloadIdentityUserImpersonate it from GKE workloads—

Worked example (synthetic). A developer holds Service Account User on deployer and runs a command with --impersonate-service-account=deployer@…, which is refused. Nothing is misconfigured: impersonation needs Token Creator.

Four roles are granted on a service account, and the exam separates the first two. The Service Account User role lets a principal attach a service account to a resource. Google is explicit about its limit: this role does not allow principals to create short-lived credentials for service accounts, or to use the impersonate-service-account flag for the Google Cloud command line. That takes the second role: the Service Account Token Creator role lets principals create short-lived credentials for a service account. Service Account Admin is the role for managing access to the service account itself. And the Workload Identity User role lets principals impersonate service accounts from Google Kubernetes Engine (GKE) workloads. Google adds a caution worth remembering: if a service account holds highly privileged permissions, be cautious when granting the Service Account User role or its permissions to a user on it, because being able to use a powerful account is itself a powerful grant.

Disable, delete, undelete — and re-create

Only one of the four keeps the account's roles and identity by design

Figure. Four cards: disabling a service account cuts off access but can easily be reversed; deleting it can be undone by undelete for a limited time; undelete within thirty days restores the same identity with its roles; re-creating a service account with the same name makes a separate identity that does not inherit the old roles.

Worked example (synthetic). A cleanup script deletes etl, then someone re-creates etl to fix the outage and it still fails every permission check. The re-created account is a new identity; undelete would have brought the roles back.

Lifecycle is where managing a service account goes wrong in practice, so here are the four moves side by side. Disabling a service account is like deleting it for the applications — Google says they will no longer have access to Google Cloud resources through it — but unlike deletion, disabled service accounts can easily be re-enabled, which is why Google's practice is to disable before you delete. Deleting is recoverable for a while: you can undelete a service account if it's been thirty days or less since you deleted it, and when you undelete it, the service account's identity does not change and it retains its roles. The fourth card is the trap. If you delete a service account and then create a new one with the same name, the new service account is treated as a separate identity, and it does not inherit the roles granted to the deleted one. Same email address, different identity — so every grant must be made again.

Managing service account impersonation

Two identities: the one who asks, and the one who acts

Figure. An engineer asks IAM, through the Service Account Credentials API, for a short-lived token as a service account; IAM issues it only if the engineer holds Token Creator on that service account. The engineer then sends the request to the Cloud Storage API with the service account's token, the service account's roles are checked, and the bucket is read as the service account. The callout says Token Creator on the service account lets the engineer in, while the bucket grant belongs to the service account.

Worked example (synthetic). An on-call engineer needs one hour of access to a production bucket. Instead of granting the engineer a role on the bucket, the team grants Token Creator on a service account that already holds it — and removes it after the incident.

The fifth objective is impersonation, and Google defines it exactly: when an authenticated principal, such as a user or another service account, authenticates as a service account to gain the service account's permissions, it's called impersonating the service account. The figure shows why it always involves two identities — an authenticated principal, and the service account it impersonates. The engineer first asks for a token for the service account; that step needs the iam dot serviceAccounts dot getAccessToken permission, which Google says is in the Service Account Token Creator role, granted on the service account. With that token, the engineer authenticates as the service account, so when the request reaches the bucket, it is the service account's roles that are checked. That separation is what makes impersonation useful: Google names temporarily granting a user elevated access, and testing whether a set of permissions is sufficient for a task, without changing anyone's own grants. And it stays accountable — if a principal accesses resources while impersonating, most audit logs include both their identity and the identity of the service account.

Impersonating from the command line

One command, every command, or your client libraries

Figure. Four cards: impersonating for one gcloud command with the impersonate-service-account flag; setting auth/impersonate_service_account with gcloud config set so every command impersonates; gcloud requesting short-lived credentials and running the command with them; and the Token Creator role being required on the service account.

Worked example (synthetic). A platform engineer tests a new deployment role safely: every command in that session runs with auth/impersonate_service_account set to the deployer, then the property is unset — and the audit logs show both identities throughout.

On the command line, impersonation comes in two scopes. For a specific command, you use the impersonate-service-account flag — Google's example lists storage buckets using the identity and access provided by the specified service account. To make it the default, you use the gcloud config command to set the auth impersonate_service_account property, and with it set, the command line requests short-lived credentials for the service account and uses them for every command. Either way the mechanism is the same: when you run a command with this setting, the command line creates short-lived credentials for the service account, then runs the command with those credentials — nothing is written to a key file. And the permission is the same too: to impersonate a service account you need the Service Account Token Creator role on that service account. That is the sentence to hold on to when an option offers Service Account User instead.

Creating and managing short-lived credentials

Tokens that expire on their own, instead of keys that don't

  • Enable the IAM and Service Account Credentials APIs first
  • gcloud auth print-access-token --impersonate-service-account=SA_EMAIL
  • REST: serviceAccounts.generateAccessToken returns an OAuth 2.0 token
  • Default maximum lifetime is one hour; no refresh token — request again

Worked example (synthetic). A deployment pipeline needs to call an API as deployer for a few minutes. It prints a short-lived access token for the service account at the start of each run; when a long run's token expires, it simply requests a new one.

The last objective is the credentials themselves. Short-lived credentials, Google says, have a limited lifetime, with durations of just a few hours or shorter, are not automatically refreshed, and create less risk than long-lived credentials such as service account keys. Depending on the type you create, the token carries the service account's permissions — an OAuth 2.0 access token — or its identity — an OpenID Connect (OIDC) ID token; Google also lists self-signed JSON Web Tokens (JWTs) and blobs. Before any of it, enable the identity and access management (IAM) and Service Account Credentials application programming interfaces (APIs): gcloud services enable iam dot googleapis dot com and iamcredentials dot googleapis dot com. A direct request involves two identities, the caller and the service account, and on the command line you generate a token for the service account with gcloud auth print-access-token and the impersonate flag; in the REST API, the Service Account Credentials API's generateAccessToken method returns an OAuth 2.0 access token. Two limits are tested. By default the maximum token lifetime is one hour; extending it to twelve hours means adding the service account to an organization policy with the allowServiceAccountCredentialLifetimeExtension constraint. And an impersonated access token comes without a refresh token — when it expires, you repeat the impersonation.

Short-lived credentials against service account keys

Why Google treats a key as the last resort

AspectShort-lived credentialService account key
LifetimeOne hour by default; up to twelve with a constraintLong-lived
When it runs outNo refresh — impersonate againUntil someone removes it
If it leaksExpires on its ownLikely to work — no extra sign-in checks
Google's adviceUse whenever possibleAvoid user-managed keys
Organization policyallowServiceAccountCredentialLifetimeExtension extends itdisableServiceAccountKeyCreation blocks new keys

Worked example (synthetic). An engineer's key download is refused in a new organization. That is the organization policy disabling key creation doing its job — the fix is impersonation, not an exception.

This comparison is why the whole topic leans away from keys. Service account keys are a security risk if not managed correctly, and Google's key guide is blunt about why: authenticating by using a leaked service account key is likely to succeed, because service accounts are not subject to any additional sign-in verifications. So its advice is to avoid user-managed service account keys and use other methods whenever possible. The short-lived column is the other method. Its lifetime is one hour by default, extendable to twelve hours through the lifetime-extension organization policy constraint, and when it runs out there is no refresh — you simply impersonate again. Organizations can also enforce the choice. The iam dot disableServiceAccountKeyCreation constraint disables the creation of new external service account keys, and when it is set, user-managed credentials cannot be created for service accounts in the affected projects. Google's overview adds the practical reading: if you are prevented from creating a service account key, key creation might be disabled for your organization.

What this topic actually tests

Principal or resource, User or Token Creator, and never a key first

Principal or resource? roles FOR the service account are minimum grants; roles ON it decide who can use it. User or Token Creator? User attaches; Token Creator impersonates and mints tokens. Where is the grant? on the individual service account, not the project. Key or token? a short-lived token, every time Google offers one.

Close the topic, and the Associate Cloud Engineer guide, on four questions. First, principal or resource: a service account receives roles in allow policies, where it should hold only what its job needs, and it also has its own allow policy, which decides who may use it. Second, Service Account User or Token Creator: User lets a principal attach the account to a resource, but it does not allow short-lived credentials or the impersonate flag — Token Creator does. Third, where the grant lives: Google says don't manage access to service accounts at the project or folder level, but individually for each service account. Fourth, key or token: short-lived credentials expire on their own and are not refreshed, while a leaked key is likely to work, so a scenario that reaches for a key before impersonation, an attached service account or Workload Identity Federation is almost always offering the distractor. That same order — attach, federate, impersonate, and only then a key — is the most useful thing to carry out of this unit.

Official sources for this topic

Ready to study Associate Cloud Engineer (GCP-ACE)?

Practice tests, flashcards, and all study notes — free, no sign-up needed.

Start Studying — Free