Creating and managing service accounts

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

When you create a new Cloud project, Google Cloud 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): Includes permissions to list service accounts, get details about a service account, and impersonate a service account.
  • Service Account Admin (roles/iam.serviceAccountAdmin): Includes permissions to list service accounts and get details about a service account. Also includes permissions to create, update, and delete service accounts, and to view or change the IAM policy on a service account.

To learn more about these roles, see Service Accounts roles.

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

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.

When you create a service account, you must provide an alphanumeric ID (sa-name in the samples below), such as my-service-account. The ID must be between 6 and 30 characters, and can contain lowercase alphanumeric characters and dashes. After you create a service account, you cannot change its name.

The service account's name is a unique identifier; it will appear in the service account's email address that is provisioned during creation, such as sa-name@project-id.iam.gserviceaccount.com.

Each service account also has a unique numeric ID, which is generated automatically.

You also provide the following information when you create a service account:

  • 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 project.

To create a service account, at minimum the user must be granted the Service Account Admin role (roles/iam.serviceAccountAdmin) or the Editor basic role (roles/editor). You should not grant basic roles in a production environment, but you can grant them in a development or test environment.

After you create a service account, you might need to wait for 60 seconds or more before you use the service account. If you try to use a service account immediately after you create it, and you receive an error, wait at least 60 seconds and try again.

Console

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

    Go to the Service accounts page
  2. Select a project.
  3. Click Create service account.
  4. Enter a service account name to display in the Cloud Console.

    The Cloud Console generates a service account ID based on this name. Edit the ID if necessary. You cannot change the ID later.

  5. Optional: Enter a description of the service account.
  6. If you do not want to set access controls now, click Done to finish creating the service account.

    To set access controls now, click Create and continue to the next step.

  7. Optional: Choose one or more IAM roles to grant to the service account on the project.
  8. When you are done adding roles, click Continue.
  9. Optional: In the Service account users role field, add members that can impersonate the service account.
  10. Optional: In the Service account admins role field, add members that can manage the service account.
  11. Click Done to finish creating the service account.

gcloud

  1. To create the service account, run the gcloud iam service-accounts create command:

    gcloud iam service-accounts create SERVICE_ACCOUNT_ID \
        --description="DESCRIPTION" \
        --display-name="DISPLAY_NAME"

    Replace the following values:

    • SERVICE_ACCOUNT_ID: The ID for the service account.
    • DESCRIPTION: Optional. A description of the service account.
    • DISPLAY_NAME: A service account name to display in the Cloud Console.
  2. Optional: To grant your service account an IAM role on your project, run the gcloud projects add-iam-policy-binding command:

    gcloud projects add-iam-policy-binding PROJECT_ID \
        --member="serviceAccount:SERVICE_ACCOUNT_ID@PROJECT_ID.iam.gserviceaccount.com" \
        --role="ROLE_NAME"

    Replace the following values:

    • PROJECT_ID: The project id.
    • SERVICE_ACCOUNT_ID: The service account ID.
    • ROLE_NAME: A role name, such as roles/compute.osLogin.
  3. Optional: To allow users to impersonate the service account, run the gcloud iam service-accounts add-iam-policy-binding command to grant a user the Service Account User role (roles/iam.serviceAccountUser) on the service account:

    gcloud iam service-accounts add-iam-policy-binding \
        SERVICE_ACCOUNT_ID@PROJECT_ID.iam.gserviceaccount.com \
        --member="user:USER_EMAIL" \
        --role="roles/iam.serviceAccountUser"

    Replace the following values:

    • PROJECT_ID: The project ID.
    • SERVICE_ACCOUNT_ID: The service account ID.
    • USER_EMAIL: The email address for the user.

REST

The serviceAccounts.create method creates a service account.

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

  • project-id: Your Google Cloud project ID.
  • sa-name: The alphanumeric ID of your service account. This name must be between 6 and 30 characters, and can contain lowercase alphanumeric characters and dashes.
  • sa-description: Optional. A description for the service account.
  • sa-display-name: A human-readable name for the service account.

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/project-id/serviceAccounts

Request JSON body:

{
  "accountId": "sa-name",
  "serviceAccount": {
    "description": "sa-description",
    "displayName": "sa-display-name"
  }
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "name": "projects/my-project/serviceAccounts/my-service-account@my-project.iam.gserviceaccount.com",
  "projectId": "my-project",
  "uniqueId": "123456789012345678901",
  "email": "my-service-account@my-project.iam.gserviceaccount.com",
  "displayName": "My service account",
  "etag": "BwUp3rVlzes=",
  "description": "A service account for running jobs in my project",
  "oauth2ClientId": "987654321098765432109"
}

C#

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


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

public partial class 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 IAM Quickstart Using Client Libraries. For more information, see the IAM Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

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

// createServiceAccount creates a service account.
func createServiceAccount(w io.Writer, projectID, name, displayName string) (*iam.ServiceAccount, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %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 IAM Quickstart Using Client Libraries. For more information, see the IAM Java API reference documentation.

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

public class CreateServiceAccount {

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

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

    try {
      ServiceAccount serviceAccount = new ServiceAccount();
      serviceAccount.setDisplayName("your-display-name");
      CreateServiceAccountRequest request = new CreateServiceAccountRequest();
      request.setAccountId(serviceAccountName);
      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
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
    // Initialize the IAM service, which can be used to send requests to the IAM API.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

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

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def create_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 basic role (roles/viewer).

Console

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

    Go to the Service accounts page

  2. Select a project.

    The Service accounts page lists the service accounts in the project you selected.

gcloud

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

The serviceAccounts.list method lists every service account in your project.

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

  • project-id: Your Google Cloud project ID.

HTTP method and URL:

GET https://iam.googleapis.com/v1/projects/project-id/serviceAccounts

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "accounts": [
    {
      "name": "projects/my-project/serviceAccounts/sa-1@my-project.iam.gserviceaccount.com",
      "projectId": "my-project",
      "uniqueId": "123456789012345678901",
      "email": "sa-1@my-project.iam.gserviceaccount.com",
      "description": "My first service account",
      "displayName": "Service account 1",
      "etag": "BwUpTsLVUkQ=",
      "oauth2ClientId": "987654321098765432109"
    },
    {
      "name": "projects/my-project/serviceAccounts/sa-2@my-project.iam.gserviceaccount.com",
      "projectId": "my-project",
      "uniqueId": "234567890123456789012",
      "email": "sa-2@my-project.iam.gserviceaccount.com",
      "description": "My second service account",
      "displayName": "Service account 2",
      "etag": "UkQpTwBVUsL=",
      "oauth2ClientId": "876543210987654321098"
    }
  ]
}

C#

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


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

public partial class 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 IAM Quickstart Using Client Libraries. For more information, see the IAM Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

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

// listServiceAccounts lists a project's service accounts.
func listServiceAccounts(w io.Writer, projectID string) ([]*iam.ServiceAccount, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %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 IAM Quickstart Using Client Libraries. For more information, see the IAM Java API reference documentation.

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

public class 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
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
    // Initialize the IAM service, which can be used to send requests to the IAM API.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

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

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def list_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

Updating a service account

The display name (friendly name) and description of a service account are 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 update the name or description of a service account, at minimum the user must be granted the Service Account Admin role (roles/iam.serviceAccountAdmin) or the Editor basic role (roles/editor).

Console

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

    Go to the Service accounts page

  2. Select a project.

  3. Look for the service account you want to rename, click the in that row, and then click Edit.

  4. Enter the new name and click Save.

gcloud

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-sa-description
displayName: updated-display-name
name: projects/project-id/serviceAccounts/sa-name@project-id.iam.gserviceaccount.com

REST

The serviceAccounts.patch method updates a service account.

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

  • project-id: Your Google Cloud project ID.
  • sa-id: The ID of your service account. This can either be the service account's email address in the form sa-name@project-id.iam.gserviceaccount.com, or the service account's unique numeric ID.
  • sa-name: The alphanumeric ID of your service account. This name must be between 6 and 30 characters, and can contain lowercase alphanumeric characters and dashes.
  • Replace at least one of the following:
    • updated-display-name: A new display name for your service account.
    • updated-description: A new description for your service account.

HTTP method and URL:

PATCH https://iam.googleapis.com/v1/projects/project-id/serviceAccounts/sa-id 

Request JSON body:

{
  "serviceAccount": {
    "email": "sa-name@project-id.iam.gserviceaccount.com",
    "displayName": "updated-display-name",
    "description": "updated-description"
  },
  "updateMask": "displayName,description"
}

To send your request, expand one of these options:

You should receive a JSON response similar to the following:

{
  "name": "projects/my-project/serviceAccounts/my-service-account@my-project.iam.gserviceaccount.com",
  "displayName": "My updated service account",
  "description": "An updated description of my service account"
}

C#

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


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

public partial class 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 IAM Quickstart Using Client Libraries. For more information, see the IAM Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

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

// renameServiceAccount renames a service account.
func renameServiceAccount(w io.Writer, email, newDisplayName string) (*iam.ServiceAccount, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %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 IAM Quickstart Using Client Libraries. For more information, see the IAM Java API reference documentation.

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

public class RenameServiceAccount {

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

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

    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
    try {
      // First, get a service account using List() or Get()
      ServiceAccount serviceAccount =
          service
              .projects()
              .serviceAccounts()
              .get("projects/-/serviceAccounts/" + serviceAccountEmail)
              .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
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
    // Initialize the IAM service, which can be used to send requests to the IAM API.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

Before trying this sample, follow the Python setup instructions in the IAM Quickstart Using Client Libraries. For more information, see the 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 Google Cloud 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 basic role (roles/editor).

Console

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

    Go to the Service accounts page

  2. Select a project.

  3. Click the name of the service account that you want to disable.

  4. Under Service account status, click Disable service account, then click Disable to confirm the change.

gcloud

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

The serviceAccounts.disable method immediately disables a service account.

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

  • project-id: Your Google Cloud project ID.
  • sa-id: The ID of your service account. This can either be the service account's email address in the form sa-name@project-id.iam.gserviceaccount.com, or the service account's unique numeric ID.

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/project-id/serviceAccounts/sa-id:disable

To send your request, expand one of these options:

If successful, the response body will be empty.

C#

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


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

public partial class 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 IAM Quickstart Using Client Libraries. For more information, see the IAM Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	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
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return fmt.Errorf("iam.NewService: %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 IAM Quickstart Using Client Libraries. For more information, see the IAM Java API reference documentation.

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

public class DisableServiceAccount {

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

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

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

      System.out.println("Disabled service account: " + serviceAccountEmail);
    } 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
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
    // Initialize the IAM service, which can be used to send requests to the IAM API.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

Before trying this sample, follow the Python setup instructions in the IAM Quickstart Using Client Libraries. For more information, see the 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 Google Cloud 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 basic role (roles/editor).

Console

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

    Go to the Service accounts page

  2. Select a project.

  3. Click the name of the service account that you want to enable.

  4. Under Service account status, click Enable service account, then click Enable to confirm the change.

gcloud

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

The serviceAccounts.enable method enables a previously disabled service account.

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

  • project-id: Your Google Cloud project ID.
  • sa-id: The ID of your service account. This can either be the service account's email address in the form sa-name@project-id.iam.gserviceaccount.com, or the service account's unique numeric ID.

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/project-id/serviceAccounts/sa-id:enable

To send your request, expand one of these options:

If successful, the response body will be empty.

C#

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


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

public partial class 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 IAM Quickstart Using Client Libraries. For more information, see the IAM Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	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
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return fmt.Errorf("iam.NewService: %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 IAM Quickstart Using Client Libraries. For more information, see the IAM Java API reference documentation.

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

public class EnableServiceAccount {

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

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

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

      System.out.println("Enabled service account: " + serviceAccountEmail);
    } 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
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
    // Initialize the IAM service, which can be used to send requests to the IAM API.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

Before trying this sample, follow the Python setup instructions in the IAM Quickstart Using Client Libraries. For more information, see the 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("Enabled service account :" + email)

Deleting a service account

When you delete a service account, applications will no longer have access to Google Cloud 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.

Deleted service accounts do not count towards your service account quota.

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

Console

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

    Go to the Service accounts page

  2. Select a project.

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

gcloud

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

The serviceAccounts.delete method deletes a service account.

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

  • project-id: Your Google Cloud project ID.
  • sa-id: The ID of your service account. This can either be the service account's email address in the form sa-name@project-id.iam.gserviceaccount.com, or the service account's unique numeric ID.

HTTP method and URL:

DELETE https://iam.googleapis.com/v1/projects/project-id/serviceAccounts/sa-id

To send your request, expand one of these options:

If successful, the response body will be empty.

C#

Before trying this sample, follow the C# setup instructions in the IAM Quickstart Using Client Libraries. For more information, see the 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 IAM Quickstart Using Client Libraries. For more information, see the IAM Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

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

// deleteServiceAccount deletes a service account.
func deleteServiceAccount(w io.Writer, email string) error {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return fmt.Errorf("iam.NewService: %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 IAM Quickstart Using Client Libraries. For more information, see the IAM Java API reference documentation.

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.iam.v1.Iam;
import com.google.api.services.iam.v1.IamScopes;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
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 serviceAccountName) {
    // String projectId = "my-project-id";
    // String serviceAccountName = "my-service-account-name";

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

    String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com";
    try {
      service
          .projects()
          .serviceAccounts()
          .delete("projects/-/serviceAccounts/" + serviceAccountEmail)
          .execute();

      System.out.println("Deleted service account: " + serviceAccountEmail);
    } 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
    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
    // Initialize the IAM service, which can be used to send requests to the IAM API.
    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

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

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def delete_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)

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, IAM permanently removes the service account. Google Cloud 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.

    The new service account does not inherit the permissions of the deleted service account. In effect, it is completely separate from the deleted service account. However, 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.

If you are not able to undelete the service account, you can create a new service account with the same name; revoke all of the roles from the deleted service account; and grant the same roles to the new service account. For details, see Policies with deleted members.

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 123456789012345678901, 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.

If you know that a binding in an IAM policy includes the deleted service account, you can get the policy, then find the numeric ID in the policy. The numeric ID is appended to the name of the deleted service account. For example, in this policy, the numeric ID for the deleted service account is 123456789012345678901:

{
  "version": 1,
  "etag": "BwUjMhCsNvY=",
  "bindings": [
    {
      "members": [
        "deleted:serviceAccount:my-service-account@project-id.iam.gserviceaccount.com?uid=123456789012345678901"
      ],
      "role": "roles/iam.serviceAccountUser"
    },
  ]
}

Alternatively, you can search your audit logs for the DeleteServiceAccount operation that deleted the service account:

  1. In the Cloud Console, go to the Logs viewer page.

    Go to the Logs viewer page

  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-email with the email address of your service account (for example, my-service-account@project-id.iam.gserviceaccount.com):

    resource.type="service_account"
    resource.labels.email_id="service-account-email"
    "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 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

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

The serviceAccounts.undelete method restores a deleted service account.

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

  • project-id: Your Google Cloud project ID.
  • sa-numeric-id: The unique numeric ID of the service account.

HTTP method and URL:

POST https://iam.googleapis.com/v1/projects/project-id/serviceAccounts/sa-numeric-id:undelete

To send your request, expand one of these options:

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

{
  "restoredAccount": {
    "name": "projects/my-project/serviceAccounts/my-service-account@my-project.iam.gserviceaccount.com",
    "projectId": "my-project",
    "uniqueId": "123456789012345678901",
    "email": "my-service-account@my-project.iam.gserviceaccount.com",
    "displayName": "My service account",
    "etag": "BwUp3rVlzes=",
    "description": "A service account for running jobs in my project",
    "oauth2ClientId": "987654321098765432109"
  }
}

What's next