列出和修改服务账号

本页面介绍如何使用 Identity and Access Management (IAM) API、Google Cloud 控制台和 gcloud 命令行工具列出和修改服务账号。

准备工作

  • Enable the IAM API.

    Enable the API

  • 设置身份验证。

    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.

    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++

    如需在本地开发环境中使用本页面上的 C++ 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    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 user account:

      gcloud auth application-default login

    如需了解详情,请参阅 Google Cloud 身份验证文档中的为本地开发环境设置身份验证

    C#

    如需在本地开发环境中使用本页面上的 .NET 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    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 user account:

      gcloud auth application-default login

    如需了解详情,请参阅 Google Cloud 身份验证文档中的为本地开发环境设置身份验证

    Go

    如需在本地开发环境中使用本页面上的 Go 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    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 user account:

      gcloud auth application-default login

    如需了解详情,请参阅 Google Cloud 身份验证文档中的为本地开发环境设置身份验证

    Java

    如需在本地开发环境中使用本页面上的 Java 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    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 user account:

      gcloud auth application-default login

    如需了解详情,请参阅 Google Cloud 身份验证文档中的为本地开发环境设置身份验证

    Python

    如需在本地开发环境中使用本页面上的 Python 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭据设置应用默认凭据。

    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 user account:

      gcloud auth application-default login

    如需了解详情,请参阅 Google Cloud 身份验证文档中的为本地开发环境设置身份验证

    REST

    如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 gcloud CLI 的凭据。

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

      gcloud init

    如需了解详情,请参阅 Google Cloud 身份验证文档中的使用 REST 时进行身份验证

  • 了解 IAM 服务账号

所需的角色

如需获得管理服务账号所需的权限,请让管理员向您授予项目的以下 IAM 角色:

如需详细了解如何授予角色,请参阅管理访问权限

您也可以通过自定义角色或其他预定义角色来获取所需的权限。

如需详细了解这些角色,请参阅服务账号角色

IAM 基本角色也具有管理服务账号的权限。您不应在生产环境中授予基本角色,但可以在开发或测试环境中授予这些角色。

列出服务账号

您可以列出项目中的用户管理的服务账号以帮助您审核服务账号和密钥,也可以列出用于管理服务账号的自定义工具。

您无法列出可能出现在项目的允许政策和审核日志中的服务代理或其他 Google 管理的服务账号。Google 管理的服务账号不在您的项目中,您无法直接访问它们。

控制台

  1. 在 Google Cloud 控制台中,转到服务账号页面。

    转到“服务账号”

  2. 选择一个项目。

    服务账号页面列出了您所选项目中所有用户管理的服务账号。

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. 执行 gcloud iam service-accounts list 命令可列出项目中的所有服务账号。

    命令:

    gcloud iam service-accounts list

    输出会列出项目中所有用户管理的服务账号:

    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++

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C++ API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

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#

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C# API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作


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

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Go API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

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

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Java API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

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

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Python API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

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

serviceAccounts.list 方法可列出项目中的每个用户管理的服务账号。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。项目 ID 是字母数字字符串,例如 my-project

HTTP 方法和网址:

GET https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

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

修改服务账号

通常可通过服务账号的显示名(易记名称)和说明获知有关该服务账号的额外信息,例如服务账号的用途或该账号的联系人。

控制台

  1. 在 Google Cloud 控制台中,转到服务账号页面。

    转到“服务账号”

  2. 选择一个项目。

  3. 点击要重命名的服务账号的电子邮件地址。

  4. 名称框中输入新名称,然后点击保存

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. 执行 gcloud iam service-accounts update 命令可更新服务账号。

    命令:

    gcloud iam service-accounts update \
        SA_NAME@PROJECT_ID.iam.gserviceaccount.com \
        --description="UPDATED_SA_DESCRIPTION" \
        --display-name="UPDATED_DISPLAY_NAME"

    输出是重命名后的服务账号:

    description: UPDATED_SA_DESCRIPTION
    displayName: UPDATED_DISPLAY_NAME
    name: projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com
    

C++

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C++ API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

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#

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM C# API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作


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

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Go API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

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

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Java API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作


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

如需了解如何安装和使用 IAM 客户端库,请参阅 IAM 客户端库。如需了解详情,请参阅 IAM Python API 参考文档

如需向 IAM 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅准备工作

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

serviceAccounts.patch 方法可更新服务账号。

在使用任何请求数据之前,请先进行以下替换:

  • PROJECT_ID:您的 Google Cloud 项目 ID。项目 ID 是字母数字字符串,例如 my-project
  • SA_ID:您的服务账号的 ID。此 ID 可以是服务账号的电子邮件地址(格式为 SA_NAME@PROJECT_ID.iam.gserviceaccount.com)或服务账号的唯一数字 ID。
  • SA_NAME:您的服务账号的字母数字 ID。此名称必须介于 6 到 30 个字符之间,且可以包含小写字母数字字符和短划线。
  • 请至少替换以下其中一项:
    • UPDATED_DISPLAY_NAME:您的服务账号的新显示名。
    • UPDATED_DESCRIPTION:您的服务账号的新说明。

HTTP 方法和网址:

PATCH https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_ID 

请求 JSON 正文:

{
  "serviceAccount": {
    "email": "SA_NAME@PROJECT_ID.iam.gserviceaccount.com",
    "displayName": "UPDATED_DISPLAY_NAME",
    "description": "UPDATED_DESCRIPTION"
  },
  "updateMask": "displayName,description"
}

如需发送您的请求,请展开以下选项之一:

您应该收到类似以下内容的 JSON 响应:

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

后续步骤

自行试用

如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。

免费开始使用