Creating and managing service accounts

This page explains how to create and manage service accounts using the Cloud Identity and Access Management API, the Google Cloud Platform Console, and the gcloud command-line tool.

When you create a new Cloud project, Google Cloud Platform (GCP) automatically creates one Compute Engine service account and one App Engine service account under that project. You can create up to 98 additional service accounts to your project to control access to your resources.

Before you begin

Required permissions

To allow a user to manage service accounts, grant one of the following roles:

  • Service Account User (roles/iam.serviceAccountUser): Grants permissions to get, list, or impersonate a service account.
  • Service Account Admin (roles/iam.serviceAccountAdmin): Includes Service Account User permissions and also grants permissions to create, update, delete, and set or get the Cloud IAM policy on a service account.

Cloud IAM primitive roles also contain permissions to manage service accounts. However, we recommend granting one of the predefined roles above to prevent unnecessary access to other GCP resources.

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

Creating a service account

Creating a service account is similar to adding a member to your project, but the service account belongs to your applications rather than an individual end user.

In the examples below, [SA-NAME] is the name of the service account that you provide, such as my-service-account. This is a unique identifier; it will appear in the service account's email address that is provisioned during creation, such as my-service-account@project-name.iam.gserviceaccount.com. You'll also use it to update the service account with other APIs. It cannot be changed once created.

Also provide the following values:

  • [SA-DESCRIPTION] is an optional description for the service account
  • [SA-DISPLAY-NAME] is a friendly name for the service account
  • [PROJECT-ID] is the ID of your Google Cloud Platform project

To create a service account, at minimum the user must be granted the Service Account Admin role (roles/iam.serviceAccountAdmin) or the Editor primitive role (roles/editor).

Console

  1. Open the Service Accounts page in the GCP Console.

    Open the Service Accounts page

  2. Click Select a project.

  3. Select your project and click Open.

  4. Click Create Service Account.

  5. Enter a service account name, an optional description, select a role you wish to grant to the service account, and then click Save.

GCLOUD COMMAND

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

Command:

gcloud beta iam service-accounts create [SA-NAME]
    --description "[SA-DESCRIPTION]"
    --display-name "[SA-DISPLAY-NAME]"

The output is the service account:

Created service account [SA-NAME].

REST API

Call serviceAccounts.create() to create a service account.

POST https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts

The request body should contain the properties for the service account.

{
    "accountId": "[SA-NAME]",
    "serviceAccount": {
        "description": "[SA-DESCRIPTION]",
        "displayName": "[SA-DISPLAY-NAME]"
    }
}

Response:

{
    "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com",
    "projectId": "PROJECT-ID",
    "uniqueId": "113948692397867021414",
    "email": "SA-NAME@PROJECT-ID.iam.gserviceaccount.com",
    "description": "SA-DESCRIPTION",
    "displayName": "SA-DISPLAY-NAME",
    "etag": "BwUp3rVlzes=",
    "oauth2ClientId": "117249000288840666939"
}

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 .

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

public partial class ServiceAccounts
{
    public static ServiceAccount CreateServiceAccount(string projectId,
        string name, string displayName)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new CreateServiceAccountRequest
        {
            AccountId = name,
            ServiceAccount = new ServiceAccount
            {
                DisplayName = displayName
            }
        };
        var serviceAccount = service.Projects.ServiceAccounts.Create(
            request, "projects/" + projectId).Execute();
        Console.WriteLine("Created service account: " + serviceAccount.Email);
        return serviceAccount;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

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

// createServiceAccount creates a service account.
func createServiceAccount(w io.Writer, projectID, name, displayName string) (*iam.ServiceAccount, error) {
	client, err := google.DefaultClient(context.Background(), iam.CloudPlatformScope)
	if err != nil {
		return nil, fmt.Errorf("google.DefaultClient: %v", err)
	}
	service, err := iam.New(client)
	if err != nil {
		return nil, fmt.Errorf("iam.New: %v", err)
	}

	request := &iam.CreateServiceAccountRequest{
		AccountId: name,
		ServiceAccount: &iam.ServiceAccount{
			DisplayName: displayName,
		},
	}
	account, err := service.Projects.ServiceAccounts.Create("projects/"+projectID, request).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Create: %v", err)
	}
	fmt.Fprintf(w, "Created service account: %v", account)
	return account, nil
}

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 ServiceAccount createServiceAccount(String projectId, String name, String displayName)
    throws IOException {

  ServiceAccount serviceAccount = new ServiceAccount();
  serviceAccount.setDisplayName(displayName);
  CreateServiceAccountRequest request = new CreateServiceAccountRequest();
  request.setAccountId(name);
  request.setServiceAccount(serviceAccount);

  serviceAccount =
      service.projects().serviceAccounts().create("projects/" + projectId, request).execute();

  System.out.println("Created service account: " + serviceAccount.getEmail());
  return serviceAccount;
}

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_service_account(project_id, name, display_name):
    """Creates a service account."""

    # pylint: disable=no-member
    service_account = service.projects().serviceAccounts().create(
        name='projects/' + project_id,
        body={
            'accountId': name,
            'serviceAccount': {
                'displayName': display_name
            }
        }).execute()

    print('Created service account: ' + service_account['email'])
    return service_account

After you create a service account, grant one or more roles to the service account so that it can act on your behalf.

Listing service accounts

When listing service accounts, you can specify parameters to limit the number of service accounts to include in the response. You can then use ListServiceAccountsResponse.next_page_token in a subsequent request to list the remaining service accounts.

Use this method to audit service accounts and keys, or to build custom tools for managing service accounts.

To list service accounts, at minimum the user must be granted the Service Account User role (roles/iam.serviceAccountUser) or the Viewer primitive role (roles/viewer).

Console

  1. Open the Service Accounts page in the GCP Console.

    Open the Service Accounts page

  2. Click Select a project.

  3. Select your project and click Open. All service accounts are listed in the Service Accounts page.

GCLOUD COMMAND

Execute the gcloud iam service-accounts list command to list all service accounts in a project.

Command:

gcloud iam service-accounts list

The output is the list of all service accounts in the project:

NAME                    EMAIL
SA-DISPLAY-NAME-1       SA-NAME-1@PROJECT-ID.iam.gserviceaccount.com
SA-DISPLAY-NAME-2       SA-NAME-2@PROJECT-ID.iam.gserviceaccount.com

REST API

Call the serviceAccounts.list() method.

Request:

GET https://iam.googleapis.com/v1/projects/[PROJECT-ID]/serviceAccounts

Response:

{
    "accounts": [
    {
        "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME-1@PROJECT-ID.iam.gserviceaccount.com",
        "projectId": "PROJECT-ID",
        "uniqueId": "108979773878059201436",
        "email": "SA-NAME-1@PROJECT-ID.iam.gserviceaccount.com",
        "description": "SA-DESCRIPTION-1",
        "displayName": "SA-DISPLAY-NAME-1",
        "etag": "BwUpTsLVUkQ=",
        "oauth2ClientId": "102240834887833340852"
    },
    {
        "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME-2@PROJECT-ID.iam.gserviceaccount.com",
        "projectId": "PROJECT-ID",
        "uniqueId": "108979773878059201436",
        "email": "SA-NAME-2@PROJECT-ID.iam.gserviceaccount.com",
        "description": "SA-DESCRIPTION-2",
        "displayName": "SA-DISPLAY-NAME-2",
        "etag": "BwUpTsLVUkQ=",
        "oauth2ClientId": "102240834887833340852"
    }]
}

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 .

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 ServiceAccounts
{
    public static IList<ServiceAccount> ListServiceAccounts(string projectId)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var response = service.Projects.ServiceAccounts.List(
            "projects/" + projectId).Execute();
        foreach (ServiceAccount account in response.Accounts)
        {
            Console.WriteLine("Name: " + account.Name);
            Console.WriteLine("Display Name: " + account.DisplayName);
            Console.WriteLine("Email: " + account.Email);
            Console.WriteLine();
        }
        return response.Accounts;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

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

// listServiceAccounts lists a project's service accounts.
func listServiceAccounts(w io.Writer, projectID string) ([]*iam.ServiceAccount, error) {
	client, err := google.DefaultClient(context.Background(), iam.CloudPlatformScope)
	if err != nil {
		return nil, fmt.Errorf("google.DefaultClient: %v", err)
	}
	service, err := iam.New(client)
	if err != nil {
		return nil, fmt.Errorf("iam.New: %v", err)
	}

	response, err := service.Projects.ServiceAccounts.List("projects/" + projectID).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.List: %v", err)
	}
	for _, account := range response.Accounts {
		fmt.Fprintf(w, "Listing service account: %v\n", account.Name)
	}
	return response.Accounts, nil
}

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<ServiceAccount> listServiceAccounts(String projectId) throws IOException {

  ListServiceAccountsResponse response =
      service.projects().serviceAccounts().list("projects/" + projectId).execute();
  List<ServiceAccount> serviceAccounts = response.getAccounts();

  for (ServiceAccount account : serviceAccounts) {
    System.out.println("Name: " + account.getName());
    System.out.println("Display Name: " + account.getDisplayName());
    System.out.println("Email: " + account.getEmail());
    System.out.println();
  }
  return serviceAccounts;
}

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_service_accounts(project_id):
    """Lists all service accounts for the current project."""

    # pylint: disable=no-member
    service_accounts = service.projects().serviceAccounts().list(
        name='projects/' + project_id).execute()

    for account in service_accounts['accounts']:
        print('Name: ' + account['name'])
        print('Email: ' + account['email'])
        print(' ')
    return service_accounts

Renaming a service account

The display name of a service account is commonly used to capture additional information about the service account, such as the purpose of the service account or a contact person for the account.

To rename a service account, at minimum the user must be granted the Service Account Admin role (roles/iam.serviceAccountAdmin) or the Editor primitive role (roles/editor).

Console

  1. Open the Service Accounts page in the GCP Console.

    Open the Service Accounts page

  2. Click Select a project.
  3. Select your project and click Open.
  4. Look for the service account you wish to rename, click the More more_vert button in that row, and then click Edit.
  5. Enter the new name and click Save.

GCLOUD COMMAND

Execute the gcloud iam service-accounts update command to update a service account.

Command:

gcloud beta iam service-accounts update
    [SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com
    --description "[UPDATED-SA-DESCRIPTION]"
    --display-name "[UPDATED-DISPLAY-NAME]"

The output is the renamed service account:

description: Updated description
displayName: Updated display name
name: projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com

REST API

Use the serviceAccounts.patch() method.

Request:

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

The request body must contain the service account email and the new display name or description.

{
    "serviceAccount": {
        "email": "[SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com",
        "displayName": "[UPDATED-DISPLAY-NAME]",
        "description": "[UPDATED-DESCRIPTION]",
    },
    "updateMask": "displayName,description"
}

Response:

{
    "name": "projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com",
    "projectId": "PROJECT-ID",
    "uniqueId": "107522985251862639552",
    "email": "SA-NAME@PROJECT-ID.iam.gserviceaccount.com",
    "description": "SA-DESCRIPTION",
    "displayName": "Updated display name",
    "etag": "BwUqLK4bL9U=",
    "oauth2ClientId": "105236325228757713905"
}

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 .

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

public partial class ServiceAccounts
{
    public static ServiceAccount RenameServiceAccount(string email,
        string newDisplayName)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        // First, get a ServiceAccount using List() or Get().
        string resource = "projects/-/serviceAccounts/" + email;
        var serviceAccount = service.Projects.ServiceAccounts.Get(resource)
            .Execute();
        // Then you can update the display name.
        serviceAccount.DisplayName = newDisplayName;
        serviceAccount = service.Projects.ServiceAccounts.Update(
            serviceAccount, resource).Execute();
        Console.WriteLine($"Updated display name for {serviceAccount.Email} " +
            "to: " + serviceAccount.DisplayName);
        return serviceAccount;
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

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

// renameServiceAccount renames a service account.
func renameServiceAccount(w io.Writer, email, newDisplayName string) (*iam.ServiceAccount, error) {
	client, err := google.DefaultClient(context.Background(), iam.CloudPlatformScope)
	if err != nil {
		return nil, fmt.Errorf("google.DefaultClient: %v", err)
	}
	service, err := iam.New(client)
	if err != nil {
		return nil, fmt.Errorf("iam.New: %v", err)
	}

	// First, get a ServiceAccount using List() or Get().
	resource := "projects/-/serviceAccounts/" + email
	serviceAccount, err := service.Projects.ServiceAccounts.Get(resource).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Get: %v", err)
	}
	// Then you can update the display name.
	serviceAccount.DisplayName = newDisplayName
	serviceAccount, err = service.Projects.ServiceAccounts.Update(resource, serviceAccount).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Update: %v", err)
	}

	fmt.Fprintf(w, "Updated service account: %v", serviceAccount.Email)
	return serviceAccount, nil
}

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 ServiceAccount renameServiceAccount(String email, String newDisplayName)
    throws IOException {

  // First, get a service account using List() or Get()
  ServiceAccount serviceAccount =
      service.projects().serviceAccounts().get("projects/-/serviceAccounts/" + email).execute();

  // Then you can update the display name
  serviceAccount.setDisplayName(newDisplayName);
  service.projects().serviceAccounts().update(serviceAccount.getName(), serviceAccount).execute();

  System.out.println(
      "Updated display name for " + serviceAccount.getName() + " to: " + newDisplayName);
  return serviceAccount;
}

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 rename_service_account(email, new_display_name):
    """Changes a service account's display name."""

    # First, get a service account using List() or Get()
    resource = 'projects/-/serviceAccounts/' + email
    # pylint: disable=no-member
    service_account = service.projects().serviceAccounts().get(
        name=resource).execute()

    # Then you can update the display name
    service_account['displayName'] = new_display_name
    service_account = service.projects().serviceAccounts().update(
        name=resource, body=service_account).execute()

    print('Updated display name for {} to: {}'.format(
        service_account['email'], service_account['displayName']))
    return service_account

Disabling a service account

Similar to deleting a service account, when you disable a service account, applications will no longer have access to GCP resources through that service account. If you disable the default App Engine and Compute Engine service accounts, the instances will no longer have access to resources in the project. If you attempt to disable an already disabled service account, it will have no effect.

Unlike deleting a service account, disabled service accounts can easily be re-enabled as necessary. We recommend disabling a service account before deleting it to make sure no critical applications are using the service account.

To disable a service account, at minimum the user must be granted the Service Account Admin role (roles/iam.serviceAccountAdmin) or the Editor primitive role (roles/editor).

GCLOUD COMMAND

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

Command:

gcloud alpha iam service-accounts disable
  [SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com

Output:

Disabled service account SA-NAME@PROJECT-ID.iam.gserviceaccount.com

REST API

Use the serviceAccounts.disable() method.

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

Enabling a service account

After enabling a disabled service account, applications will regain access to GCP resources through that service account.

You can enable a disabled service account whenever you need to. If you attempt to enable an already enabled service account, it will have no effect.

To enable a service account, at minimum the user must be granted the Service Account Admin role (roles/iam.serviceAccountAdmin) or the Editor primitive role (roles/editor).

GCLOUD COMMAND

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

Command:

gcloud alpha iam service-accounts enable
  [SA-NAME]@[PROJECT-ID].iam.gserviceaccount.com

Output:

Enabled service account SA-NAME@PROJECT-ID.iam.gserviceaccount.com

REST API

Use the serviceAccounts.enable() method.

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

Deleting a service account

When you delete a service account, applications will no longer have access to Google Cloud Platform resources through that service account. If you delete the default App Engine and Compute Engine service accounts, the instances will no longer have access to resources in the project.

Delete with caution; make sure your critical applications are no longer using a service account before deleting it. If you're not sure whether a service account is being used, we recommend disabling the service account before deleting it. Disabled service accounts can be easily re-enabled if they are still in use.

When a service account is deleted, its role bindings are not immediately removed; they are automatically purged from the system after a maximum of 60 days.

To delete a service account, at minimum the user must be granted the Service Account Admin role (roles/iam.serviceAccountAdmin) or the Editor primitive role (roles/editor).

Console

  1. Open the Service Accounts page in the GCP Console.

    Open the Service Accounts page

  2. Click Select a project.

  3. Select your project and click Open.

  4. Select the service account(s) you wish to delete, and then click Delete delete.

GCLOUD COMMAND

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

Command:

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

Output:

Deleted service account SA-NAME@PROJECT-ID.iam.gserviceaccount.com

REST API

Use the serviceAccounts.delete() method.

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

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 .

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

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

        string resource = "projects/-/serviceAccounts/" + email;
        service.Projects.ServiceAccounts.Delete(resource).Execute();
        Console.WriteLine("Deleted service account: " + email);
    }
}

Go

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

import (
	"context"
	"fmt"
	"io"

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

// deleteServiceAccount deletes a service account.
func deleteServiceAccount(w io.Writer, email string) error {
	client, err := google.DefaultClient(context.Background(), iam.CloudPlatformScope)
	if err != nil {
		return fmt.Errorf("google.DefaultClient: %v", err)
	}
	service, err := iam.New(client)
	if err != nil {
		return fmt.Errorf("iam.New: %v", err)
	}

	_, err = service.Projects.ServiceAccounts.Delete("projects/-/serviceAccounts/" + email).Do()
	if err != nil {
		return fmt.Errorf("Projects.ServiceAccounts.Delete: %v", err)
	}
	fmt.Fprintf(w, "Deleted service account: %v", email)
	return nil
}

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 deleteServiceAccount(String email) throws IOException {

  service.projects().serviceAccounts().delete("projects/-/serviceAccounts/" + email).execute();

  System.out.println("Deleted service account: " + email);
}

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_service_account(email):
    """Deletes a service account."""

    # pylint: disable=no-member
    service.projects().serviceAccounts().delete(
        name='projects/-/serviceAccounts/' + email).execute()

    print('Deleted service account: ' + email)

After deleting a service account, avoid creating a new service account with the same name. This can result in unexpected behavior. For more information, see Deleting and recreating service accounts.

Undeleting a service account

It's sometimes possible to restore a deleted service account using the undelete command.

To undelete a service account, the caller must be granted the iam.serviceAccounts.undelete permission on the deleted service account. This permission is included in the Owner (roles/owner) primitive role.

The deleted service account's unique ID must be provided when using the undelete command. Unique IDs are a 22 digit number, such as 103271949540120710052. If you don't know the unique ID for the deleted service account, it can be found in the Activity Log for the corresponding deletion operation.

You will be unable to restore a deleted service account under the following conditions:

  • If a service account has been deleted for more than 30 days, it will be automatically purged from the system and will no longer be restorable, even if a customer support request is filed.
  • If a deleted service account's email address is being used by an active (non-deleted) service account, it is impossible to restore the deleted service account. For example, if you delete an account named foo@project.iam.gserviceaccount.com with a unique ID of 103271949540120710052, and later create a new account using the same name foo@project.iam.gserviceaccount.com but with a unique ID of 103271949540120710329, it is impossible to restore the first service account. To overcome this issue, you can delete the newer (second) service account, and then execute the undelete command.

REST API

Use the serviceAccounts.undelete() method.

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

A REST call must be issued to recover the account. For example, this can be done using curl, where the unique ID of the deleted service account is 103271949540120710052:

curl -X POST -H "Authorization: Bearer $(gcloud auth print-access-token)" "https://iam.googleapis.com/v1/projects/-/serviceAccounts/103271949540120710052:undelete"

Successful recovery will result in a 200 response code with details about the restored service account.

Next steps

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

Send feedback about...

Cloud Identity and Access Management Documentation