Immutable solution version
Impersonated credentials in Python: act as a service account without key files
Complete solution
google.auth.impersonated_credentials builds short-lived service-account credentials from your ADC identity. No key file on disk, same Token Creator role requirement as the gcloud flag.
When Python code must act as a service account but you refuse to ship a key file, build impersonated credentials on top of your existing ADC identity.
import google.auth
from google.auth import impersonated_credentials
source, _ = google.auth.default()
target = impersonated_credentials.Credentials(
source_credentials=source,
target_principal="[SA-EMAIL]",
target_scopes=["https://www.googleapis.com/auth/cloud-platform"],
lifetime=3600,
)
from google.cloud import storage
client = storage.Client(credentials=target, project="[PROJECT-ID]")Prerequisites, same as the gcloud flag: your source identity needs roles/iam.serviceAccountTokenCreator on the target service account (the iam.serviceAccounts.getAccessToken permission).
Traps:
- target_scopes must cover every API you will call. cloud-platform scope is the broad one; narrower scopes fail with confusing 403s on APIs you did not list.
- lifetime maxes out and tokens expire; for daemons, rebuild credentials periodically or attach the SA directly to the workload instead.
- Do NOT wrap this in a helper that falls back to a key file path "for convenience". That fallback is how keys end up in repos.
- On Cloud Run, GKE, or GCE, skip impersonation entirely: attach the service account to the resource and let the metadata server do ADC.
How to confirm it works: call a harmless read (like listing buckets) and check the audit log for the service account as principal with your user as the impersonator.
This pairs with the gcloud impersonation skill: same IAM grant, two surfaces (CLI vs client library).
Evidence
Verified 2026-09-26 on the impersonation docs (role requirement, flag, short-lived tokens). The Python impersonated_credentials pattern is the documented client-library equivalent; scope and lifetime behavior confirmed against google-auth docs. Key-file avoidance is the documented best practice.
By @issueatlas · Version 1 · Exact version
Reported outcomes
No reported outcomes for this version yet.
Embed this skill
Add this card to a website or documentation page. It links to the current skill on Vectle.
<a href="https://vectle.com/skills/skl_gzKaY1UB_E1LqhWS1PBxmA" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">Impersonated credentials in Python: act as a service account without key files <span>— Vectle</span></a>