Skip to main content
Security and Compliance

Service Accounts Best Practices: Keys, Impersonation, and Workload Identity Federation

Use Google Cloud service accounts safely: attached accounts, impersonation instead of keys, Workload Identity Federation for GitHub and AWS, and key clean-up.

Last checked against Google's official documentation on .

Service Accounts Best Practices: Keys, Impersonation, and Workload Identity Federation

Every application in Google Cloud needs an identity. A Cloud Run service reading from a bucket, a nightly job writing to BigQuery, a GitHub workflow deploying code: each one acts as a service account. Service accounts are not the problem. The way people give them credentials is.

People are different: your staff sign in with Google Workspace accounts protected by passwords, 2-Step Verification, and session controls. Workloads have none of that by default.

For years the standard approach was to download a JSON key and paste it wherever the code ran. Those keys are now one of the most common causes of Google Cloud breaches. This guide explains the safer options Google provides, in the order you should consider them, and how to clean up the keys you already have.

Key Takeaways

  • Create one service account per application, with only the roles it needs.
  • Attach service accounts to Google Cloud resources; they get credentials automatically.
  • Use impersonation for admins and scripts instead of keys.
  • Use Workload Identity Federation for GitHub, AWS, Azure, and on-premises workloads.
  • Find and delete old keys, then keep key creation blocked by policy.

Table of contents

Open Table of contents

How to Choose a Credential

Choosing a credential for a Google Cloud workload

Where the code runsUseKey needed?
On Google Cloud (Compute Engine, Cloud Run, GKE, functions)Attached service accountNo
An admin’s laptop running gcloud or TerraformImpersonation from the admin’s own accountNo
GitHub Actions, GitLab, or another CI systemWorkload Identity FederationNo
AWS or AzureWorkload Identity FederationNo
On-premises with an OIDC or SAML identity providerWorkload Identity FederationNo
A third-party product that only accepts a key fileA key, as a last resortYes

The pattern is clear: keys are the exception.

Dedicated Service Accounts per Application

The default compute service account is created in every project with Compute Engine enabled and is used by every VM unless you choose otherwise. In organizations created before May 3, 2024, it often has the Editor role, which gives any VM broad control of the project. Enforcing iam.automaticIamGrantsForDefaultServiceAccounts stops new automatic grants, but Google notes it doesn’t remove Editor from existing default service accounts, so remove those grants yourself.

Instead:

  1. Create a service account per application, for example payroll-api@acme-payroll-prod.iam.gserviceaccount.com.
  2. Grant it the predefined roles it needs on the specific resources, such as Storage Object Viewer on one bucket.
  3. Attach it to the VM, Cloud Run service, or function when you deploy.

Google’s best practices also recommend single-purpose accounts, managing access on each service account rather than at project or folder level, watching for cross-project impersonation chains (lateral movement insights), and naming them so their purpose is obvious. Disable unused accounts before deleting them: a recreated account with the same name is a new identity and loses the old IAM bindings.

Attached Service Accounts

When a service account is attached to a Google Cloud resource, the platform supplies short-lived credentials through the metadata server. Client libraries pick them up automatically through Application Default Credentials. There is nothing to store, rotate, or leak.

This covers most workloads. If your code runs on Google Cloud and still uses a key file, that is the first thing to change.

Impersonation for Admins and Scripts

Admins often need to run commands as a service account, for example to test permissions or apply Terraform. Instead of downloading a key, grant the admin (or better, an admin group) the Service Account Token Creator role on that service account, then run:

gcloud config set auth/impersonate_service_account \
  terraform@acme-platform.iam.gserviceaccount.com

Every action is logged with both the admin’s identity and the service account. The access token gcloud receives lasts one hour by default, and there is no key file to store or leak.

Treat Token Creator as a powerful role. Whoever holds it can act as the service account, with all its permissions.

Workload Identity Federation

Workload Identity Federation lets external workloads exchange their own identity token for a short-lived Google Cloud token. You create a workload identity pool, add a provider for the external system, and grant the external identity access to a service account or directly to resources.

A typical GitHub Actions setup:

  1. Create a pool, for example github-pool.
  2. Add an OIDC provider with issuer https://token.actions.githubusercontent.com.
  3. Add an attribute condition that limits access to your organization’s repositories, such as assertion.repository_owner == 'acme'. Google says you must use a condition like this, because GitHub uses one issuer URL for every organization; without it, any GitHub repository could try to use the pool. You can also restrict it to a branch, for example && assertion.ref == 'refs/heads/main'.
  4. Grant roles directly to the repository’s federated identity (Google’s recommended option), or let it impersonate a deployment service account where an API doesn’t support federated identities.
  5. In the workflow, use Google’s google-github-actions/auth action with the provider name instead of a key secret.

The same model works for AWS roles, Azure managed identities, and on-premises identity providers that issue OIDC or SAML tokens.

Cleaning Up Existing Keys

Most older organizations have keys scattered across projects. Clean them up in this order:

  1. Inventory. List user-managed keys across the organization with Cloud Asset Inventory, or check Security Command Center findings for old keys.
  2. Find usage. Check when each key was last used; the console shows key activity, and Cloud Audit Logs record authentication with keys.
  3. Replace. Move each workload to an attached account, impersonation, or federation.
  4. Disable, then delete. Disable a key first and wait a week for complaints, then delete it.
  5. Enforce. Keep iam.managed.disableServiceAccountKeyCreation enforced, with project-level exceptions only for vendors that genuinely need a key. Our organization policies guide covers this constraint.

If You Must Use a Key

Some third-party tools only accept a key file. In that case:

  • Put the service account in its own project with nothing else in it.
  • Give it the narrowest roles possible.
  • Store the key in a secret manager, never in code or chat.
  • Rotate it on a schedule and alert on its use from unexpected IP addresses.
  • Set an expiry for new keys with the iam.serviceAccountKeyExpiryHours organization policy (set values from 1 hour up to 2,160 hours, which is 90 days). It applies only to keys created after you set it.

Leaked keys are disabled automatically

Since June 16, 2024, Google Cloud automatically disables service account keys that its detection service finds exposed in public repositories and other public places. This is controlled by the iam.serviceAccountKeyExposureResponse organization policy. DISABLE_KEY, the default when you set nothing, disables the key and sends a notification. WAIT_FOR_ABUSE does not disable keys proactively, but Google may still disable a key that is used in ways that adversely affect Google Cloud. Either way, Google emails the project owners and the security contacts listed in Essential Contacts, so make sure those contacts reach a monitored group rather than one person’s inbox. Leave the policy at DISABLE_KEY: an outage from a disabled leaked key is far cheaper than a breach.

Common Mistakes

  • One service account for everything in a project.
  • Editor on the default compute service account left in place.
  • Keys in Git repositories, including private ones.
  • Workload Identity pools without attribute conditions, which trust far more than intended.
  • Token Creator granted widely, which is equivalent to sharing the key.

Worked Example: Removing a Key From a Cloud Run App

A common legacy pattern is a Cloud Run service that reads a key file from an environment variable to access BigQuery. Moving it to an attached identity takes about an hour:

  1. Create a dedicated service account, for example reports-api@acme-reports-prod.iam.gserviceaccount.com.

  2. Grant only what the app uses: BigQuery Job User on the project and BigQuery Data Viewer on the dataset.

  3. Redeploy with the identity attached:

    gcloud run deploy reports-api --source . --region asia-south1 \
      --service-account reports-api@acme-reports-prod.iam.gserviceaccount.com
  4. Remove the key code path. Client libraries use Application Default Credentials, so deleting the code that loads the file is usually enough.

  5. Delete the environment variable or secret that held the key.

  6. Disable the old key, wait a week, then delete it.

Troubleshooting

“Permission iam.serviceAccounts.getAccessToken denied.” The caller is trying to impersonate a service account without Service Account Token Creator on it. Grant the role on that specific service account, not the whole project.

“Permission iam.serviceAccounts.actAs denied” when deploying. The deployer needs Service Account User on the service account being attached to the resource.

Federation fails with an attribute condition error. The external token does not match the condition. Check the token’s claims, for example the repository and branch in GitHub’s OIDC token, and correct the condition or the workflow.

Workloads suddenly lose access after a policy change. If default service accounts lost Editor, the workloads were relying on it. Create dedicated service accounts with the right roles instead of restoring Editor.

Naming and Inventory

Service accounts multiply quickly. A simple convention keeps them understandable years later:

PartExamplePurpose
Application or jobpayroll-apiWhat uses it
Environment, if shared projects exist-prodWhere it runs
Description field”Payroll API on Cloud Run, owner team-payroll”Who to ask

Avoid names like sa1, test, or a person’s name. Use the description field for the owner and the system it belongs to, because the console shows it next to the account.

Review service accounts every quarter:

  • Accounts with no recent authentication are candidates for disabling.
  • Accounts with Owner or Editor need narrower roles.
  • Accounts with user-managed keys need a plan to remove them.
  • Accounts used across projects need a reason.

The IAM recommender and service account insights in the console highlight unused accounts and permissions, which makes this review quick.

Conclusion

Service accounts are safe when they never have a key. Attach them on Google Cloud, impersonate them as an admin, and federate them from everywhere else. Clean up old keys gradually, then keep the door closed with organization policy.

If your developers sign in with Google Workspace accounts, impersonation means their normal, 2SV-protected identity is the only credential they need. Tomorrow’s guide covers Identity-Aware Proxy, which uses those same identities to protect internal apps without a VPN.


Official Google documentation:

Related reading:

This guide contains referral or affiliate links. If you sign up through one, Workspace Blog may earn a commission at no extra cost to you. Read our referral and advertising disclosure.

Frequently Asked Questions

Why are service account keys considered risky?
A service account key is a long-lived credential in a file. Anyone who gets a copy can act as the service account from anywhere until the key is deleted. Keys leak through code repositories, laptops, and CI logs, which is why Google blocks key creation by default in new organizations.
What is Workload Identity Federation?
Workload Identity Federation lets workloads outside Google Cloud, such as GitHub Actions, AWS, Azure, or an on-premises system with an OIDC or SAML identity provider, exchange their own credentials for short-lived Google Cloud tokens. No service account key is needed.
What is service account impersonation?
Impersonation lets a user or another service account get short-lived credentials for a service account, if they hold a role such as Service Account Token Creator on it. Admins can run gcloud commands as a service account without ever downloading its key.
Should applications use the default compute service account?
No. The default service account is shared by every VM in the project and, in older organizations, has the Editor role. Create a dedicated service account per application with only the roles it needs, and attach it to the VM, Cloud Run service, or function.
How do I find old service account keys?
In the console, the Service accounts page shows keys per account, and the IAM recommender and Security Command Center flag unused or old keys. Cloud Asset Inventory can list all user-managed keys across the organization.