During a routine access review we counted 41 user-managed service account keys across our Google Cloud projects. Nine were older than two years. One belonged to a service account with roles/editor on the production project, and nobody could say which system still used it. A service account key is a private key in a JSON file: it never expires unless someone deletes it, and anyone who copies the file is that service account.
Google's own guidance is to avoid keys whenever another option exists. This post walks through how we removed them: finding where keys are used, switching GKE workloads to Workload Identity Federation for GKE, switching workloads on another cloud to Workload Identity Federation, and finally blocking new keys. CI pipelines get only a short section here, because our post on CI OIDC to Google Cloud and Azure covers GitHub Actions and GitLab in depth.
Step 1: find every key and who uses it
List user-managed keys per service account (system-managed keys are rotated by Google and are not the problem):
for sa in $(gcloud iam service-accounts list --project=acme-prod --format='value(email)'); do
gcloud iam service-accounts keys list \
--iam-account="$sa" --managed-by=user \
--format="table[no-heading](name.basename(), validAfterTime, disabled)" \
| sed "s|^|$sa |"
done
Then find out which keys are actually used. Cloud Monitoring exposes per-key authentication metrics, and Policy Intelligence shows the last authentication time for service accounts and keys. We used the activity query:
gcloud policy-intelligence query-activity \
--activity-type=serviceAccountKeyLastAuthentication \
--project=acme-prod
Keys with no authentication in 90 days went to a "disable, wait two weeks, delete" list. Disabling first gives you an undo button. For the rest, the Cloud Audit Logs entries of the calls they made (protoPayload.authenticationInfo.serviceAccountKeyName) told us which hosts were calling from which IP ranges, and that led us to the owning systems.
We ended up with three groups:
Where the key lived | Count | Replacement |
|---|---|---|
Kubernetes secrets on GKE | 17 | Workload Identity Federation for GKE |
EC2 instances and ECS tasks on AWS | 6 | Workload Identity Federation with an AWS provider |
CI variables | 9 | Workload Identity Federation with an OIDC provider |
Unused | 9 | Disabled, then deleted |
Step 2: GKE pods without keys
On GKE, pods can get Google Cloud credentials from the GKE metadata server, tied to their Kubernetes service account. No secret is mounted; tokens are short-lived and fetched on demand.
Enable the workload pool on the cluster and the GKE metadata server on node pools (Autopilot clusters have it on by default):
gcloud container clusters update orders-prod \
--location=europe-west1 \
--workload-pool=acme-prod.svc.id.goog
gcloud container node-pools update default-pool \
--cluster=orders-prod --location=europe-west1 \
--workload-metadata=GKE_METADATA
Now grant roles directly to the Kubernetes service account as an IAM principal. This is the current recommended form and needs no Google service account at all:
gcloud projects add-iam-policy-binding acme-prod \
--role=roles/pubsub.subscriber \
--member="principal://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/acme-prod.svc.id.goog/subject/ns/orders/sa/order-worker" \
--condition=None
The principal identifier uses the project number, not the project ID. The pod spec only needs the Kubernetes service account:
apiVersion: v1
kind: ServiceAccount
metadata:
name: order-worker
namespace: orders
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: order-worker
namespace: orders
spec:
template:
spec:
serviceAccountName: order-worker
containers:
- name: worker
image: europe-west1-docker.pkg.dev/acme-prod/apps/order-worker:2027.01.3
Remove the old GOOGLE_APPLICATION_CREDENTIALS variable and the mounted secret in the same change, otherwise the client libraries keep using the key file (Application Default Credentials check that variable first).
A few services do not yet accept the Kubernetes principal directly for every API. For those, use the older pattern: give the pod's Kubernetes service account roles/iam.workloadIdentityUser on a Google service account and annotate it with iam.gke.io/gcp-service-account. It still uses no keys.
To check from inside a pod which identity it gets:
kubectl -n orders run wi-test --rm -it --restart=Never \
--image=google/cloud-sdk:slim --overrides='{"spec":{"serviceAccountName":"order-worker"}}' \
-- gcloud auth list
Step 3: workloads on AWS without keys
Six jobs on AWS read from BigQuery and Cloud Storage. They used a JSON key stored in AWS Secrets Manager, which meant two secret stores to protect. Workload Identity Federation lets Google Cloud trust the AWS role directly: the job signs a request with its AWS credentials, and Google's Security Token Service exchanges it for a short-lived Google token.
Create a pool and an AWS provider, and restrict it to the roles that should be trusted:
gcloud iam workload-identity-pools create aws-workloads \
--location=global --project=acme-prod \
--display-name="AWS workloads"
gcloud iam workload-identity-pools providers create-aws aws-prod \
--location=global --project=acme-prod \
--workload-identity-pool=aws-workloads \
--account-id=111122223333 \
--attribute-mapping="google.subject=assertion.arn,attribute.aws_role=assertion.arn.extract('assumed-role/{role}/')" \
--attribute-condition="attribute.aws_role in ['bq-export-job', 'gcs-sync-job']"
Grant access to the federated principal set for one role:
gcloud projects add-iam-policy-binding acme-prod \
--role=roles/bigquery.dataViewer \
--member="principalSet://iam.googleapis.com/projects/123456789012/locations/global/workloadIdentityPools/aws-workloads/attribute.aws_role/bq-export-job" \
--condition=None
Generate a credential configuration file. It contains no secret, only instructions for the client library on how to exchange the AWS credentials:
gcloud iam workload-identity-pools create-cred-config \
projects/123456789012/locations/global/workloadIdentityPools/aws-workloads/providers/aws-prod \
--aws --enable-imdsv2 \
--output-file=gcp-wif.json
Ship gcp-wif.json with the job and point GOOGLE_APPLICATION_CREDENTIALS at it. The Google client libraries recognise the external_account type and handle the token exchange.
Step 4: CI pipelines
The same idea applies to CI: GitHub Actions and GitLab issue OIDC tokens per job, and a Workload Identity Federation provider trusts them. Two rules matter most:
Always set an
--attribute-conditionthat pins the repository or project (for GitHub, at leastassertion.repository_owner). Without it, any repository on the same platform could exchange a token for access to your pool.Bind roles to a principal set filtered by repository and, for deploy jobs, by branch or environment.
Our CI OIDC post shows full provider settings and claim conditions for both platforms.
Step 5: block new keys
Once the last key was gone, we enforced the organization policy constraint that prevents key creation:
gcloud resource-manager org-policies enable-enforce \
iam.disableServiceAccountKeyCreation --organization=987654321098
Google Cloud organizations created since 2024 have this constraint enforced by default as part of "secure by default" policies; older organizations need to enable it. We also enforced iam.disableServiceAccountKeyUpload so nobody can upload their own public key as a workaround. For a genuine exception (a third-party SaaS that only accepts a key), we use a dedicated project with a scoped policy exception and a 90-day expiry recorded in the ticket.
Common mistakes
Mistake | Why it hurts | Do this instead |
|---|---|---|
Leaving | Libraries keep using the old key file | Remove the variable and the secret in the same deploy |
Using the project ID in principal identifiers | Bindings do not match, access denied | Use the project number |
Provider without an attribute condition | Any identity from that issuer may be trusted | Pin the account, repository or role |
Deleting unknown keys immediately | Breaks a forgotten system with no rollback | Disable first, delete after two quiet weeks |
Granting | Same blast radius as the old key | Grant the narrowest predefined role per resource |
Key takeaways
Service account keys are long-lived secrets; treat each one as a liability.
Find usage with key authentication activity and audit logs before removing anything.
GKE workloads should use Workload Identity Federation for GKE with direct principal bindings.
Workloads on AWS, Azure or CI can exchange their native identity for short-lived Google tokens.
Finish by enforcing the organization policies that block key creation and upload.
References
Google Cloud: Best practices for managing service account keys — https://cloud.google.com/iam/docs/best-practices-for-managing-service-account-keys
Google Cloud: Workload Identity Federation — https://cloud.google.com/iam/docs/workload-identity-federation
Google Cloud: Authenticate to Google Cloud APIs from GKE workloads — https://cloud.google.com/kubernetes-engine/docs/how-to/workload-identity
Google Cloud: Configure Workload Identity Federation with AWS or Azure — https://cloud.google.com/iam/docs/workload-identity-federation-with-other-clouds
Google Cloud: Restricting service account usage (organization policies) — https://cloud.google.com/resource-manager/docs/organization-policy/restricting-service-accounts
Google Cloud: Monitor usage patterns for service accounts and keys — https://cloud.google.com/iam/docs/service-account-monitoring
Comments
0No comments yet. Be the first to comment!
Sign In to post a comment.