Creating and Managing Service Account Keys

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

Prerequisites for this guide

Required permissions

To allow a user to manage service account keys, grant the Service Account Key Admin role (roles/iam.serviceAccountKeyAdmin). Cloud IAM primitive roles also contain permissions to manage service account keys, but we recommend granting this role instead to prevent unnecessary access to other GCP resources.

See the Service Account Roles topic for more information about roles related to service accounts.

Creating service account keys

To use a service account outside of the Google Cloud Platform (on other platforms or on premise), you must establish the identity of the service account. Public/private key pairs will let you do that.

You can create a service account key using the GCP Console, the gcloud tool, the serviceAccounts.keys.create() method, or one of the client libraries.

In the examples below, [SA-NAME] is the name of your service account, and [PROJECT-ID] is the ID of your Google Cloud Platform project. You can retrieve the [SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com string from the Service Accounts page in the GCP Console.

Console

  1. Open the IAM & Admin page in the GCP Console.

    Open the IAM & Admin page

  2. Select your project and click Continue.

  3. In the left nav, click Service accounts.

  4. Look for the service account for which you wish to create a key, click the More more_vert button in that row, and then click Create key.

  5. Select a Key type and click Create.

GCLOUD COMMAND

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

Command:

gcloud iam service-accounts keys create ~/key.json
  --iam-account [SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com

Output:

created key [e44da1202f82f8f4bdd9d92bc412d1d8a837fa83] of type [json] as
[/usr/home/username/key.json] for
[SA-NAME@PROJECT-ID.iam.gserviceaccount.com]

REST API

Request:

POST https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts/[SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com/keys

Response:

{
    "name":"projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com/keys/90c48f61c65cd56224a12ab18e6ee9ca9c3aee7c",
    "privateKeyType": "TYPE_GOOGLE_CREDENTIALS_FILE",
    "privateKeyData":"MIIJqAIB . . .",
    "validBeforeTime": "2028-05-08T21:00:00Z",
    "validAfterTime": "2016-01-25T18:38:09.000Z",
    "keyAlgorithm": "KEY_ALG_RSA_2048"
}

C#

Before trying this sample, follow the C# setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM C# API reference documentation .

public static ServiceAccountKey CreateKey(string serviceAccountEmail)
{
    ServiceAccountKey key = s_service.Projects.ServiceAccounts.Keys.Create(
        new CreateServiceAccountKeyRequest(),
        "projects/-/serviceAccounts/" + serviceAccountEmail)
        .Execute();

    Console.WriteLine("Created key: " + key.Name);
    return key;
}

Java

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Java API reference documentation .

public ServiceAccountKey createKey(String serviceAccountEmail) throws IOException {

  ServiceAccountKey key =
      service
          .projects()
          .serviceAccounts()
          .keys()
          .create(
              "projects/-/serviceAccounts/" + serviceAccountEmail,
              new CreateServiceAccountKeyRequest())
          .execute();

  System.out.println("Created key: " + key.getName());
  return key;
}

Python

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Python API reference documentation .

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

    # pylint: disable=no-member
    key = service.projects().serviceAccounts().keys().create(
        name='projects/-/serviceAccounts/' + service_account_email, body={}
        ).execute()

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

Note that the privateKeyData returned is a base64-encoded string representation of the JSON or P12 key/credentials.

When you create a key, your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of the private key. You are responsible for storing the private key securely. Take note of its location and ensure the key is accessible to your application; it needs the key to make authenticated API calls.

It may take up to 60 seconds before a newly created key can be used for authentication. If you experience authentication failures immediately after creating a new key, ensure that 60 seconds have elapsed before trying again.

The format of the key may differ depending on how it is generated. Keys created using the GCP Console or the gcloud command-line tool look like this:

{
"type": "service_account",
"project_id": "[PROJECT-ID]",
"private_key_id": "[KEY-ID]"
"private_key": "-----BEGIN PRIVATE KEY-----\n[PRIVATE-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]"
}

Whereas keys generated with the REST API or client libraries look like this:

{
"name": "projects/[PROJECT-ID]/serviceAccounts/[SERVICE-ACCOUNT-EMAIL>/keys/[KEY-ID]",
"privateKeyType": "TYPE_GOOGLE_CREDENTIALS_FILE",
"privateKeyData": "[PRIVATE-KEY]"
"validAfterTime": "[DATE]",
"validBeforeTime": "[DATE]",
"keyAlgorithm": "KEY_ALG_RSA_2048"
}

Because the formatting differs between each method, it's easiest to generate a key using the same method you plan to use when making future API calls. For example, if you're using gcloud, also generate your key using gcloud. To use a key for one method that's been generated using a different method (such as using a REST-generated key with gcloud), you'll need to edit the key to match the appropriate format.

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 GCP 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 may see keys listed that you did not create. These are GCP-managed keys used by GCP services such as App Engine and Compute Engine. For more information on the difference between user and GCP-managed keys, see Understanding service accounts.

Console

  1. Open the IAM & Admin page in the GCP Console.

    Open the IAM & Admin page

  2. Select your project and click Continue.

  3. In the left nav, click Service accounts. All service accounts and their corresponding keys are listed.

GCLOUD COMMAND

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

Command:

gcloud iam service-accounts keys list
  --iam-account [SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com

Output:

KEY_ID CREATED_AT EXPIRES_AT
8e6e3936d7024646f8ceb39792006c07f4a9760c 2016-01-26T21:01:42.000Z 2026-01-23T21:01:42.000Z
937c98f870f5c8db970af527aa3c12fd88b1c20a 2016-01-26T20:55:40.000Z 2026-01-23T20:55:40.000Z

REST API

Request:

POST https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts/[SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com/keys

Response:

{
    "keys": [
    {
        "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com/keys/90c48f61c65cd56224a12ab18e6ee9ca9c3aee7c",
        "validAfterTime": "2016-01-25T18:38:09.000Z",
        "validBeforeTime": "2026-01-22T18:38:09.000Z",
        "keyAlgorithm": "KEY_ALG_RSA_2048"
    },
    {
        "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com/keys/e5e3800831ac1adc8a5849da7d827b4724b1fce8",
        "validAfterTime": "2016-01-25T13:43:27.000Z",
        "validBeforeTime": "2016-01-26T13:43:27.000Z",
        "keyAlgorithm": "KEY_ALG_RSA_2048"
    },
    {
        "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com/keys/b97699f042b8eee6a846f4f96259fbcd13e2682e",
        "validAfterTime": "2016-01-26T13:28:27.000Z",
        "validBeforeTime": "2016-01-27T13:28:27.000Z",
        "keyAlgorithm": "KEY_ALG_RSA_2048"
    }]
}

C#

Before trying this sample, follow the C# setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM C# API reference documentation .

public static IList<ServiceAccountKey> ListKeys(string serviceAccountEmail)
{
    IList<ServiceAccountKey> keys = s_service.Projects.ServiceAccounts.Keys
        .List($"projects/-/serviceAccounts/{serviceAccountEmail}")
        .Execute().Keys;

    foreach (ServiceAccountKey key in keys)
    {
        Console.WriteLine("Key: " + key.Name);
    }
    return keys;
}

Java

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Java API reference documentation .

public List<ServiceAccountKey> listKeys(String serviceAccountEmail) throws IOException {

  List<ServiceAccountKey> keys =
      service
          .projects()
          .serviceAccounts()
          .keys()
          .list("projects/-/serviceAccounts/" + serviceAccountEmail)
          .execute()
          .getKeys();

  for (ServiceAccountKey key : keys) {
    System.out.println("Key: " + key.getName());
  }
  return keys;
}

Python

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Python API reference documentation .

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

    # pylint: disable=no-member
    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 GCP Console or the gcloud command-line tool is not supported.

Deleting service account keys

You can delete a service account key using the GCP Console, the gcloud tool, the serviceAccount.keys.delete() method, or one of the client libraries.

If you delete a key, your application will no longer be able to access Cloud Platform resources using that key. A security best practice is to rotate your service account keys regularly. You can rotate a key by creating a new key, switching applications to use the new key and then deleting old key. Use the serviceAccount.keys.create() method and serviceAccount.keys.delete() method together to automate the rotation.

Console

  1. Open the IAM & Admin page in the GCP Console.

    Open the IAM & Admin page

  2. Select your project and click Continue.

  3. In the left nav, click Service accounts. All service accounts and their corresponding keys are listed.

  4. Click the desired service account's email to view its keys.

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

GCLOUD COMMAND

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

Command:

gcloud iam service-accounts keys delete [KEY-ID]
  --iam-account [SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com

Output:

Deleted key [8e6e3936d7024646f8ceb39792006c07f4a9760c] for
service account [SA-NAME@PROJECT-ID.iam.gserviceaccount.com]

REST API

Request:

DELETE https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts/[SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com/keys/[KEY-ID]

C#

Before trying this sample, follow the C# setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM C# API reference documentation .

public static void DeleteKey(string fullKeyName)
{
    s_service.Projects.ServiceAccounts.Keys.Delete(fullKeyName).Execute();
    Console.WriteLine("Deleted key: " + fullKeyName);
}

Java

Before trying this sample, follow the Java setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Java API reference documentation .

public void deleteKey(String fullKeyName) throws IOException {

  service.projects().serviceAccounts().keys().delete(fullKeyName).execute();

  System.out.println("Deleted key: " + fullKeyName);
}

Python

Before trying this sample, follow the Python setup instructions in the Cloud IAM Quickstart Using Client Libraries . For more information, see the Cloud IAM Python API reference documentation .

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

    # pylint: disable=no-member
    service.projects().serviceAccounts().keys().delete(
        name=full_key_name).execute()

    print('Deleted key: ' + full_key_name)

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Identity and Access Management Documentation