Creating and managing service account keys

This page explains how to create and manage service account keys using the Google Cloud Console, the gcloud command-line tool, the Identity and Access Management API, or one of the Google Cloud Client Libraries.

Before you begin

Required permissions

To allow a user to manage service account keys, grant the Service Account Key Admin role (roles/iam.serviceAccountKeyAdmin). 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.

Creating service account keys

To use a service account from outside of Google Cloud, such as on other platforms or on-premises, you must first establish the identity of the service account. Public/private key pairs provide a secure way of accomplishing this goal. When you create a service account key, the public portion is stored on Google Cloud, while the private portion is available only to you. For more information about public/private key pairs, see Service account keys.

You can create a service account key using the Cloud Console, the gcloud tool, the serviceAccounts.keys.create() method, or one of the client libraries. A service account can have up to 10 keys.

In the examples below, sa-name is the name of your service account, and project-id is the ID of your Google Cloud project. You can retrieve the sa-name@project-id.iam.gserviceaccount.com string from the Service Accounts page in the Cloud Console.

Console

  1. In the Cloud Console, go to the Service Accounts page.

    Go to Service accounts

  2. Select a project.

  3. Click the email address of the service account that you want to create a key for.

  4. Click the Keys tab.

  5. Click the Add key drop-down menu, then select Create new key.

  6. Select JSON as the Key type and click Create.

Clicking Create downloads a service account key file. After you download the key file, you cannot download it again.

The downloaded key has the following format, where private-key is the private portion of the public/private key pair:

{
  "type": "service_account",
  "project_id": "project-id",
  "private_key_id": "key-id",
  "private_key": "-----BEGIN PRIVATE KEY-----\nprivate-key\n-----END PRIVATE KEY-----\n",
  "client_email": "service-account-email",
  "client_id": "client-id",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service-account-email"
}

Make sure to store the key file securely, because it can be used to authenticate as your service account. You can move and rename this file however you would like.

You can use service account key files to authenticate an application as a service account.

gcloud

Execute the gcloud iam service-accounts keys create command to create service account keys.

Replace the following values:

  • key-file: The path to a new output file for the private key—for example, ~/sa-private-key.json.
  • sa-name: The name of the service account to create a key for.
  • project-id: Your Google Cloud project ID.
gcloud iam service-accounts keys create key-file \
    --iam-account=sa-name@project-id.iam.gserviceaccount.com

Output:

created key [e44da1202f82f8f4bdd9d92bc412d1d8a837fa83] of type [json] as
[/usr/home/username/key-file] for
[sa-name@project-id.iam.gserviceaccount.com]

The service account key file is now downloaded to your machine. After you download the key file, you cannot download it again.

The downloaded key has the following format, where private-key is the private portion of the public/private key pair:

{
  "type": "service_account",
  "project_id": "project-id",
  "private_key_id": "key-id",
  "private_key": "-----BEGIN PRIVATE KEY-----\nprivate-key\n-----END PRIVATE KEY-----\n",
  "client_email": "service-account-email",
  "client_id": "client-id",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/service-account-email"
}

Make sure to store the key file securely, because it can be used to authenticate as your service account. You can move and rename this file however you would like.

You can use service account key files to authenticate an application as a service account.

REST

The projects.serviceAccounts.keys.create method creates a key for a service account.

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 that you want to create a key for.
  • KEY_ALGORITHM: Optional. The key algorithm to use for the key. The default, which is subject to change, is a 2,048-bit RSA key. For a list of all possible values, see the ServiceAccountKeyAlgorithm reference.

HTTP method and URL:

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

Request JSON body:

{
  "keyAlgorithm": "KEY_ALGORITHM"
}

To send your request, expand one of these options:

The response contains a key for your service account. The returned key has the following format, where ENCODED_PRIVATE_KEY is the private portion of the public/private key pair, encoded in base64.

{
  "name": "projects/PROJECT_ID/serviceAccounts/SERVICE_ACCOUNT_EMAIL/keys/KEY_ID",
  "privateKeyType": "TYPE_GOOGLE_CREDENTIALS_FILE",
  "privateKeyData": "ENCODED_PRIVATE_KEY",
  "validAfterTime": "DATE",
  "validBeforeTime": "DATE",
  "keyAlgorithm": "KEY_ALG_RSA_2048"
}

To create a key file that you can use to authenticate as the service account, decode the private key data and save it in a file:

Linux

Run the following command:

echo 'ENCODED_PRIVATE_KEY' | base64 --decode > PATH

Replace PATH with the path of the file that you want to save the key to. Use the .json file extension.

macOS

Run the following command:

echo 'ENCODED_PRIVATE_KEY' | base64 --decode > PATH

Replace PATH with the path of the file that you want to save the key to. Use the .json file extension.

PowerShell

  1. Save the encoded private key data (ENCODED_PRIVATE_KEY) in a file.

  2. Use certutil to decode the file:

    certutil -decode ENCODED_FILE DECODED_FILE
    

    Replace the following values:

    • ENCODED_FILE: the path to the file containing the encoded private key data.
    • DECODED_FILE: the path of the file that you want to save the key to. Use the .json file extension.

Make sure to store the key data securely, because it can be used to authenticate as your service account.

You can use service account key files to authenticate an application as a service account.

C++

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

namespace iam = ::google::cloud::iam;
return [](std::string const& name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  auto response = client.CreateServiceAccountKey(
      name,
      google::iam::admin::v1::ServiceAccountPrivateKeyType::
          TYPE_GOOGLE_CREDENTIALS_FILE,
      google::iam::admin::v1::ServiceAccountKeyAlgorithm::KEY_ALG_RSA_2048);
  if (!response) throw std::runtime_error(response.status().message());
  std::cout << "ServiceAccountKey successfully created: "
            << response->DebugString() << "\n";
  return response->name();
}

C#

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


using System;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class ServiceAccountKeys
{
    public static ServiceAccountKey CreateKey(string serviceAccountEmail)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var key = service.Projects.ServiceAccounts.Keys.Create(
            new CreateServiceAccountKeyRequest(),
            "projects/-/serviceAccounts/" + serviceAccountEmail)
            .Execute();
        Console.WriteLine("Created key: " + key.Name);
        return key;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// createKey creates a service account key.
func createKey(w io.Writer, serviceAccountEmail string) (*iam.ServiceAccountKey, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %v", err)
	}

	resource := "projects/-/serviceAccounts/" + serviceAccountEmail
	request := &iam.CreateServiceAccountKeyRequest{}
	key, err := service.Projects.ServiceAccounts.Keys.Create(resource, request).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Keys.Create: %v", err)
	}
	fmt.Fprintf(w, "Created key: %v", key.Name)
	return key, nil
}

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.

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.api.services.iam.v1.model.CreateServiceAccountKeyRequest;
import com.google.api.services.iam.v1.model.ServiceAccountKey;
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 CreateServiceAccountKey {

  // Creates a key for a service account.
  public static void createKey(String projectId, String serviceAccountName) {
    // String projectId = "my-project-id";
    // String serviceAccountName = "my-service-account-name";

    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e.toString());
      return;
    }

    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
    try {
      ServiceAccountKey key =
          service
              .projects()
              .serviceAccounts()
              .keys()
              .create(
                  "projects/-/serviceAccounts/" + serviceAccountEmail,
                  new CreateServiceAccountKeyRequest())
              .execute();

      System.out.println("Created key: " + key.getName());
    } catch (IOException e) {
      System.out.println("Unable to create service account key: \n" + e.toString());
    }
  }

  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.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-account-keys")
            .build();
    return service;
  }
}

Python

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

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def create_key(service_account_email):
    """Creates a key for a service account."""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
        scopes=['https://www.googleapis.com/auth/cloud-platform'])

    service = googleapiclient.discovery.build(
        'iam', 'v1', credentials=credentials)

    key = service.projects().serviceAccounts().keys().create(
        name='projects/-/serviceAccounts/' + service_account_email, body={}
        ).execute()

    print('Created key: ' + key['name'])

Google ensures that all public keys for all service accounts are publicly accessible by anyone and available to verify signatures that are created with the private key. The public key is publicly accessible at the following URLs:

  • x.509 certificate: https://www.googleapis.com/service_accounts/v1/metadata/x509/sa-name@project-id.iam.gserviceaccount.com
  • JSON web key (JWK): https://www.googleapis.com/service_accounts/v1/jwk/sa-name@project-id.iam.gserviceaccount.com
  • Raw endpoint: https://www.googleapis.com/service_accounts/v1/metadata/raw/sa-name@project-id.iam.gserviceaccount.com

Listing service account keys

You can list the service account keys for a service account using the Cloud Console, the gcloud tool, the serviceAccount.keys.list() method, or one of the client libraries.

The serviceAccount.keys.list() method is commonly used to audit service accounts and keys, or to build custom tooling for managing service accounts.

To find out which project your key belongs to, you can download the key as a JSON file and look at that file.

You might see keys listed that you did not create. These are Google Cloud-managed keys used by Google Cloud services such as App Engine and Compute Engine. For more information on the difference between user and Google Cloud-managed keys, see Understanding service accounts.

Console

  1. In the Cloud Console, go to the Service Accounts page.

    Go to Service accounts

  2. Select a project. The Cloud Console lists all of the project's service accounts and their corresponding keys.

gcloud

Execute the gcloud iam service-accounts keys list command to list service account keys.

Replace the following values:

  • sa-name: The name of the service account to list keys for.
  • project-id: Your Google Cloud project ID.
gcloud iam service-accounts keys list \
    --iam-account=sa-name@project-id.iam.gserviceaccount.com

Output:

KEY_ID CREATED_AT EXPIRES_AT DISABLED
8e6e3936d7024646f8ceb39792006c07f4a9760c 2021-01-01T21:01:42Z 9999-12-31T23:59:59Z  
937c98f870f5c8db970af527aa3c12fd88b1c20a 2021-01-01T20:55:40Z 9999-12-31T23:59:59Z True

REST

The projects.serviceAccounts.keys.list method lists all of the service account keys for a service account.

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 keys you want to list.
  • KEY_TYPES: Optional. A comma-separated list of key types that you want to include in the response. The key type indicates whether a key is user-managed (USER_MANAGED) or system-managed (SYSTEM_MANAGED). If left blank, all keys are returned.

HTTP method and URL:

GET https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com/keys?keyTypes=KEY_TYPES

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "keys": [
    {
      "name": "projects/my-project/serviceAccounts/my-service-account@my-project.iam.gserviceaccount.com/keys/90c48f61c65cd56224a12ab18e6ee9ca9c3aee7c",
      "validAfterTime": "2020-03-04T17:39:47Z",
      "validBeforeTime": "9999-12-31T23:59:59Z",
      "keyAlgorithm": "KEY_ALG_RSA_2048",
      "keyOrigin": "GOOGLE_PROVIDED",
      "keyType": "USER_MANAGED"
    },
    {
      "name": "projects/my-project/serviceAccounts/my-service-account@my-project.iam.gserviceaccount.com/keys/e5e3800831ac1adc8a5849da7d827b4724b1fce8",
      "validAfterTime": "2020-03-31T23:50:09Z",
      "validBeforeTime": "9999-12-31T23:59:59Z",
      "keyAlgorithm": "KEY_ALG_RSA_2048",
      "keyOrigin": "GOOGLE_PROVIDED",
      "keyType": "USER_MANAGED"
    },
    {
      "name": "projects/my-project/serviceAccounts/my-service-account@my-project.iam.gserviceaccount.com/keys/b97699f042b8eee6a846f4f96259fbcd13e2682e",
      "validAfterTime": "2020-05-17T18:58:13Z",
      "validBeforeTime": "9999-12-31T23:59:59Z",
      "keyAlgorithm": "KEY_ALG_RSA_2048",
      "keyOrigin": "GOOGLE_PROVIDED",
      "keyType": "USER_MANAGED",
      "disabled": true
    }
  ]
}

C++

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

namespace iam = ::google::cloud::iam;
[](std::string const& service_account_name,
   std::vector<std::string> const& key_type_labels) {
  iam::IAMClient client(iam::MakeIAMConnection());
  std::vector<google::iam::admin::v1::ListServiceAccountKeysRequest::KeyType>
      key_types;
  for (auto const& type : key_type_labels) {
    if (type == "USER_MANAGED") {
      key_types.push_back(google::iam::admin::v1::
                              ListServiceAccountKeysRequest::USER_MANAGED);
    } else if (type == "SYSTEM_MANAGED") {
      key_types.push_back(google::iam::admin::v1::
                              ListServiceAccountKeysRequest::SYSTEM_MANAGED);
    }
  }
  auto response =
      client.ListServiceAccountKeys(service_account_name, key_types);
  if (!response) throw std::runtime_error(response.status().message());
  std::cout << "ServiceAccountKeys successfully retrieved: "
            << response->DebugString() << "\n";
}

C#

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


using System;
using System.Collections.Generic;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class ServiceAccountKeys
{
    public static IList<ServiceAccountKey> ListKeys(string serviceAccountEmail)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var response = service.Projects.ServiceAccounts.Keys
            .List($"projects/-/serviceAccounts/{serviceAccountEmail}")
            .Execute();
        foreach (ServiceAccountKey key in response.Keys)
        {
            Console.WriteLine("Key: " + key.Name);
        }
        return response.Keys;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// listKey lists a service account's keys.
func listKeys(w io.Writer, serviceAccountEmail string) ([]*iam.ServiceAccountKey, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %v", err)
	}

	resource := "projects/-/serviceAccounts/" + serviceAccountEmail
	response, err := service.Projects.ServiceAccounts.Keys.List(resource).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Keys.List: %v", err)
	}
	for _, key := range response.Keys {
		fmt.Fprintf(w, "Listing key: %v", key.Name)
	}
	return response.Keys, nil
}

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.

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

public class ListServiceAccountKeys {

  // Lists all keys for a service account.
  public static void listKeys(String projectId, String serviceAccountName) {
    // String projectId = "my-project-id";
    // String serviceAccountName = "my-service-account-name";

    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e.toString());
      return;
    }

    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
    try {
      List<ServiceAccountKey> keys =
          service
              .projects()
              .serviceAccounts()
              .keys()
              .list("projects/-/serviceAccounts/" + serviceAccountEmail)
              .execute()
              .getKeys();

      for (ServiceAccountKey key : keys) {
        System.out.println("Key: " + key.getName());
      }
    } catch (IOException e) {
      System.out.println("Unable to list service account keys: \n" + e.toString());
    }
  }

  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.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-account-keys")
            .build();
    return service;
  }
}

Python

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

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def list_keys(service_account_email):
    """Lists all keys for a service account."""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
        scopes=['https://www.googleapis.com/auth/cloud-platform'])

    service = googleapiclient.discovery.build(
        'iam', 'v1', credentials=credentials)

    keys = service.projects().serviceAccounts().keys().list(
        name='projects/-/serviceAccounts/' + service_account_email).execute()

    for key in keys['keys']:
        print('Key: ' + key['name'])

Getting a service account key

You can only get the private key data for a service account key when the key is first created.

You can get basic information about a key such as its ID, algorithm, and public key data with the projects.serviceAccounts.keys.get() REST API method. Using the Cloud Console or the gcloud command-line tool is not supported.

Uploading public keys for service accounts

You can upload the public key portion of a user-managed key pair to a service account. After you upload the public key, it is permanently associated with the service account and will be used the same way as any other user-managed service account keys. To disable the ability to upload keys for your project, see restricting service account key upload.

If you choose to use a user-managed key pair instead of a Google-managed key pair, ensure that you maintain it and regularly rotate it.

The key you upload must be an RSA public key that is wrapped in an X.509 v3 certificate and encoded in base64. You can use tools such as OpenSSL to generate a key and certificate in this format.

For example, the following command generates a 2048-bit RSA key pair and wraps the public key in a self-signed certificate that is valid for 365 days:

openssl req -x509 -nodes -newkey rsa:2048 -days 365 \
    -keyout /path/to/private_key.pem \
    -out /path/to/public_key.pem \
    -subj "/CN=unused"

You can then upload the public_key.pem file as the public key for a service account.

Console

  1. In the Cloud Console, go to the Service Accounts page.

    Go to Service accounts

  2. Select a project.

  3. Click the email address of the service account that you want to upload a key for.

  4. Click the Keys tab.

  5. Click the Add key drop-down menu, then select Upload existing key.

  6. Click Browse, then find and select your public key file. Alternatively, you can copy and paste the contents of your public key file into the Paste existing key box.

  7. Click Upload.

gcloud

Execute the gcloud iam service-accounts keys upload command to upload a public key for signing service account keys.

Replace the following values:

  • key-file: The path to the file containing the key data to upload—for example, ./public_key.pem.
  • sa-name: The name of the service account to upload a key for.
  • project-id: Your Google Cloud project ID.
gcloud iam service-accounts keys upload key-file \
    --iam-account=sa-name@project-id.iam.gserviceaccount.com

The output contains a unique identifier for the uploaded key:

Name: projects/project-id/serviceAccounts/sa-name@project-id.iam.gserviceaccount.com/keys/c7b74879da78e4cdcbe7e1bf5e129375c0bfa8d0

To determine whether the command was successful, execute the gcloud iam service-accounts keys list command:

gcloud iam service-accounts keys list \
    --iam-account=sa-name@project-id.iam.gserviceaccount.com

The output will contain the same unique identifier that was returned after the key was created:

KEY_ID CREATED_AT EXPIRES_AT DISABLED
c7b74879da78e4cdcbe7e1bf5e129375c0bfa8d0 2019-06-26T21:01:42Z 9999-12-31T23:59:59Z  

REST

The projects.serviceAccounts.keys.upload method uploads the public key from a user-managed key pair, and adds this key to the service account.

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 to associate the key with.
  • PUBLIC_KEY_DATA: The public key data for the key pair. Must be an RSA public key that is wrapped in an X.509 v3 certificate. Encode the public key data in base64, including the first line, -----BEGIN CERTIFICATE-----, and the last line, -----END CERTIFICATE-----.

HTTP method and URL:

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

Request JSON body:

{
  "publicKeyData": "PUBLIC_KEY_DATA"
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "name": "projects/my-project/serviceAccounts/my-service-account@my-project.iam.gserviceaccount.com/keys/c7b74879da78e4cdcbe7e1bf5e129375c0bfa8d0",
  "validAfterTime": "2020-05-17T19:31:19Z",
  "validBeforeTime": "2021-05-17T19:31:19Z",
  "keyAlgorithm": "KEY_ALG_RSA_2048",
  "keyOrigin": "USER_PROVIDED",
  "keyType": "USER_MANAGED"
}

Disabling service account keys

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 Cloud Console, but you cannot use the Cloud Console to disable a key. Use the gcloud tool 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.
  • 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

Output:

Disabled key [key-id] for service account
[sa-name@project-id.iam.gserviceaccount.com]

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.

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:

{
}

Enabling service account keys

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 Cloud Console to enable service account keys. Use the gcloud tool 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.
  • 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

Output:

Enabled key [key-id] for service account
[sa-name@project-id.iam.gserviceaccount.com]

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.

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:

{
}

Deleting service account keys

Deleting a service account key permanently prevents you from using the key to authenticate with Google APIs.

You cannot undelete a deleted key. Before you delete a 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.

As a best practice, rotate your service account keys regularly. You can rotate a key by doing the following:

  1. Create a new key.
  2. Update your applications to use the new key.
  3. Disable the old key.
  4. Wait long enough to confirm that the old key is no longer in use.
  5. Delete the old key.

Console

  1. In the Cloud Console, go to the Service Accounts page.

    Go to Service accounts

  2. Select a project.

  3. Click the email address of the service account whose key you want to delete.

  4. Click the Keys tab.

  5. From the list of keys, click Delete for each key you'd like to delete.

gcloud

Execute the gcloud iam service-accounts keys delete command to delete service account keys.

Replace the following values:

  • key-id: The ID of the key to delete.
  • 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 delete key-id \
    --iam-account=sa-name@project-id.iam.gserviceaccount.com

Output:

Deleted key [key-id] for service account
[sa-name@project-id.iam.gserviceaccount.com]

REST

The projects.serviceAccounts.keys.delete method deletes 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 delete.
  • KEY_ID: The ID of the key that you want to delete.

HTTP method and URL:

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

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
}

C++

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

namespace iam = ::google::cloud::iam;
[](std::string const& name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  auto response = client.DeleteServiceAccountKey(name);
  if (!response.ok()) throw std::runtime_error(response.message());
  std::cout << "ServiceAccountKey successfully deleted.\n";
}

C#

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


using System;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class ServiceAccountKeys
{
    public static void DeleteKey(string fullKeyName)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        service.Projects.ServiceAccounts.Keys.Delete(fullKeyName).Execute();
        Console.WriteLine("Deleted key: " + fullKeyName);
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// deleteKey deletes a service account key.
func deleteKey(w io.Writer, fullKeyName string) error {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return fmt.Errorf("iam.NewService: %v", err)
	}

	_, err = service.Projects.ServiceAccounts.Keys.Delete(fullKeyName).Do()
	if err != nil {
		return fmt.Errorf("Projects.ServiceAccounts.Keys.Delete: %v", err)
	}
	fmt.Fprintf(w, "Deleted key: %v", fullKeyName)
	return nil
}

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.

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

public class DeleteServiceAccountKey {

  // Deletes a service account key.
  public static void deleteKey(String projectId, String serviceAccountName) {
    // String projectId = "my-project-id";
    // String serviceAccountName = "my-service-account-name";

    Iam service = null;
    try {
      service = initService();
    } catch (IOException | GeneralSecurityException e) {
      System.out.println("Unable to initialize service: \n" + e.toString());
      return;
    }

    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
    try {
      // First, get the name of the key using List() or Get()
      List<ServiceAccountKey> keys =
          service
              .projects()
              .serviceAccounts()
              .keys()
              .list("projects/-/serviceAccounts/" + serviceAccountEmail)
              .execute()
              .getKeys();
      String keyToDelete = keys.get(0).getName();

      // Then you can delete the key
      service.projects().serviceAccounts().keys().delete(keyToDelete).execute();

      System.out.println("Deleted key: " + keyToDelete);
    } catch (IOException e) {
      System.out.println("Unable to delete service account key: \n" + e.toString());
    }
  }

  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.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-account-keys")
            .build();
    return service;
  }
}

Python

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

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def delete_key(full_key_name):
    """Deletes a service account key."""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
        scopes=['https://www.googleapis.com/auth/cloud-platform'])

    service = googleapiclient.discovery.build(
        'iam', 'v1', credentials=credentials)

    service.projects().serviceAccounts().keys().delete(
        name=full_key_name).execute()

    print('Deleted key: ' + full_key_name)

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