列出及編輯服務帳戶

本頁說明如何使用 Identity and Access Management (IAM) API、 Trusted Cloud 控制台和 gcloud 指令列工具,列出及編輯服務帳戶。

事前準備

必要的角色

如要取得管理服務帳戶所需的權限,請要求管理員在專案中授予下列 IAM 角色:

  • 如要查看服務帳戶: 按一下「查看服務帳戶」 (roles/iam.serviceAccountViewer)
  • 如要編輯服務帳戶: 服務帳戶管理員 (roles/iam.serviceAccountAdmin)

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

您或許還可透過自訂角色或其他預先定義的角色取得必要權限。

如要進一步瞭解這些角色,請參閱「服務帳戶角色」。

身分與存取權管理基本角色也包含管理服務帳戶的權限。您不應在正式版環境中授予基本角色,但可以在開發或測試環境中授予。

列出服務帳戶

您可以列出專案中的使用者代管服務帳戶,以稽核服務帳戶和金鑰,或做為管理服務帳戶的自訂工具。

您無法列出可能出現在專案允許政策和稽核記錄中的服務代理程式。服務代理不在您的專案中,您無法直接存取。

控制台

  1. 前往 Trusted Cloud 控制台的「Service accounts」(服務帳戶) 頁面。

    前往「Service accounts」(服務帳戶)

  2. 選取專案。

    「Service accounts」(服務帳戶) 頁面會列出所選專案中的所有使用者管理服務帳戶。

gcloud

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

    Activate Cloud Shell

    At the bottom of the Trusted 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.s3ns-system.iam.gserviceaccount.com
    SA_DISPLAY_NAME_2    SA_NAME_2@PROJECT_ID.s3ns-system.iam.gserviceaccount.com
    
  3. C++

    如要瞭解如何安裝及使用 IAM 的用戶端程式庫,請參閱 IAM 用戶端程式庫。 詳情請參閱 IAM C++ API 參考說明文件

    如要向 IAM 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

    執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

    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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

    執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

    
    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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

    執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

    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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

    執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

    
    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

    如要瞭解如何安裝及使用 IAM 的用戶端程式庫,請參閱 IAM 用戶端程式庫。 詳情請參閱 IAM Python API 參考說明文件

    如要向 IAM 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

    執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

    from typing import List
    
    from google.cloud import iam_admin_v1
    from google.cloud.iam_admin_v1 import types
    
    
    def 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.
    
        returns a list of iam_admin_v1.ServiceAccount
        """
    
        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

    serviceAccounts.list 方法會列出專案中的所有使用者管理服務帳戶。

    使用任何要求資料之前,請先替換以下項目:

    • PROJECT_ID:您的 Trusted 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.s3ns-system.iam.gserviceaccount.com",
          "projectId": "my-project",
          "uniqueId": "123456789012345678901",
          "email": "sa-1@my-project.s3ns-system.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.s3ns-system.iam.gserviceaccount.com",
          "projectId": "my-project",
          "uniqueId": "234567890123456789012",
          "email": "sa-2@my-project.s3ns-system.iam.gserviceaccount.com",
          "description": "My second service account",
          "displayName": "Service account 2",
          "etag": "UkQpTwBVUsL=",
          "oauth2ClientId": "876543210987654321098"
        }
      ]
    }
    

編輯服務帳戶

服務帳戶的顯示名稱 (好記的名稱) 和說明通常用於擷取與服務帳戶有關的其他資訊,例如服務帳戶用途或帳戶聯絡人。

控制台

  1. 前往 Trusted Cloud 控制台的「Service accounts」(服務帳戶) 頁面。

    前往「Service accounts」(服務帳戶)

  2. 選取專案。

  3. 按一下要重新命名的服務帳戶電子郵件地址。

  4. 在「名稱」方塊中輸入新名稱,然後按一下「儲存」

gcloud

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

    Activate Cloud Shell

    At the bottom of the Trusted 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.s3ns-system.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.s3ns-system.iam.gserviceaccount.com
    
  3. C++

    如要瞭解如何安裝及使用 IAM 的用戶端程式庫,請參閱 IAM 用戶端程式庫。 詳情請參閱 IAM C++ API 參考說明文件

    如要向 IAM 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

    執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

    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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

    執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

    
    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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

    執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

    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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

    執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

    
    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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「事前準備」。

    執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr

    from google.cloud import iam_admin_v1
    from google.cloud.iam_admin_v1 import types
    
    
    def 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

    serviceAccounts.patch 方法會更新服務帳戶。

    使用任何要求資料之前,請先替換以下項目:

    • PROJECT_ID:您的 Trusted Cloud 專案 ID。專案 ID 為英數字串,例如 my-project
    • SA_ID:服務帳戶的 ID。 這可以是 SA_NAME@PROJECT_ID.s3ns-system.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.s3ns-system.iam.gserviceaccount.com",
        "displayName": "UPDATED_DISPLAY_NAME",
        "description": "UPDATED_DESCRIPTION"
      },
      "updateMask": "displayName,description"
    }
    

    如要傳送要求,請展開以下其中一個選項:

    您應該會收到如下的 JSON 回應:

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

後續步驟