Google Cloud Tutorial · Identity and Access · Lesson 8 of 27

Service Accounts

Identities for workloads: attaching service accounts, impersonation, and why to avoid key files.

Members can save this page, take notes and track progress. See membership · Sign in

What a service account is

A service account is an identity used by an application rather than a person, for example [email protected]. It is also a resource: you control who may use or impersonate it.

Getting credentials without keys

  • Attach a service account to a VM, Cloud Run service or function: the workload gets short-lived tokens from the metadata server automatically.
  • Workload Identity Federation for GKE gives Kubernetes ServiceAccounts their own Google identity.
  • Impersonation: an engineer with roles/iam.serviceAccountTokenCreator on the account can act as it temporarily (gcloud ... --impersonate-service-account=...), and the audit log records who did it.

Service account keys (downloaded JSON files) are long-lived passwords that leak through Git, laptops and CI logs. New organisations block key creation by default through the organisation policy iam.disableServiceAccountKeyCreation; keep it that way.

gcloud iam service-accounts create orders-api --display-name "Orders API"
gcloud run deploy orders-api --image "$IMAGE" \
  --service-account [email protected]

One identity per workload

Give each workload its own service account with only the roles it needs. Avoid the Compute Engine default service account, which older projects granted the Editor role.

Short-lived tokens versus long-lived keysTry it yourself
from datetime import datetime, timedelta

issued = datetime(2026, 11, 23, 9, 0)
token_lifetime = timedelta(hours=1)            # access tokens from the metadata server are short-lived
leaked_key_found = datetime(2026, 11, 23, 9, 0) + timedelta(days=200)

print("Attached service account token valid until", issued + token_lifetime)
print("A leaked JSON key keeps working until someone deletes it:")
print("  created", issued.date(), "-> still valid on", leaked_key_found.date(),
      f"({(leaked_key_found - issued).days} days later)")

Output

Attached service account token valid until 2026-11-23 10:00:00
A leaked JSON key keeps working until someone deletes it:
  created 2026-11-23 -> still valid on 2027-06-11 (200 days later)

Test yourself

What is the preferred way for a Cloud Run service to call other Google Cloud APIs?

  1. Bake a service account key into the image
  2. Use the Compute Engine default service account
  3. Attach a dedicated service account with only the roles it needs
  4. Use an engineer's personal credentials
Show answer

Answer: Attach a dedicated service account with only the roles it needs

Attached service accounts give short-lived tokens with no keys to leak.

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake