Disable and enable service account keys

This page explains how to disable and enable service account keys using the Google Cloud console, the Google Cloud CLI, the Identity and Access Management API, or one of the Google Cloud Client Libraries.

Before you begin

  • Enable the IAM API.

    Enable the API

  • Set up authentication.

    Select the tab for how you plan to use the samples on this page:

    gcloud

    You can use the gcloud CLI samples on this page from either of the following development environments:

    • Cloud Shell: To use an online terminal with the gcloud CLI already set up, activate Cloud Shell.

      At the bottom of this page, a Cloud Shell session starts and displays a command-line prompt. It can take a few seconds for the session to initialize.

    • Local shell: To use the gcloud CLI in a local development environment, install and initialize the gcloud CLI.

    Java

    To use the Java samples on this page from a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. Create local authentication credentials for your Google Account:

      gcloud auth application-default login

    For more information, see Set up authentication for a local development environment in the Google Cloud authentication documentation.

    REST

    To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.

      Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init

  • Understand service account credentials.

Required roles

To get the permissions that you need to disable and enable service account keys, ask your administrator to grant you the Service Account Key Admin (roles/iam.serviceAccountKeyAdmin) IAM role on the project, or the service account whose keys you want to manage. For more information about granting roles, see Manage access.

You might also be able to get the required permissions through custom roles or other predefined roles.

For more information, see Service Accounts roles.

IAM basic roles also contain permissions to manage service account keys. You should not grant basic roles in a production environment, but you can grant them in a development or test environment.

Disable a service account key

Disabling a service account key prevents you from using the key to authenticate with Google APIs. You can enable a disabled key at any time.

Before you delete a service account key, we recommend that you disable the key, then wait until you are sure that the key is no longer needed. You can then delete the key.

You can view disabled keys in the Google Cloud console, but you cannot use the Google Cloud console to disable a key. Use the gcloud CLI or the REST API instead.

gcloud

Execute the gcloud iam service-accounts keys disable command to disable a service account key.

Replace the following values:

  • KEY_ID: The ID of the key to disable. To find the key's ID, list all keys for the service account, identify the key that you want to disable, and then copy its ID.
  • SA_NAME: The name of the service account that the key belongs to.
  • PROJECT_ID: Your Google Cloud project ID.
gcloud iam service-accounts keys disable KEY_ID \
    --iam-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com \
    --project=PROJECT_ID

Output:

Disabled key [KEY_ID] for service account
[SA_NAME@PROJECT_ID.iam.gserviceaccount.com]

Java

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Java API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.


import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.DisableServiceAccountKeyRequest;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;


public class DisableServiceAccountKey {

  public static void main(String[] args) throws IOException {
    // TODO(Developer): Replace the below variables before running.
    String projectId = "gcloud-project-id";
    String serviceAccountName = "service-account-name";
    String serviceAccountKeyName = "service-account-key-name";

    disableServiceAccountKey(projectId, serviceAccountName, serviceAccountKeyName);
  }

  // Disables a service account key.
  public static void disableServiceAccountKey(String projectId, String serviceAccountName,
      String serviceAccountKeyName) {
    // Initialize the IAM service.
    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e);
      return;
    }

    // Construct the service account email.
    // You can modify the ".iam.gserviceaccount.com" to match the service account name in which
    // you want to disable the key.
    // See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys?hl=en#disabling
    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";

    try {
      DisableServiceAccountKeyRequest
          disableServiceAccountKeyRequest = new DisableServiceAccountKeyRequest();
      // Use the IAM service to disable the service account key.
      service
          .projects()
          .serviceAccounts()
          .keys()
          .disable(String
              .format("projects/%s/serviceAccounts/%s/keys/%s", projectId, serviceAccountEmail,
                  serviceAccountKeyName), disableServiceAccountKeyRequest)
          .execute();

      System.out.println("Disabled service account key: " + serviceAccountKeyName);
    } catch (IOException e) {
      System.out.println("Failed to disable service account key: \n" + e);
    }
  }

  private static Iam initService() throws GeneralSecurityException, IOException {
    /* Use the Application Default Credentials strategy for authentication. For more info, see:
     https://cloud.google.com/docs/authentication/production#finding_credentials_automatically */
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

    // Initialize the IAM service, which can be used to send requests to the IAM API.
    return new Iam.Builder(
        GoogleNetHttpTransport.newTrustedTransport(),
        GsonFactory.getDefaultInstance(),
        new HttpCredentialsAdapter(credential))
        .setApplicationName("service-accounts")
        .build();
  }
}

REST

The projects.serviceAccounts.keys.disable method disables a service account key.

Before using any of the request data, make the following replacements:

  • PROJECT_ID: Your Google Cloud project ID. Project IDs are alphanumeric strings, like my-project.
  • SA_NAME: The name of the service account whose key you want to disable.
  • KEY_ID: The ID of the key that you want to disable. To find the key's ID, list all keys for the service account, identify the key that you want to disable, and then copy its ID from the end of the name field. The key's ID is everything after keys/.

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com/keys/KEY_ID:disable

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
}

Enable a service account key

After you disable a service account key, you can enable the key at any time, then use the key to authenticate with Google APIs.

You cannot use the Google Cloud console to enable service account keys. Use the gcloud CLI or the REST API instead.

gcloud

Execute the gcloud iam service-accounts keys enable command to enable a service account key.

Replace the following values:

  • KEY_ID: The ID of the key to enable. To find the key's ID, list all keys for the service account, identify the key that you want to enable, and then copy its ID.
  • SA_NAME: The name of the service account that the key belongs to.
  • PROJECT_ID: Your Google Cloud project ID.
gcloud iam service-accounts keys enable KEY_ID \
    --iam-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com\
    --project=PROJECT_ID

Output:

Enabled key [KEY_ID] for service account
[SA_NAME@PROJECT_ID.iam.gserviceaccount.com]

Java

To learn how to install and use the client library for IAM, see IAM client libraries. For more information, see the IAM Java API reference documentation.

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.


import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.EnableServiceAccountKeyRequest;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;


public class EnableServiceAccountKey {

  public static void main(String[] args) {
    // TODO(Developer): Replace the below variables before running.
    String projectId = "gcloud-project-id";
    String serviceAccountName = "service-account-name";
    String serviceAccountKeyName = "service-account-key-name";

    enableServiceAccountKey(projectId, serviceAccountName, serviceAccountKeyName);
  }

  // Enables a service account key.
  public static void enableServiceAccountKey(String projectId, String serviceAccountName,
      String serviceAccountKeyName) {
    // Initialize the IAM service.
    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e);
      return;
    }

    // Construct the service account email.
    // You can modify the ".iam.gserviceaccount.com" to match the service account name in which
    // you want to enable the key.
    // See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys?hl=en#enabling
    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";

    try {
      EnableServiceAccountKeyRequest
          enableServiceAccountKeyRequest = new EnableServiceAccountKeyRequest();
      // Use the IAM service to enable the service account key.
      service
          .projects()
          .serviceAccounts()
          .keys()
          .enable(String
              .format("projects/%s/serviceAccounts/%s/keys/%s", projectId, serviceAccountEmail,
                  serviceAccountKeyName), enableServiceAccountKeyRequest)
          .execute();

      System.out.println("Enabled service account key: " + serviceAccountKeyName);
    } catch (IOException e) {
      System.out.println("Failed to enable service account key: \n" + e);
    }
  }

  private static Iam initService() throws GeneralSecurityException, IOException {
    /* Use the Application Default Credentials strategy for authentication. For more info, see:
     https://cloud.google.com/docs/authentication/production#finding_credentials_automatically */
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

    // Initialize the IAM service, which can be used to send requests to the IAM API.
    return new Iam.Builder(
        GoogleNetHttpTransport.newTrustedTransport(),
        GsonFactory.getDefaultInstance(),
        new HttpCredentialsAdapter(credential))
        .setApplicationName("service-accounts")
        .build();
  }
}

REST

The projects.serviceAccounts.keys.enable method enables a service account key.

Before using any of the request data, make the following replacements:

  • PROJECT_ID: Your Google Cloud project ID. Project IDs are alphanumeric strings, like my-project.
  • SA_NAME: The name of the service account whose key you want to enable.
  • KEY_ID: The ID of the key that you want to enable. To find the key's ID, list all keys for the service account, identify the key that you want to enable, and then copy its ID from the end of the name field. The key's ID is everything after keys/.

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com/keys/KEY_ID:enable

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
}

What's next

Try it for yourself

If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.

Get started for free