Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 45 ยท Identity and Security

Service Accounts and Credentials

Learn Google Cloud service accounts: attaching them to workloads, impersonation, workload identity federation, and why key files are a last resort.

A program that calls Google Cloud needs an identity, just as a person does. A service account is that identity: an account that belongs to a project, not to a human, and that holds IAM roles like any other principal. Your web app, your nightly job and your build pipeline should each run as a service account with only the access they need.

The hard part is not creating a service account. It is giving a program its credentials without leaving secrets lying around. This lesson walks from the safest approach to the riskiest: attached accounts, impersonation, federation, and finally key files.

What a service account looks like

A service account has an email address that doubles as its principal name:

Creating one and granting it a role looks like this (read-only; these need a real project):

Terminal
gcloud iam service-accounts create orders-api \
  --display-name="Orders API"

gcloud projects add-iam-policy-binding my-project-id \
  --member="serviceAccount:[email protected]" \
  --role="roles/pubsub.publisher"

A service account is two things at once: a principal (it can be granted roles) and a resource (people can be granted roles on it, for example the right to act as it). Mixing these up is behind many confusing permission errors.

Four ways to get credentials

Attached The platform runs your code as the account. No secret at all.
Impersonation A person or account borrows it briefly with a short token.
Federation An outside identity, like CI, trades its own token for one.
Key file A long-lived secret. The last resort.

Go left to right when you can; avoid the key file.

1 / 2

Attached service accounts

When you create a VM, a Cloud Run service or a function, you choose which service account it runs as:

Terminal
gcloud run deploy orders-api \
  --image=us-docker.pkg.dev/my-project-id/apps/orders:1 \
  --service-account[email protected]

Code running there needs no key. The client libraries ask a local metadata server for a short-lived access token on behalf of the attached account, refresh it automatically, and use it. This mechanism is part of Application Default Credentials (ADC): a library checks, in order, an environment variable that points to a credentials file, the credentials created by gcloud auth application-default login on your laptop, and finally the attached account of the platform. In production on Google Cloud, the last one wins, and your code stays the same everywhere:

Python
from google.cloud import storage

client = storage.Client()   # finds credentials by itself via ADC

Give each workload its own service account. The default accounts that some products create are often broader than needed (older projects may even have given the default Compute Engine account a very wide role), so check what yours can do and prefer a dedicated account with a specific role.

Impersonation instead of keys

Suppose you, as a developer, want to test with the same access your app has. Rather than download a key, you can impersonate the service account. You need a role on the account that lets you create tokens for it, such as roles/iam.serviceAccountTokenCreator:

Terminal
gcloud storage ls gs://orders-bucket \
  --impersonate-service-account[email protected]

Google's token service checks that you may act as the account, then returns a token that lasts about an hour by default. Everything is logged against both identities, and nothing permanent exists on your disk. Closely related is the permission to attach an account to a resource (iam.serviceAccounts.actAs, included in the role roles/iam.serviceAccountUser): without it, anyone who can create VMs could run them as a powerful account and borrow its power. Grant it narrowly.

Federation: no keys for outside systems

What about code that runs outside Google Cloud, like a GitHub Actions workflow or a server in another cloud? Workload Identity Federation lets it exchange a short-lived token from its own platform for a short-lived Google token. You configure Google Cloud to trust a particular external issuer and conditions (for example, only this repository on this branch), and the workflow never stores a Google secret. On Google Kubernetes Engine, a similar feature maps a Kubernetes service account to a Google one so pods get access without keys. The setup commands vary by provider, so follow the current documentation when you build one; the concept to keep is trade an identity you already have for a short-lived token.

Why key files are a last resort

You can create a JSON key for a service account:

Terminal
gcloud iam service-accounts keys create key.json \
  --iam-account[email protected]

That file is a password that does not expire by default. It can be committed to a repository, copied into a chat, baked into a container image, and nobody will know until the bill or the breach arrives. A leaked key is one of the most common serious cloud incidents (see Common Mistakes and Troubleshooting).

Never commit a key file or paste it into an issue. If you must create one (a system that supports none of the other methods), store it in Secret Manager, rotate it on a schedule, delete the old key, and set an alert on its use. An organization policy can block key creation entirely, which is a good default (see Least Privilege and Organization Policies).

A stand-in token-minting model

The model below imitates the idea of short-lived tokens and impersonation. It is not Google's token format or API: tokens here are plain objects with an expiry, the "service" is a function, and time is a number we control. What it shows accurately is the flow: check the caller's right to impersonate, mint a token that expires, and reject it after that.

JS Stand-in: short-lived tokens and impersonation

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line is the lesson in one output: a stolen short-lived token stops working on its own, while a stolen key keeps working until someone notices.

How code finds credentials

This second model imitates how the Application Default Credentials search order lets the same code run on a laptop and in the cloud. The environment is a plain object here; the real libraries read environment variables, local files and a metadata server.

JS Stand-in: credential search order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at the third case: a forgotten environment variable silently overrides the safe attached account. When behaviour surprises you, check which credentials your code actually found.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which approach gives a Cloud Run service access to other Google services without any secret file?

    The platform supplies short-lived tokens for the attached account through the metadata server, so no secret is stored with the code.
  2. 2. What does impersonation give a developer compared with a downloaded key?

    The caller needs permission to create tokens for the account, receives a short-lived token, and the action is auditable.
  3. 3. Workload Identity Federation is mainly used for which situation?

    Federation exchanges a short-lived token from an external identity provider for a short-lived Google token, removing the need for a key file.
  4. 4. A service account is both a principal and what else?

    You can grant someone a role on the service account, such as permission to impersonate it or to attach it to resources.

Summary

  • A service account is the identity for a program and holds roles like any principal.
  • Prefer attached accounts, then impersonation, then federation; use key files only when nothing else works.
  • Application Default Credentials let the same code run on a laptop and in production.
  • Give each workload its own account with narrow roles, and restrict who may attach or impersonate it.
  • Short-lived tokens limit the damage of a leak; keys do not.

Next: Least Privilege and Organization Policies