Migrate from service account keys Stay organized with collections Save and categorize content based on your preferences.
Service account keys are commonly used to authenticate toGoogle Cloud services. However, they can also become a security risk if they'renot managed properly, increasing your vulnerability to threats like credentialleakage, privilege escalation, information disclosure, and non-repudiation.
In many cases, you can authenticate withmore securealternatives to service account keys. This guide helps you tomigrate from using service account keys as your primary authentication mechanismto using more secure alternatives, with occasional exceptions where serviceaccount keys are truly necessary.
This document is intended for security administrators who want to improve theirsecurity posture by reducing the usage of service account keys in favor of moresecure authentication mechanisms. These security administrators might beresponsible for the security of existing production workloads, developerworkflows, and internal processes that use service account keys.
Overview
Removing service account keys from existing workloads requires careful planningto prevent accidental disruption. The following migration plan is designed toallow you to enforce centralized controls while minimizing disruption todevelopers.
This migration plan includes three phases:
- Assess: In this phase, you assess your existing environment to understandwhere service account keys exist and whether the keys are in use.
- Plan: In this phase, you decide which controls you will eventually deployand communicate the migration plan to stakeholders.
- Deploy: In this phase, you begin refactoring workloads to authenticatewith more secure alternatives to service account keys. You also buildadditional capabilities to continuously monitor your environment and mitigatefuture risk.
Assess service account key use
In this phase, you assess your existing environment to understand where serviceaccount keys exist and whether the keys are in use.
The following sections describe the data you can collect to better understandhow service account keys are used in your organization.
Gather data on key usage
First, identify where service account keys exist and how they're used.
Google Cloud providestools to understand service accountusage. These tools help you determine which service accountsand keys were recently used to authenticate, which service accounts haven't beenused in the past 90 days, and which service accounts haveoverly privileged roles.
You can combine information from all of these tools to get a better picture ofhow service accounts and keys are used across your organization.For an example of how to combine information from these various sources acrossyour entire organization, see thedeployable referencearchitecture on GitHub. This reference architectureaggregates data from various tools and regularly exports it to aBigQuery table for analysis.
The reference architecture deploys a data pipeline that queriesCloud Asset Inventory to identify service account keys in your organization. Then, thedata pipeline combines that data with data about key usage and permission usagefor the associated account. The resulting table,sa_key_usage, helps youanswer questions like the following:
- How many persistent keys have been created? This number can be useful as ahigh-level metric to track progress as you migrate away from keys.
- Which projects and service accounts use keys? This information helps youidentify the owners of workloads that use service account keys.
- Which keys are inactive? You can likely delete these keys without furtherassessment from workload owners.
- Which keys are associated with service accounts that have recommendationsabout excess permissions? If a service account key is associated with anoverly privileged service account, especially one with an Owner, Editor, orViewer role, the key might be particularly high-risk. Looking for serviceaccounts that haverole recommendations can help youidentify which service accounts are overly privileged. After you identifythese service accounts, you might decide to prioritize these workloads formigration. You can also choose to apply the role recommendations toproactively reduce excess permissions.
This data pipeline runs daily and writes to a date-partitionedBigQuery table. You can use this table to investigate specificservice accounts or keys, or to track remediation progress using a dashboardtool likeLooker Studio.
Enrich key usage data with additional context
After you gather data about key usage, you can optionally enrich your data withadditional data sources. We recommend adding data sources that you already usefor tracking governance and provenance of resources. Depending on your existinggovernance, you might add additional data such as the following:
- Ownership information from a configuration management database (CMDB) orsimilar system.
- Governance information configured inproject labels, like the teamor cost center responsible for a project.
- Environment information about keys used for workloads in environments externalto Google Cloud.
Create a plan for reducing service account key usage
Before you can deploy any changes to reduce service account key usage, you needto determine which workloads and environments will be affected and how you willenforce those changes. You also need to communicate this plan across yourbusiness and make sure that workload owners support the plan.
The following sections introduce key topics your plan should address. Yourspecific plan will vary based on the size of your organization and the specificrequirements of your workloads.
Decide the responsibility of current workload owners
Although a central security team can assess which keys exist, a successfulmigration requires effort from workload owners. For keys in scope for migration,workload owners must determine which of the available authentication methodswill work for their use case, then execute that migration.
Consider how to balance improvements to your existing security posture againstthe effort required from workload owners. The following sections describe twosample approaches: one that heavily prioritizes improvements to your securityposture, and one that heavily prioritizes minimizing effort from workloadowners. Your actual approach might vary—for example, you might decide toindividually select which workloads are in scope.
Example: All current workloads are evaluated for migration
One possible approach is to enforce service account key controls for allexisting and future workloads. This involves steps like the following:
- Collaborating with workload owners to evaluate their key usage for existingworkloads.
- Requiring that workload owners migrate all existing workloads with key usage,unless they have been granted an exception.
- Preventing all future workloads from using service account keys, unless theyhave been granted an exception.
This approach prioritizes improvements to your existing security posture butrequires more effort from developers and workload owners in the short term. Tosuccessfully execute a plan like this, you must have commitment from workloadowners to participate in workload review and refactoring.
Example: No current workloads are evaluated for migration
Another approach is to allow existing workloads an automatic exception tocontinue using service account keys and only apply new controls on futureworkloads.
This approach improves the security posture of future workloads and minimizesthe responsibility of current workload owners. However, it doesn't improvethe security posture of existing workloads.
Identify quick wins
In your assessment, you might identify keys that can be safely deleted withoutfurther remediation work from workload owners. For example, if a key has noactivity for 90 days, or is related to resources that are no longer active, youmight be able to remove it safely without needing to migrate to a differentauthentication mechanism.
Make a list of keys that meet this criteria. You will use this list during thedeployment phase todelete unnecessary keys. Before youadd a key to the list, confirm whether there are use cases that require theservice account key infrequently, such as emergency production access relying onservice account keys.
Plan where to enforce organization policy changes
To successfully migrate away from using service account keys, you need toprevent new keys from being created. During the deployment phase, you enforcetheiam.disableServiceAccountKeyCreationorganization policy constraint to prevent the creation of new service accountkeys.
Although this constraint doesn't prevent the usage of existing keys, it mightdisrupt existing workloads that regularly rotate their keys. Before you startthe deployment phase, decide where you will enforce it in your resourcehierarchy to minimize disruption.
You might prefer to initially enforce the constraint at the project or folderlevel instead of the organization level. For example, you might enforce theconstraint on the folder used for your development environment before deployingit to production folders. Or, in a large organization with many teams, you mightenforce the constraint on a folder for a single team first, and then enforce theconstraint for additional folders as you migrate them.
You can useorganization policies with tags toconditionally enforce organization policies at the project or folder level.
Design an exceptions process
Although the goal of this migration is to reduce or eliminate service accountkey usage, there are some legitimate use cases that require service accountkeys. Even if no existing workloads require service account keys, it's possiblethat future workloads will. Therefore, you must define an operational process toevaluate and approve exceptions for use cases that require service account keys.
Define a process for workload owners to request an exception that allows theirworkload to use service account keys. Ensure that the decision makersresponsible for granting an exception have the technical knowledge to validatethe use case, consult with the workload owners on which of the more securealternatives to service account keys might be more appropriate, and adviseworkload owners aboutbest practices for managing service accountkeys.
Communicate upcoming changes to workload owners
After you've designed a plan, you need to clearly communicate that plan acrossyour organization and make sure that stakeholders, particularly senior leaders,are willing to commit to the migration.
While the specific migration details will vary for your organization, considerincluding the following topics in your communication plan:
- The negative impact that insecure service account keys can have on theorganization, and the motivations that drive your migration away from serviceaccount keys.
- The new security controls to prevent service account key creation and how thiscan impact existing processes.
- Guidance for developers to identifymore secure alternatives to serviceaccount keys.
- The process for teams to request an exception to allow service account keys,including how frequently this exception is re-evaluated.
- The timeline to enforce your proposed changes.
Work with workload owners to refine your plan and ensure that it works acrossyour organization.
Deploy controls and refactor workloads
After you create a plan and communicate it to workload owners, you can beginmigrating away from service account keys.
In this phase, you begin refactoring workloads to authenticate with more securealternatives to service account keys. You also build additional capabilities tocontinuously monitor your environment and mitigate future risk.
The following sections describe the steps you can take to refactor workloads anddelete keys with minimal disruption. You can choose to do these steps in anyorder, based on the priority and effort required for your organization.
Enforce controls to stop the creation of new service account keys
To stop the creation of new service account keys, you enforce theiam.disableServiceAccountKeyCreation organizationpolicy constraint.
However, before enforcing this constraint, you need to addtagsto any projects or folders that will be exempt from the policy. You might allowexceptions for existing workloads that are unable to migrate from serviceaccount keys, or for new workloads that have a legitimate reason to authenticateonly with service account keys.
After you add tags to exempt projects and folders, you can set anorganizationpolicy with tags to enforce theiam.disableServiceAccountKeyCreation constraint for non-exempt projects andfolders.
To prevent the creation of service account keys in all non-exempt projects andfolders, do the following:
- Ensure that you have the Tag Administrator role (
roles/resourcemanager.tagAdmin) and the Organization Policy Administrator role (roles/orgpolicy.policyAdmin) at the organization level. To learn how to grant roles at the organization level, seeManage access to projects, folders, and organizations. At the organization level, create a tag key and tag value that you will use to define whether a resource should be exempt from the organization policy. We recommend creating a tag with the key
disableServiceAccountKeyCreationand the valuesenforcedandnot_enforced.To learn how to create tag keys and tag values, seeCreating and defining a new tag.
Attach the
disableServiceAccountKeyCreationtag to the organization and set its value toenforced. All resources in the organization inherit this tag value, unless it's overwritten with a different tag value.To learn how to attach tags to resources, seeAttaching tags to resources.
- For each project or folder that you want to exempt from the organization policy, attach the
disableServiceAccountKeyCreationtag and set its value tonot_enforced. Setting a tag value for a project or folder in this way overrides the tag value inherited from the organization. Create an organization policy that prevents the creation of service account keys for all resources except the exempt resources. This policy should have the following rules:
Configure the
iam.disableServiceAccountKeyCreationconstraint to not be enforced on any resources with thedisableServiceAccountKeyCreation: not_enforcedtag. The condition in this rule should look like the following:"resource.matchTag('ORGANIZATION_ID/disableServiceAccountKeyCreation', 'not_enforced')"- Configure the
iam.disableServiceAccountKeyCreationconstraint to be enforced on all other resources.
Remediate existing workloads
For each workload that uses service account keys, collaborate with the workloadowners to choose and implement an alternative authentication method.
When you access Google Cloud services by using the Google Cloud CLI, Cloud Client Libraries, tools that support Application Default Credentials (ADC) like Terraform, or REST requests, use the following diagram to help you choose an authentication method:
This diagram guides you through the following questions:
- Are you running code in a single-user development environment, such as your own workstation, Cloud Shell, or a virtual desktop interface?
- If yes, proceed to question 4.
- If no, proceed to question 2.
- Are you running code in Google Cloud?
- If yes, proceed to question 3.
- If no, proceed to question 5.
- Are you running containers in Google Kubernetes Engine?
- If yes, use Workload Identity Federation for GKE to attach service accounts to Kubernetes pods.
- If no,attach a service account to the resource.
Does your use case require a service account?
For example, you want to configure authentication and authorization consistently for your application across all environments.
- Does your workload authenticate with an external identity provider that supportsworkload identity federation?
- If yes, configure Workload Identity Federation to let applications running on-premises or on other cloud providers use a service account.
- If no,create a service account key.
In some cases, you might not be able to use any authentication method other thanservice account keys. Examples of where a service account key might be your onlyfeasible option include the following:
- You're using commercial off-the-shelf products (COTS) orsoftware-as-a-service (SaaS) applications that ask you to input aGoogle Cloud service account key directly into its user interface.
- Your workload is running outside of Google Cloud and isn't authenticatedwith an identity provider that can supportworkload identityfederation.
In cases where you must keep using service account keys, ensure that you'refollowing thebest practices for managing service accountkeys.
You might also decide not to remediate certain workloads because you assess thatthe risk of continuing to use service account keys doesn't justify the cost ofswitching to a different authentication method.
Delete unnecessary keys
If you are certain that a service account key isn't needed, you should deletethe key. Unnecessary keys include the following:
Keys with no recent usage or keys that are related to unused resources, whichyou identified in theIdentify quick wins section ofthis page.
Keys for workloads that have migrated to other authentication methods.
After you delete all of the service account keys in a project, ensure thatthe
iam.disableServiceAccountKeyCreationconstraint is enforced for thatproject. If the project was previously exempt from this constraint, removethe tag that allowed for the exemption.
To delete keys safely, we recommend that youdisable the keybefore deleting it. Deleting is irreversible, but disabling it lets you quicklyre-enable the key if you identify unexpected issues. After you disable the key,wait until you're sure that removing the key permanently won't cause issues,thendelete the key. If, after disabling the key, you identifyunexpected issues, re-enable the key, resolve the issues, and then repeat theprocess until you can safely delete the key.
Use built-in controls to help respond to leaked keys
Google Cloud offers tools and services to help you detect andrespond to leaked service account keys. Consider using the following mechanismsto help you respond to leaked service account keys:
- TheService Account Key Exposure Responseconstraint lets you automatically disable exposedkeys that Google Cloud detects.
Ongoing improvements to service account management
Wherever possible, implementbest practices for managing service accountkeys. Improving your key management processes can helpmitigate the risk of any remaining service account keys in your organization.
What's next
- Best practices for using service accounts
- Best practices for managing service account keys
- Build a collaborative incident management process
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.