This page explains how to list and edit service accounts using theIdentity and Access Management (IAM) API, the Google Cloud console, and the gcloud
command-line tool.
Before you begin
Enable the IAM 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
In the Google Cloud console, 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.
C++
To use the C++ samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
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 in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
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 in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
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 in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
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 in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
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
For more information, see Authenticate for using REST in the Google Cloud authentication documentation.
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:
- To view service accounts: View Service Accounts (
roles/iam.serviceAccountViewer
) - To edit service accounts: Service Account Admin (
roles/iam.serviceAccountAdmin
)
For more information about granting roles, see Manage access to projects, folders, and organizations.
You might also be able to get the required permissions through custom roles or other predefined roles.
To learn more about these roles, seeService Accounts roles.
IAM basic roles also contain permissions to manage serviceaccounts. You should not grant basic roles in a production environment, but you can grant them in adevelopment or test environment.
Listing service accounts
You can list the user-managed service accounts in a projectto help you audit service accounts and keys, or as part of a custom tool formanaging service accounts.
You can't list the service agents that might appear in yourproject's allow policy and audit logs. Service agents aren't located in yourproject, and you can't access them directly.
Console
In the Google Cloud console, go to the Service accounts page.
Select a project.
The Service accounts page lists all of the user-managed service accountsin the project you selected.
gcloud
-
In the Google Cloud console, 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.
-
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 EMAILSA_DISPLAY_NAME_1 SA_NAME_1@PROJECT_ID.iam.gserviceaccount.comSA_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.cloud.iam.admin.v1.IAMClient;import com.google.iam.admin.v1.ServiceAccount;import java.io.IOException;public class ListServiceAccounts { public static void main(String[] args) throws IOException { // TODO(Developer): Replace the below variables before running. String projectId = "your-project-id"; listServiceAccounts(projectId); } // Lists all service accounts for the current project. public static IAMClient.ListServiceAccountsPagedResponse listServiceAccounts(String projectId) throws IOException { // Initialize client that will be used to send requests. // This client only needs to be created once, and can be reused for multiple requests. try (IAMClient iamClient = IAMClient.create()) { IAMClient.ListServiceAccountsPagedResponse response = iamClient.listServiceAccounts(String.format("projects/%s", projectId)); for (ServiceAccount account : response.iterateAll()) { System.out.println("Name: " + account.getName()); System.out.println("Display name: " + account.getDisplayName()); System.out.println("Email: " + account.getEmail() + "\n"); } return response; } }}
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.
from typing import Listfrom google.cloud import iam_admin_v1from google.cloud.iam_admin_v1 import typesdef list_service_accounts(project_id: str) -> List[iam_admin_v1.ServiceAccount]: """ Get list of project service accounts. project_id: ID or number of the Google Cloud project you want to use. """ iam_admin_client = iam_admin_v1.IAMClient() request = types.ListServiceAccountsRequest() request.name = f"projects/{project_id}" accounts = iam_admin_client.list_service_accounts(request=request) return accounts.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 projectID. Project IDs are alphanumeric strings, likemy-project
.
HTTP method and URL:
GET https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts
To send your request, expand one of these options:
curl (Linux, macOS, or Cloud Shell)
Execute the following command:
curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts"
PowerShell (Windows)
Execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts" | Select-Object -Expand Content
APIs Explorer (browser)
Open the method reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Complete any required fields and click Execute.
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 arecommonly used to capture additional information about the service account, suchas the purpose of the service account or a contact person for the account.
Console
In the Google Cloud console, go to the Service accounts page.
Select a project.
Click the email address of the service account that you want to rename.
Enter the new name in the Name box, then click Save.
gcloud
-
In the Google Cloud console, 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.
-
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_DESCRIPTIONdisplayName: UPDATED_DISPLAY_NAMEname: 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/" + emailserviceAccount, 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 = newDisplayNameserviceAccount, 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.cloud.iam.admin.v1.IAMClient;import com.google.iam.admin.v1.GetServiceAccountRequest;import com.google.iam.admin.v1.PatchServiceAccountRequest;import com.google.iam.admin.v1.ServiceAccount;import com.google.iam.admin.v1.ServiceAccountName;import com.google.protobuf.FieldMask;import java.io.IOException;public class RenameServiceAccount { public static void main(String[] args) throws IOException { // TODO(developer): Replace the variables before running the sample. String projectId = "your-project-id"; String serviceAccountName = "my-service-account-name"; String displayName = "your-new-display-name"; renameServiceAccount(projectId, serviceAccountName, displayName); } // Changes a service account's display name. public static ServiceAccount renameServiceAccount(String projectId, String serviceAccountName, String displayName) throws IOException { // Construct the service account email. // You can modify the ".iam.gserviceaccount.com" to match the service account name in which // you want to delete the key. // See, https://cloud.google.com/iam/docs/creating-managing-service-account-keys?hl=en#deleting String serviceAccountEmail = serviceAccountName + "@" + projectId + ".iam.gserviceaccount.com"; // Initialize client that will be used to send requests. // This client only needs to be created once, and can be reused for multiple requests. try (IAMClient iamClient = IAMClient.create()) { // First, get a service account using getServiceAccount or listServiceAccounts GetServiceAccountRequest serviceAccountRequest = GetServiceAccountRequest.newBuilder() .setName(ServiceAccountName.of(projectId, serviceAccountEmail).toString()) .build(); ServiceAccount serviceAccount = iamClient.getServiceAccount(serviceAccountRequest); // You can patch only the `display_name` and `description` fields. You must use // the `update_mask` field to specify which of these fields you want to patch. serviceAccount = serviceAccount.toBuilder().setDisplayName(displayName).build(); PatchServiceAccountRequest patchServiceAccountRequest = PatchServiceAccountRequest.newBuilder() .setServiceAccount(serviceAccount) .setUpdateMask(FieldMask.newBuilder().addPaths("display_name").build()) .build(); serviceAccount = iamClient.patchServiceAccount(patchServiceAccountRequest); System.out.println( "Updated display name for " + serviceAccount.getName() + " to: " + serviceAccount.getDisplayName()); return serviceAccount; } }}
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.
from google.cloud import iam_admin_v1from google.cloud.iam_admin_v1 import typesdef rename_service_account( project_id: str, account: str, new_name: str) -> types.ServiceAccount: """ Renames service account display name. project_id: ID or number of the Google Cloud project you want to use. account: ID or email which is unique identifier of the service account. new_name: New display name of the service account. """ iam_admin_client = iam_admin_v1.IAMClient() get_request = types.GetServiceAccountRequest() get_request.name = f"projects/{project_id}/serviceAccounts/{account}" service_account = iam_admin_client.get_service_account(request=get_request) service_account.display_name = new_name request = types.PatchServiceAccountRequest() request.service_account = service_account # You can patch only the `display_name` and `description` fields. You must use # the `update_mask` field to specify which of these fields you want to patch. # To successfully set update mask you need to transform snake_case field to camelCase. # e.g. `display_name` will become `displayName` request.update_mask = "displayName" updated_account = iam_admin_client.patch_service_account(request=request) return updated_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 projectID. Project IDs are alphanumeric strings, likemy-project
.SA_ID
: The ID of your service account.This can either be the service account's email address in the formSA_NAME@PROJECT_ID.iam.gserviceaccount.com
, or the serviceaccount's unique numeric ID.SA_NAME
: The alphanumeric ID of yourservice account. This name must be between 6 and 30 characters, and can contain lowercasealphanumeric 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:
curl (Linux, macOS, or Cloud Shell)
Save the request body in a file named request.json
, and execute the following command:
curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID"
PowerShell (Windows)
Save the request body in a file named request.json
, and execute the following command:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }Invoke-WebRequest `
-Method PATCH `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID" | Select-Object -Expand Content
APIs Explorer (browser)
Copy the request body and open the method reference page. The APIs Explorer panel opens on the right side of the page. You can interact with this tool to send requests. Paste the request body in this tool, complete any other required fields, and click Execute.
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
- Learn how to disable and enable service accounts.
- Review the process for granting IAM roles to all types of principals,including service accounts.
- Explore how you can use role recommendations todownscope permissions for all principals, including service accounts.
- Understand how to attach service accounts to resources.
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.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2024-09-13 UTC.
[{ "type": "thumb-down", "id": "hardToUnderstand", "label":"Hard to understand" },{ "type": "thumb-down", "id": "incorrectInformationOrSampleCode", "label":"Incorrect information or sample code" },{ "type": "thumb-down", "id": "missingTheInformationSamplesINeed", "label":"Missing the information/samples I need" },{ "type": "thumb-down", "id": "otherDown", "label":"Other" }] [{ "type": "thumb-up", "id": "easyToUnderstand", "label":"Easy to understand" },{ "type": "thumb-up", "id": "solvedMyProblem", "label":"Solved my problem" },{ "type": "thumb-up", "id": "otherUp", "label":"Other" }]