建立服務帳戶

本頁說明如何使用 Identity and Access Management (IAM) API、 Google Cloud 控制台和 gcloud 指令列工具建立服務帳戶。

根據預設,每個專案最多可有 100 個服務帳戶,用於控管資源存取權。如有需要,您可以申請提高配額。進一步瞭解配額與限制

事前準備

  • 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#

      如要在本機開發環境中使用本頁的 .NET 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. 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.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      C++

      如要在本機開發環境中使用本頁的 C++ 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. 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.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Go

      如要在本機開發環境中使用本頁的 Go 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. 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.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Java

      如要在本機開發環境中使用本頁的 Java 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. 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.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      Python

      如要在本機開發環境中使用本頁的 Python 範例,請安裝並初始化 gcloud CLI,然後使用使用者憑證設定應用程式預設憑證。

      1. Install the Google Cloud CLI.

      2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      3. To initialize the gcloud CLI, run the following command:

        gcloud init
      4. 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.

        If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「 為本機開發環境設定 ADC」。

      REST

      如要在本機開發環境中使用本頁的 REST API 範例,請使用您提供給 gcloud CLI 的憑證。

        After installing the Google Cloud CLI, initialize it by running the following command:

        gcloud init

        If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

      詳情請參閱 Google Cloud 驗證說明文件中的「Authenticate for using REST」。

    1. 瞭解 IAM 服務帳戶

必要的角色

如要取得建立服務帳戶所需的權限,請要求管理員授予您專案的「建立服務帳戶」 (roles/iam.serviceAccountCreator) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

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

如要授予新建立的服務帳戶專案存取權,您也需要專案 IAM 管理員 (roles/resourcemanager.projectIamAdmin) 角色。

建立服務帳戶

建立服務帳戶時,您必須提供英數字元 ID (以下範例中的 SERVICE_ACCOUNT_NAME),例如 my-service-account。ID 長度必須介於 6 至 30 個字元之間,可以使用小寫英數字元和破折號。服務帳戶建立完成後,您就無法變更名稱。

服務帳戶名稱會出現在建立期間佈建的電子郵件地址中,格式為 SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com

每個服務帳戶也都有永久且不重複的數字 ID,系統會自動產生這組 ID。

建立服務帳戶時,您也需要提供下列資訊:

  • DESCRIPTION 是服務帳戶的選填說明。
  • DISPLAY_NAME 是服務帳戶的好記名稱。
  • PROJECT_ID 是 Google Cloud 專案 ID。

建立服務帳戶後,可能需要等待 60 秒以上才能使用該帳戶。發生這種情況的原因是讀取作業具有最終一致性,因此需要一段時間才能顯示新的服務帳戶。如果您在建立服務帳戶後立即嘗試讀取或使用該帳戶,但收到錯誤訊息,可以使用指數輪詢重試要求

控制台

  1. 前往 Google Cloud 控制台的「Create service account」(建立服務帳戶) 頁面。

    前往「建立服務帳戶」

    其餘步驟會顯示在 Google Cloud 控制台。

  2. 選取 Google Cloud 專案。
  3. 輸入要顯示在 Google Cloud 控制台的服務帳戶名稱。

    Google Cloud 控制台會根據這個名稱產生服務帳戶 ID。請視需要編輯 ID,ID 設定後即無法變更。

  4. 選用:輸入服務帳戶的說明。
  5. 如果您現在不想設定存取權控管機制,請按一下「Done」(完成) 以完成服務帳戶建立程序。如要立即設定存取權控管,請按一下「Create and continue」(建立並繼續),然後繼續進行下一個步驟。
  6. 選用:選擇一或多個 IAM 角色以授予專案的服務帳戶。
  7. 新增角色之後,請按一下「Continue」(繼續)
  8. 選用:在「Service account users role」(服務帳戶使用者角色) 欄位中,新增需要將服務帳戶附加至其他資源的成員。
  9. 選用:在「Service account admins role」(服務帳戶管理員角色) 欄位中,新增需要管理服務帳戶的成員。
  10. 按一下「Done」(完成),即完成建立服務帳戶。

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 create 指令:

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

    替換下列值:

    • SERVICE_ACCOUNT_NAME:服務帳戶名稱

    • DESCRIPTION:服務帳戶的選填說明

    • DISPLAY_NAME:要在 Google Cloud 控制台中顯示的服務帳戶名稱

  3. 選用:如要授予服務帳戶專案的 IAM 角色,請執行 gcloud projects add-iam-policy-binding 指令:

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

    替換下列值:

    • PROJECT_ID:專案 ID

    • SERVICE_ACCOUNT_NAME:服務帳戶名稱

    • ROLE_NAME:角色名稱,例如 roles/compute.osLogin

  4. 選用:如要允許使用者將服務帳戶附加至其他資源,請執行 gcloud iam service-accounts add-iam-policy-binding 指令,在服務帳戶上授予使用者服務帳戶使用者角色 (roles/iam.serviceAccountUser):

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

    替換下列值:

    • PROJECT_ID:專案 ID

    • SERVICE_ACCOUNT_NAME:服務帳戶名稱

    • USER_EMAIL:使用者的電子郵件地址

C++

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

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

namespace iam = ::google::cloud::iam_admin_v1;
[](std::string const& project_id, std::string const& account_id,
   std::string const& display_name, std::string const& description) {
  iam::IAMClient client(iam::MakeIAMConnection());
  google::iam::admin::v1::ServiceAccount service_account;
  service_account.set_display_name(display_name);
  service_account.set_description(description);
  auto response = client.CreateServiceAccount("projects/" + project_id,
                                              account_id, service_account);
  if (!response) throw std::move(response).status();
  std::cout << "ServiceAccount successfully created: "
            << 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 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

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

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

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: %w", 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: %w", err)
	}
	fmt.Fprintf(w, "Created service account: %v", account)
	return account, nil
}

Java

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

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


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.iam.admin.v1.CreateServiceAccountRequest;
import com.google.iam.admin.v1.ProjectName;
import com.google.iam.admin.v1.ServiceAccount;
import java.io.IOException;

public class CreateServiceAccount {
  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";

    createServiceAccount(projectId, serviceAccountName);
  }

  // Creates a service account.
  public static ServiceAccount createServiceAccount(String projectId, String serviceAccountName)
          throws IOException {
    ServiceAccount serviceAccount = ServiceAccount
            .newBuilder()
            .setDisplayName("your-display-name")
            .build();
    CreateServiceAccountRequest request = CreateServiceAccountRequest.newBuilder()
            .setName(ProjectName.of(projectId).toString())
            .setAccountId(serviceAccountName)
            .setServiceAccount(serviceAccount)
            .build();
    // 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()) {
      serviceAccount = iamClient.createServiceAccount(request);
      System.out.println("Created service account: " + serviceAccount.getEmail());
    }
    return serviceAccount;
  }
}

Python

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

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

from typing import Optional

from google.cloud import iam_admin_v1
from google.cloud.iam_admin_v1 import types


def create_service_account(
    project_id: str, account_id: str, display_name: Optional[str] = None
) -> types.ServiceAccount:
    """Creates a service account.

    project_id: ID or number of the Google Cloud project you want to use.
    account_id: ID which will be unique identifier of the service account
    display_name (optional): human-readable name, which will be assigned
        to the service account

    return: ServiceAccount
    """

    iam_admin_client = iam_admin_v1.IAMClient()
    request = types.CreateServiceAccountRequest()

    request.account_id = account_id
    request.name = f"projects/{project_id}"

    service_account = types.ServiceAccount()
    service_account.display_name = display_name
    request.service_account = service_account

    account = iam_admin_client.create_service_account(request=request)

    print(f"Created a service account: {account.email}")
    return account

REST

serviceAccounts.create 方法會建立服務帳戶。

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

  • PROJECT_ID:您的 Google Cloud 專案 ID。專案 ID 為英數字串,例如 my-project
  • SA_NAME:服務帳戶的英數字元 ID。名稱長度必須介於 6 至 30 個字元之間,可以使用小寫英數字元和破折號。
  • SA_DESCRIPTION:選用。服務帳戶的說明。
  • SA_DISPLAY_NAME:服務帳戶的名稱,方便使用者辨識。

HTTP 方法和網址:

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

JSON 要求主體:

{
  "accountId": "SA_NAME",
  "serviceAccount": {
    "description": "SA_DESCRIPTION",
    "displayName": "SA_DISPLAY_NAME"
  }
}

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

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

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

建立好服務帳戶之後,為該服務帳戶授予一或多個角色,使其能夠代表您執行作業。

此外,如果服務帳戶需要存取其他專案中的資源,您通常必須在建立服務帳戶的專案中啟用這些資源的 API

後續步驟

歡迎試用

如果您未曾使用過 Google Cloud,歡迎建立帳戶來評估我們的產品在實際工作環境中的成效。新客戶還能獲得價值 $300 美元的免費抵免額,可用於執行、測試及部署工作負載。

免費試用