Service accounts and Application Default Credentials
Trace how ADC finds credentials locally and on a runtime, and use an attached service account, impersonation and Workload Identity Federation without keys.
By Invicly Tech, , in Google Cloud Engineering and Services. About 11 minutes to read.
In short
Code should not run as a person. It runs as a service account, and Google client libraries find that identity through Application Default Credentials (ADC) without any key file. Locally you sign in or impersonate a service account, on Google runtimes the attached service account is used, and outside Google Cloud Workload Identity Federation swaps an external token for a short-lived Google one.
Think of it like this: An attached service account is a staff badge issued at the door for the shift; a downloaded key is a copied master key that works for years in anyone's hand.
Explained simply
When your code calls a Google API, it must prove who it is, just as you do when you log in. Code should not borrow a person's account. It uses a service account, which is an identity made for software, with an email like orders-api@orders-lab-4821.iam.gserviceaccount.com.
Google client libraries find credentials for you through Application Default Credentials, or ADC. They look in three places in order: a file named in the GOOGLE_APPLICATION_CREDENTIALS variable, a local file made by gcloud, and finally the service account attached to the machine or service the code runs on.
On Cloud Run or Compute Engine you attach a service account when you deploy. The platform hands your code short-lived tokens for it, and you never see a password or key. On your laptop you sign in with gcloud, or you impersonate the service account to test with exactly its permissions.
Code that runs outside Google Cloud, such as a GitHub Actions job, can use Workload Identity Federation. It trades the platform's own signed token for a short-lived Google token. Downloaded service account keys also work, but they are long-lived secrets that leak easily, so avoid them.
Press Play on a diagram to walk through it one step at a time.
- Step 1GOOGLE_APPLICATION_CREDENTIALS
Path to a federation config or key file
- Step 2Local ADC file
Written by gcloud auth application-default login
- Step 3Metadata server
Attached service account on Cloud Run, GCE, GKE
- Step 4Not found
Library raises a default credentials error
- Code runs on Google Cloud
- Set with --service-account at deploy
- Tokens from the metadata server
- Nothing to rotate
- A person or SA acts as another SA
- Needs Service Account Token Creator
- Short-lived tokens
- Good for local testing
- Code runs outside Google Cloud
- Trusts an external OIDC or SAML issuer
- Exchanges tokens via STS
- Used by GitHub Actions, AWS, Azure
- Developer laptop
- gcloud auth application-default login
- Add --impersonate-service-account for SA tests
- Cloud Run, GCE, GKE
- Attached dedicated service account
- Tokens from metadata server
- GitHub, AWS, Azure, on-premises
- Workload Identity Federation
- Credential config file, no secret
- Nothing else works
- Service account key
- Rotate, restrict, monitor
In depth
The ADC lookup, step by step
Client libraries call a function such as google.auth.default() in Python. It first checks GOOGLE_APPLICATION_CREDENTIALS. If set, the file it points to is used, whether it is a federation configuration or a key; nothing else is tried. Next it looks for the user ADC file at $HOME/.config/gcloud/application_default_credentials.json on Linux and macOS, written by gcloud auth application-default login. Last, it asks the metadata server, which exists only on Google runtimes, for a token of the attached service account.
This order explains most surprises. A stale variable from an old tutorial beats everything. A developer's own login file can make code work locally with far more access than it will have in production. Print the credential type at start-up and log the identity in use so you can tell which branch ADC took.
- 1: GOOGLE_APPLICATION_CREDENTIALS
- 2: local user or impersonated ADC file
- 3: metadata server (attached service account)
- Check: unset the variable when debugging
Attaching a service account to a runtime
Create one service account per workload, such as orders-api and orders-worker. Grant each only the roles it needs on the resources it touches. At deploy time, attach it: Cloud Run uses --service-account, Compute Engine uses --service-account with --scopes=cloud-platform so IAM alone decides access. To attach a service account, the person deploying needs roles/iam.serviceAccountUser on it, which stops people from borrowing powerful identities.
If you attach nothing, many services fall back to the Compute Engine default service account, PROJECT_NUMBER-compute@developer.gserviceaccount.com. In older projects it may hold the Editor role on the whole project. Newer organisations prevent that automatic grant, but the safe habit is the same everywhere: always pass a dedicated service account.
- Your code to Metadata server: Client library asks for a token1Client library asks for a token
- Metadata server to Your code: Short-lived token for orders-api2Short-lived token for orders-api
- Your code to Cloud Storage: Request with bearer token3Request with bearer token
- Cloud Storage to Your code: IAM checks orders-api's roles, returns data4IAM checks orders-api's roles, returns data
Impersonation for people and pipelines
Impersonation lets one principal get short-lived tokens for a service account. The caller needs roles/iam.serviceAccountTokenCreator on that specific service account. For gcloud, add --impersonate-service-account=EMAIL to a command, or set it as a configuration property. For your code, run gcloud auth application-default login --impersonate-service-account=EMAIL so ADC writes an impersonated credential file.
This is the best way to test locally with production-like permissions, because your code sees exactly what the service account can do, not what you can do. Every token request is recorded in audit logs against both identities. Tokens last an hour or less and are not refreshed after that, which limits damage if one leaks.
- Grant Token Creator on the service account, not the project
- gcloud ... --impersonate-service-account=EMAIL
- ADC: application-default login --impersonate-service-account
- Audit logs show who impersonated whom
Workload Identity Federation and why keys are a last resort
Workload Identity Federation trusts an external identity provider. You create a workload identity pool, add a provider for GitHub, AWS, Microsoft Entra ID or any OIDC or SAML 2.0 issuer, map claims to Google attributes such as google.subject, and add an attribute condition that accepts only your tokens, for example one repository. Then grant IAM roles to the federated principal directly, or let it impersonate a service account.
At run time the workload sends its own token to Google's Security Token Service and gets a short-lived federated token back. No secret is stored anywhere. Service account keys, by contrast, are JSON files that stay valid until deleted, get copied into repos and laptops, and are hard to trace. New organisations block key creation by default with the iam.managed.disableServiceAccountKeyCreation constraint. Use keys only when nothing else works, and rotate and monitor them.
- GitHub job to GitHub OIDC: Request ID token (id-token: write)1Request ID token (id-token: write)
- GitHub OIDC to GitHub job: Signed token with repo and ref claims2Signed token with repo and ref claims
- GitHub job to Google STS: Exchange token3Exchange token
- Google STS to GitHub job: Short-lived federated token if condition passes4Short-lived federated token if condition passes
- GitHub job to Google APIs: Deploy call with federated token5Deploy call with federated token
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Follow the ADC search order~35m
- 2Attach a service account to a runtime~35m
- 3Impersonate a service account locally~35m
- 4Federate an external identity~35m
- 5Avoid service account keys~35m
Key points
- ADC checks GOOGLE_APPLICATION_CREDENTIALS, then the local ADC file, then the attached service account.
- Give each workload its own service account with only the roles it needs; avoid the default compute service account.
- Impersonation needs roles/iam.serviceAccountTokenCreator on the target service account.
- Workload Identity Federation lets external workloads call Google APIs with no stored key.
- Service account keys are long-lived secrets; new organisations block their creation by default.
Key terms
Tap a card to flip it. 0/6 known
Examples
import google.auth
from google.cloud import storage
# Same code works on a laptop (ADC file) and on Cloud Run (metadata server)
credentials, project = google.auth.default()
print("Using project:", project, type(credentials).__name__)
client = storage.Client(credentials=credentials, project=project)
for blob in client.list_blobs("orders-lab-4821-receipts", max_results=5):
print(blob.name)The client library never sees a key file; ADC decides where credentials come from.
Run the orders API on Cloud Run with its own identity
Prerequisites: a lab project with Cloud Run enabled and the receipts bucket. Step 1: create the orders-api service account. Step 2: grant it Object Creator on the bucket only. Step 3: deploy with --service-account and no public access. Expected evidence: gcloud run services describe shows serviceAccountName orders-api@..., and uploads succeed. Cleanup: delete the service and the service account.
P=orders-lab-4821; SA=orders-api@$P.iam.gserviceaccount.com
gcloud iam service-accounts create orders-api --project=$P
gcloud storage buckets add-iam-policy-binding gs://$P-receipts \
--member=serviceAccount:$SA --role=roles/storage.objectCreator
gcloud run deploy orders-api --image=us-docker.pkg.dev/cloudrun/container/hello \
--region=europe-west2 --service-account=$SA --no-allow-unauthenticated
gcloud run services describe orders-api --region=europe-west2 \
--format="value(spec.template.spec.serviceAccountName)"
# cleanup
gcloud run services delete orders-api --region=europe-west2 --quiet
gcloud iam service-accounts delete $SA --quietKeyless GitHub Actions authentication
Prerequisites: a workload identity pool and GitHub provider whose attribute condition limits tokens to your repository, and a role granted to the matching principalSet. Step 1: allow the job to request an ID token. Step 2: call google-github-actions/auth with the provider name. Step 3: later steps run gcloud as the federated identity. Expected evidence: the auth step prints the federated principal, and no secret exists in the repository settings.
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v4
- uses: google-github-actions/auth@v3
with:
workload_identity_provider: projects/123456789/locations/global/workloadIdentityPools/github/providers/my-repo
project_id: orders-lab-4821
- uses: google-github-actions/setup-gcloud@v2
- run: gcloud storage ls gs://orders-lab-4821-receiptsQuick reference
- ADC order: GOOGLE_APPLICATION_CREDENTIALS > local ADC file > attached service account
- Local ADC: gcloud auth application-default login
- Impersonate: needs roles/iam.serviceAccountTokenCreator on the target service account
- Attach an SA at deploy: needs roles/iam.serviceAccountUser on that SA
- One dedicated service account per workload; never rely on the default compute SA
- External workloads: Workload Identity Federation, not keys
- Debug: print google.auth.default() credential type at start-up
Common mistakes
- Leaving GOOGLE_APPLICATION_CREDENTIALS set to an old key file, which silently overrides everything else.
- Deploying with the default compute service account, which may hold broad project roles.
- Granting Token Creator on the whole project instead of on one service account.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a two-line Python snippet that prints which kind of credential ADC found.
- Exercise 2medium
Let ana@example.com impersonate orders-api locally, then list the receipts bucket as orders-api.
- Exercise 3hard
Design the federation set-up for one GitHub repository, contoso/orders, so only its main branch can read the receipts bucket. List resources and the condition.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is a service account a user or a resource?
- Both. It is a principal that can be granted roles, and it is a resource that has its own policy controlling who may use or impersonate it.
- Do I need a key to test locally?
- No. Use gcloud auth application-default login, with impersonation if you want the service account's exact permissions.
- What are service agents?
- Google-managed service accounts that services use to act in your project, such as the Cloud Storage service agent using a KMS key. Leave their roles alone unless the docs say otherwise.