List and edit service accounts

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

Before you begin

  • Enable the IAM API.

    Enable the API

  • Set up authentication.

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    You can use the gcloud CLI samples on this page from either of the following development environments:

    • Cloud Shell: To use an online terminal with the gcloud CLI already set up, activate Cloud Shell.

      At the bottom of this page, a Cloud Shell session starts and displays a command-line prompt. It can take a few seconds for the session to initialize.

    • Local shell: To use the gcloud CLI in a local development environment, install and initialize the gcloud CLI.

    C++

    To use the C++ samples on this page from a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. Create local authentication credentials for your Google Account:

      gcloud auth application-default login

    For more information, see Set up authentication for a local development environment in the Google Cloud authentication documentation.

    C#

    To use the .NET samples on this page from a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. Create local authentication credentials for your Google Account:

      gcloud auth application-default login

    For more information, see Set up authentication for a local development environment in the Google Cloud authentication documentation.

    Go

    To use the Go samples on this page from a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. Create local authentication credentials for your Google Account:

      gcloud auth application-default login

    For more information, see Set up authentication for a local development environment in the Google Cloud authentication documentation.

    Java

    To use the Java samples on this page from a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. Create local authentication credentials for your Google Account:

      gcloud auth application-default login

    For more information, see Set up authentication for a local development environment in the Google Cloud authentication documentation.

    Python

    To use the Python samples on this page from a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.

    1. Install the Google Cloud CLI.
    2. To initialize the gcloud CLI, run the following command:

      gcloud init
    3. Create local authentication credentials for your Google Account:

      gcloud auth application-default login

    For more information, see Set up authentication for a local development environment in the Google Cloud authentication documentation.

    REST

    To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.

      Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init

  • Understand IAM service accounts

Required roles

To get the permissions that you need to manage service accounts, ask your administrator to grant you the following IAM roles on the project:

For more information about granting roles, see Manage access.

You might also be able to get the required permissions through custom roles or other predefined roles.

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.

Listing service accounts

You can list the user-managed service accounts in a project to help you audit service accounts and keys, or as part of a custom tool for managing service accounts.

You can't list the service agents or other Google-managed service accounts that might appear in your project's allow policy and audit logs. Google-managed service accounts aren't located in your project, and you can't access them directly.

Console

  1. In the Google Cloud console, go to the Service accounts page.

    Go to Service accounts

  2. Select a project.

    The Service accounts page lists all of the user-managed service accounts in the project you selected.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 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 user-managed 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
    

C++

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& project_id) {
  iam::IAMClient client(iam::MakeIAMConnection());
  int count = 0;
  for (auto& sa : client.ListServiceAccounts("projects/" + project_id)) {
    if (!sa) throw std::move(sa).status();
    std::cout << "ServiceAccount successfully retrieved: " << sa->name()
              << "\n";
    ++count;
  }
  if (count == 0) {
    std::cout << "No service accounts found in project: " << project_id
              << "\n";
  }
}

C#

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.


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

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

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: %w", err)
	}

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

Java

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
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(),
                GsonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

import os

from google.oauth2 import service_account  # type: ignore
import googleapiclient.discovery  # type: ignore

def list_service_accounts(project_id: str) -> dict:
    """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

REST

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

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

  • PROJECT_ID: Your Google Cloud project ID. Project IDs are alphanumeric strings, like my-project.

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"
    }
  ]
}

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

Console

  1. In the Google Cloud console, go to the Service accounts page.

    Go to Service accounts

  2. Select a project.

  3. Click the email address of the service account that you want to rename.

  4. Enter the new name in the Name box, then click Save.

gcloud

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

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

C++

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& name, std::string const& display_name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::PatchServiceAccountRequest request;
  google::iam::admin::v1::ServiceAccount service_account;
  service_account.set_name(name);
  service_account.set_display_name(display_name);
  google::protobuf::FieldMask update_mask;
  *update_mask.add_paths() = "display_name";
  *request.mutable_service_account() = service_account;
  *request.mutable_update_mask() = update_mask;
  auto response = client.PatchServiceAccount(request);
  if (!response) throw std::move(response).status();
  std::cout << "ServiceAccount successfully updated: "
            << response->DebugString() << "\n";
}

C#

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.


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

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

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: %w", 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: %w", 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: %w", err)
	}

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

Java

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
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(),
                GsonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("service-accounts")
            .build();
    return service;
  }
}

Python

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

To authenticate to IAM, set up Application Default Credentials. For more information, see Before you begin.

import os

from google.oauth2 import service_account  # type: ignore
import googleapiclient.discovery  # type: ignore

def rename_service_account(email: str, new_display_name: str) -> dict:
    """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

REST

The serviceAccounts.patch method updates a service account.

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

  • PROJECT_ID: Your Google Cloud project ID. Project IDs are alphanumeric strings, like my-project.
  • SA_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"
}

What's next

Try it for yourself

If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.

Get started for free