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. To learn more about these roles, see the list of Service Accounts roles.

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-id.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 (friendly display 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 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 .

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
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.CreateServiceAccountRequest;
import com.google.api.services.iam.v1.model.ServiceAccount;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class CreateServiceAccount {

  // Creates a service account.
  public static void createServiceAccount(String projectId) {
    // String projectId = "my-project-id";

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

    try {
      ServiceAccount serviceAccount = new ServiceAccount();
      serviceAccount.setDisplayName("your-display-name");
      CreateServiceAccountRequest request = new CreateServiceAccountRequest();
      request.setAccountId("your-service-account-name");
      request.setServiceAccount(serviceAccount);

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

      System.out.println("Created service account: " + serviceAccount.getEmail());
    } catch (IOException e) {
      System.out.println("Unable to create service account: \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
    GoogleCredential credential =
        GoogleCredential.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(),
                credential)
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

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 .

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def create_service_account(project_id, name, display_name):
    """Creates 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)

    my_service_account = service.projects().serviceAccounts().create(
        name='projects/' + project_id,
        body={
            'accountId': name,
            'serviceAccount': {
                'displayName': display_name
            }
        }).execute()

    print('Created service account: ' + my_service_account['email'])
    return my_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 .

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
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.ListServiceAccountsResponse;
import com.google.api.services.iam.v1.model.ServiceAccount;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class ListServiceAccounts {

  // Lists all service accounts for the current project.
  public static void listServiceAccounts(String projectId) {
    // String projectId = "my-project-id"

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

    try {
      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();
      }
    } catch (IOException e) {
      System.out.println("Unable to list service accounts: \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
    GoogleCredential credential =
        GoogleCredential.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(),
                credential)
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

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."""

    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_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 (friendly 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 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 .

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
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.ServiceAccount;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class RenameServiceAccount {

  // Changes a service account's display name.
  public static void renameServiceAccount(String projectId) {
    // String projectId = "my-project-id";

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

    try {
      // First, get a service account using List() or Get()
      ServiceAccount serviceAccount =
          service
              .projects()
              .serviceAccounts()
              .get(
                  "projects/-/serviceAccounts/"
                      + "your-service-account-name@"
                      + projectId
                      + ".iam.gserviceaccount.com")
              .execute();

      // Then you can update the display name
      serviceAccount.setDisplayName("your-new-display-name");
      serviceAccount =
          service
              .projects()
              .serviceAccounts()
              .update(serviceAccount.getName(), serviceAccount)
              .execute();

      System.out.println(
          "Updated display name for "
              + serviceAccount.getName()
              + " to: "
              + serviceAccount.getDisplayName());
    } catch (IOException e) {
      System.out.println("Unable to rename service account: \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
    GoogleCredential credential =
        GoogleCredential.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(),
                credential)
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

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 .

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def rename_service_account(email, new_display_name):
    """Changes a service account's display name."""

    # First, get a service account using List() or Get()
    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)

    resource = 'projects/-/serviceAccounts/' + email

    my_service_account = service.projects().serviceAccounts().get(
        name=resource).execute()

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

    print('Updated display name for {} to: {}'.format(
        my_service_account['email'], my_service_account['displayName']))
    return my_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 iam service-accounts disable command to disable a service account.

Command:

gcloud 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

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 void DisableServiceAccount(string email)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new DisableServiceAccountRequest();

        string resource = "projects/-/serviceAccounts/" + email;
        service.Projects.ServiceAccounts.Disable(request, resource).Execute();
        Console.WriteLine("Disabled 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"
)

// disableServiceAccount disables a service account.
func disableServiceAccount(w io.Writer, email string) error {
	// email:= service-account@your-project.iam.gserviceaccount.com
	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)
	}

	request := &iam.DisableServiceAccountRequest{}
	_, err = service.Projects.ServiceAccounts.Disable("projects/-/serviceAccounts/"+email, request).Do()
	if err != nil {
		return fmt.Errorf("Projects.ServiceAccounts.Disable: %v", err)
	}
	fmt.Fprintf(w, "Disabled 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 .

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
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.DisableServiceAccountRequest;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class DisableServiceAccount {

  // Disables a service account.
  public static void disableServiceAccount(String projectId) {
    // String projectId = "my-project-id";

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

    try {
      DisableServiceAccountRequest request = new DisableServiceAccountRequest();
      service
          .projects()
          .serviceAccounts()
          .disable(
              "projects/-/serviceAccounts/"
                  + "your-service-account-name@"
                  + projectId
                  + ".iam.gserviceaccount.com",
              request)
          .execute();

      System.out.println(
          "Disabled service account: "
              + "your-service-account-name@"
              + projectId
              + ".iam.gserviceaccount.com");
    } catch (IOException e) {
      System.out.println("Unable to disable service account: \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
    GoogleCredential credential =
        GoogleCredential.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(),
                credential)
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

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 .

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def disable_service_account(email):
    """Disables 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)

    service.projects().serviceAccounts().disable(
        name='projects/-/serviceAccounts/' + email).execute()

    print("Disabled service account :" + email)

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 iam service-accounts enable command to enable a service account.

Command:

gcloud 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

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 void EnableServiceAccount(string email)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new EnableServiceAccountRequest();

        string resource = "projects/-/serviceAccounts/" + email;
        service.Projects.ServiceAccounts.Enable(request, resource).Execute();
        Console.WriteLine("Enabled 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"
)

// enableServiceAccount enables a service account.
func enableServiceAccount(w io.Writer, email string) error {
	// email:= service-account@your-project.iam.gserviceaccount.com
	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)
	}

	request := &iam.EnableServiceAccountRequest{}
	_, err = service.Projects.ServiceAccounts.Enable("projects/-/serviceAccounts/"+email, request).Do()
	if err != nil {
		return fmt.Errorf("Projects.ServiceAccounts.Enable: %v", err)
	}
	fmt.Fprintf(w, "Enabled 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 .

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
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.EnableServiceAccountRequest;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class EnableServiceAccount {

  // Enables a service account.
  public static void enableServiceAccount(String projectId) {
    // String projectId = "my-project-id";

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

    try {
      EnableServiceAccountRequest request = new EnableServiceAccountRequest();
      service
          .projects()
          .serviceAccounts()
          .enable(
              "projects/-/serviceAccounts/"
                  + "your-service-account-name@"
                  + projectId
                  + ".iam.gserviceaccount.com",
              request)
          .execute();

      System.out.println(
          "Enabled service account: "
              + "your-service-account-name@"
              + projectId
              + ".iam.gserviceaccount.com");
    } catch (IOException e) {
      System.out.println("Unable to enable service account: \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
    GoogleCredential credential =
        GoogleCredential.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(),
                credential)
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

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 .

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def enable_service_account(email):
    """Enables 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)

    service.projects().serviceAccounts().enable(
        name='projects/-/serviceAccounts/' + email).execute()

    print("Disabled service account :" + email)

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 .

import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
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 java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;

public class DeleteServiceAccount {

  // Deletes a service account.
  public static void deleteServiceAccount(String projectId) {
    // String projectId = "my-project-id";

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

    try {
      service
          .projects()
          .serviceAccounts()
          .delete(
              "projects/-/serviceAccounts/"
                  + "your-service-account-name@"
                  + projectId
                  + ".iam.gserviceaccount.com")
          .execute();

      System.out.println(
          "Deleted service account: "
              + "your-service-account-name@"
              + projectId
              + ".iam.gserviceaccount.com");
    } catch (IOException e) {
      System.out.println("Unable to delete service account: \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
    GoogleCredential credential =
        GoogleCredential.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(),
                credential)
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

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 .

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def delete_service_account(email):
    """Deletes 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)

    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

In some cases, you can use the undelete command to undelete a deleted service account. You can usually undelete a deleted service account if it meets these criteria:

  • The service account was deleted less than 30 days ago.

    After 30 days, Cloud IAM permanently removes the service account. GCP cannot recover the service account after it is permanently removed, even if you file a support request.

  • There is no existing service account with the same name as the deleted service account.

    For example, suppose that you accidentally delete the service account my-service-account@project-id.iam.gserviceaccount.com. You still need a service account with that name, so you create a new service account with the same name, my-service-account@project-id.iam.gserviceaccount.com. As a result, you cannot undelete the original service account, because the new service account has the same name.

    To address this issue, delete the new service account, then try to undelete the original service account.

Finding the service account's numeric ID

When you undelete a service account, you must provide its numeric ID. The numeric ID is a 21-digit number, such as 103271949540120710052, that uniquely identifies the service account. For example, if you delete a service account, then create a new service account with the same name, the original service account and the new service account will have different numeric IDs.

To find the numeric ID for a deleted service account, you can search your audit logs for DeleteServiceAccount operations:

  1. Go to the Logs Viewer page in the GCP Console.

    Go to the Logs Viewer

  2. In the search box near the top of the page, click the arrow_drop_down expander arrow, then select Convert to advanced filter.

  3. In the search box, enter the following query, replacing [SERVICE_ACCOUNT_NAME] with the name of your service account (for example, my-service-account@project-id.iam.gserviceaccount.com):

    resource.type="service_account"
    resource.labels.email_id="[SERVICE_ACCOUNT_NAME]"
    "DeleteServiceAccount"
    
  4. If the service account was deleted more than an hour ago, select the schedule Last hour drop-down list, then select a longer period of time.

    If the service account was deleted more than 7 days ago, select No limit.

  5. Click Submit filter. The Logs Viewer displays the DeleteServiceAccount operations that affected service accounts with the name you specified. The numeric ID for each service account appears next to the text DeleteServiceAccount.

    If the search results include only one DeleteServiceAccount operation, make note of the numeric ID. You will use the numeric ID to undelete the service account.

    If there is more than one search result, click the arrow_right expander arrow next to a search result. Review the details of the log entry, and determine whether the log entry shows the operation that you want to undo. Repeat this process until you find the correct log entry, then make note of the numeric ID in that entry.

Undeleting the service account by numeric ID

After you find the numeric ID for the deleted service account, you can try to undelete the service account.

GCLOUD COMMAND

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

Command:

gcloud beta iam service-accounts undelete [ACCOUNT_ID]

Output:

restoredAccount:
  email: SA-NAME@PROJECT-ID.iam.gserviceaccount.com
  etag: BwWWE7zpApg=
  name: projects/PROJECT-ID/serviceAccounts/SA-NAME@PROJECT-ID.iam.gserviceaccount.com
  oauth2ClientId: '123456789012345678901'
  projectId: PROJECT-ID
  uniqueId: '[ACCOUNT-ID]'

REST API

Use the serviceAccounts.undelete() method. Replace [ACCOUNT_UNIQUE_ID] with the numeric ID for the service account.

POST https://iam.googleapis.com/v1/projects/-/serviceAccounts/[ACCOUNT_UNIQUE_ID]:undelete

If the account can be undeleted, you receive a 200 OK response code with details about the restored service account.

What's next

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

Send feedback about...

Cloud IAM Documentation