建立及刪除服務帳戶金鑰

本頁面說明如何使用Google Cloud 控制台、Google Cloud CLIIdentity and Access Management APIGoogle Cloud 用戶端程式庫建立及刪除服務帳戶金鑰。

事前準備

  • 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. 瞭解服務帳戶憑證

必要的角色

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

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

詳情請參閱「服務帳戶角色」。

視貴機構政策設定而定,您可能也需要在專案中允許建立服務帳戶金鑰,才能建立金鑰。

如要取得權限,允許在專案中建立服務帳戶金鑰,請要求管理員在機構中授予下列 IAM 角色:

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

這些預先定義的角色包含在專案中建立服務帳戶金鑰所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要在專案中建立服務帳戶金鑰,您必須具備下列權限:

  • orgpolicy.constraints.list
  • orgpolicy.customConstraints.create
  • orgpolicy.customConstraints.delete
  • orgpolicy.customConstraints.get
  • orgpolicy.customConstraints.list
  • orgpolicy.customConstraints.update
  • orgpolicy.policies.create
  • orgpolicy.policies.delete
  • orgpolicy.policies.list
  • orgpolicy.policies.update
  • orgpolicy.policy.get
  • orgpolicy.policy.set
  • resourcemanager.organizations.get
  • resourcemanager.projects.listTagBindings
  • resourcemanager.projects.listEffectiveTags
  • resourcemanager.tagKeys.get
  • resourcemanager.tagKeys.list
  • resourcemanager.tagValues.list
  • resourcemanager.tagValues.get

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

允許建立服務帳戶金鑰

建立服務帳戶金鑰前,請確認專案未強制執行iam.disableServiceAccountKeyCreation機構政策限制。如果專案強制執行這項限制,您就無法在該專案中建立服務帳戶金鑰。

建議您為大多數專案強制執行這項限制,僅豁免真正需要服務帳戶金鑰的專案。如要進一步瞭解其他驗證方法,請參閱「根據用途選擇合適的驗證方法」。

如要免除專案的 iam.disableServiceAccountKeyCreation 機構政策限制,請機構政策管理員執行下列操作:

  1. 在機構層級建立標記鍵和標記值,用於定義資源是否應豁免於機構政策。建議您建立含有 disableServiceAccountKeyCreation 鍵和 enforcednot_enforced 值的標記。

    如要瞭解如何建立代碼鍵和代碼值,請參閱建立及定義新代碼

  2. disableServiceAccountKeyCreation 標記附加至機構,並將值設為 enforced。除非以其他標記值覆寫,否則組織中的所有資源都會繼承這個標記值。

    如要瞭解如何將標記附加至資源,請參閱將標記附加至資源

  3. 如要為專案或資料夾免除機構政策限制,請附加 disableServiceAccountKeyCreation 標記,並將值設為 not_enforced。以這種方式為專案或資料夾設定標記值,會覆寫從機構沿用的標記值。
  4. 建立或更新機構政策,禁止建立服務帳戶金鑰,以免對豁免資源強制執行限制。這項政策應包含下列規則:

    • 設定 iam.disableServiceAccountKeyCreation 限制,確保系統不會對任何含有 disableServiceAccountKeyCreation: not_enforced 標記的資源強制執行這項限制。這項規則中的條件應如下所示:

      "resource.matchTag('ORGANIZATION_ID/disableServiceAccountKeyCreation', 'not_enforced')"
      
    • 設定 iam.disableServiceAccountKeyCreation 限制,以強制執行所有其他資源。

建立服務帳戶金鑰

如要在 Google Cloud之外 (例如在其他平台或內部部署) 使用服務帳戶,您必須先建立服務帳戶的身分。公開/私密金鑰組是達成此目標的安全方式。建立服務帳戶金鑰時,公開部分會儲存於Google Cloud,私密部分則只有您看得見。如要進一步瞭解公開/私密金鑰配對,請參閱「服務帳戶金鑰」一文。

您可以使用 Google Cloud 控制台、gcloud CLI、serviceAccounts.keys.create()方法或其中一個用戶端程式庫,建立服務帳戶金鑰。 每個服務帳戶最多可有 10 個金鑰。

根據預設,服務帳戶金鑰永遠不會過期。您可以使用機構政策限制,指定服務帳戶金鑰的有效時間長度。詳情請參閱「使用者管理金鑰的到期時間」。

在下方的範例中,SA_NAME 是服務帳戶的名稱,PROJECT_ID 則是Google Cloud 專案的 ID。您可以從 Google Cloud 控制台的「Service Accounts」(服務帳戶) 頁面擷取 SA_NAME@PROJECT_ID.iam.gserviceaccount.com 字串。

控制台

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

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

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

  2. 選取專案。
  3. 點選所需的服務帳戶電子郵件地址,以便為其建立金鑰。
  4. 點選「Keys」(金鑰) 分頁標籤。
  5. 點選「Add key」(新增金鑰) 下拉式選單,然後選取「Create new key」(建立新的金鑰)
  6. 選取「JSON」做為金鑰類型,然後按一下「Create」(建立)

按一下「Create」(建立),即可下載服務帳戶金鑰檔案。金鑰檔案下載後,就不能再次下載。

下載的金鑰格式如下,其中 PRIVATE_KEY 是公開/私密金鑰組的私密部分:

{
  "type": "service_account",
  "project_id": "PROJECT_ID",
  "private_key_id": "KEY_ID",
  "private_key": "-----BEGIN PRIVATE KEY-----\nPRIVATE_KEY\n-----END PRIVATE KEY-----\n",
  "client_email": "SERVICE_ACCOUNT_EMAIL",
  "client_id": "CLIENT_ID",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/SERVICE_ACCOUNT_EMAIL"
}

請務必妥善保存金鑰檔案,因為此檔案可當做服務帳戶進行驗證。您可以任意移動及重新命名這個檔案。

您可以使用服務帳戶金鑰檔案,做為服務帳戶來驗證應用程式

gcloud

執行 gcloud iam service-accounts keys create 指令,建立服務帳戶金鑰。

替換下列值:

  • KEY_FILE:私密金鑰的新輸出檔案路徑,例如 ~/sa-private-key.json
  • SA_NAME:要建立金鑰的服務帳戶名稱。
  • PROJECT_ID:您的 Google Cloud 專案 ID。
gcloud iam service-accounts keys create KEY_FILE \
    --iam-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com

輸出:

created key [e44da1202f82f8f4bdd9d92bc412d1d8a837fa83] of type [json] as
[/usr/home/username/KEY_FILE] for
[SA_NAME@PROJECT_ID.iam.gserviceaccount.com]

服務帳戶金鑰檔案會下載到您的機器中,金鑰檔案下載後,就不能再次下載。

下載的金鑰格式如下,其中 PRIVATE_KEY 是公開/私密金鑰組的私密部分:

{
  "type": "service_account",
  "project_id": "PROJECT_ID",
  "private_key_id": "KEY_ID",
  "private_key": "-----BEGIN PRIVATE KEY-----\nPRIVATE_KEY\n-----END PRIVATE KEY-----\n",
  "client_email": "SERVICE_ACCOUNT_EMAIL",
  "client_id": "CLIENT_ID",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/SERVICE_ACCOUNT_EMAIL"
}

請務必妥善保存金鑰檔案,因為此檔案可當做服務帳戶進行驗證。您可以任意移動及重新命名此檔案。

您可以使用服務帳戶金鑰檔案,做為服務帳戶來驗證應用程式

C++

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

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

namespace iam = ::google::cloud::iam_admin_v1;
return [](std::string const& name) {
  iam::IAMClient client(iam::MakeIAMConnection());
  auto response = client.CreateServiceAccountKey(
      name,
      google::iam::admin::v1::ServiceAccountPrivateKeyType::
          TYPE_GOOGLE_CREDENTIALS_FILE,
      google::iam::admin::v1::ServiceAccountKeyAlgorithm::KEY_ALG_RSA_2048);
  if (!response) throw std::move(response).status();
  std::cout << "ServiceAccountKey successfully created: "
            << response->DebugString() << "\n"
            << "Please save the key in a secure location, as they cannot "
               "be downloaded later\n";
  return response->name();
}

C#

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

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


using System;
using System.Text;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Iam.v1;
using Google.Apis.Iam.v1.Data;

public partial class ServiceAccountKeys
{
    public static ServiceAccountKey CreateKey(string serviceAccountEmail)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var key = service.Projects.ServiceAccounts.Keys.Create(
            new CreateServiceAccountKeyRequest(),
            "projects/-/serviceAccounts/" + serviceAccountEmail)
            .Execute();

        // The PrivateKeyData field contains the base64-encoded service account key
        // in JSON format.
        // TODO(Developer): Save the below key (jsonKeyFile) to a secure location.
        //  You cannot download it later.
        byte[] valueBytes = System.Convert.FromBase64String(key.PrivateKeyData);
        string jsonKeyContent = Encoding.UTF8.GetString(valueBytes);

        Console.WriteLine("Key created successfully");
        return key;
    }
}

Go

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

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

import (
	"context"
	// "encoding/base64"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// createKey creates a service account key.
func createKey(w io.Writer, serviceAccountEmail string) (*iam.ServiceAccountKey, error) {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return nil, fmt.Errorf("iam.NewService: %w", err)
	}

	resource := "projects/-/serviceAccounts/" + serviceAccountEmail
	request := &iam.CreateServiceAccountKeyRequest{}
	key, err := service.Projects.ServiceAccounts.Keys.Create(resource, request).Do()
	if err != nil {
		return nil, fmt.Errorf("Projects.ServiceAccounts.Keys.Create: %w", err)
	}
	// The PrivateKeyData field contains the base64-encoded service account key
	// in JSON format.
	// TODO(Developer): Save the below key (jsonKeyFile) to a secure location.
	// You cannot download it later.
	// jsonKeyFile, _ := base64.StdEncoding.DecodeString(key.PrivateKeyData)
	fmt.Fprintf(w, "Key created successfully")
	return key, nil
}

Java

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

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


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.gson.Gson;
import com.google.iam.admin.v1.CreateServiceAccountKeyRequest;
import com.google.iam.admin.v1.ServiceAccountKey;
import java.io.IOException;

public class CreateServiceAccountKey {

  public static void main(String[] args) throws IOException {
    // TODO(Developer): Replace the below variables before running.
    String projectId = "your-project-id";
    String serviceAccountName = "your-service-account-name";

    ServiceAccountKey key = createKey(projectId, serviceAccountName);
    Gson gson = new Gson();

    // System.out.println("Service account key: " + gson.toJson(key));
  }

  // Creates a key for a service account.
  public static ServiceAccountKey createKey(String projectId, String accountName)
          throws IOException {
    String email = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);

    // 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()) {
      CreateServiceAccountKeyRequest req = CreateServiceAccountKeyRequest.newBuilder()
              .setName(String.format("projects/%s/serviceAccounts/%s", projectId, email))
              .build();
      ServiceAccountKey createdKey = iamClient.createServiceAccountKey(req);
      System.out.println("Key created successfully");

      return createdKey;
    }
  }
}

Python

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

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

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


def create_key(project_id: str, account: str) -> types.ServiceAccountKey:
    """
    Creates a key for a service account.

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

    iam_admin_client = iam_admin_v1.IAMClient()
    request = types.CreateServiceAccountKeyRequest()
    request.name = f"projects/{project_id}/serviceAccounts/{account}"

    key = iam_admin_client.create_service_account_key(request=request)

    # The private_key_data field contains the stringified service account key
    # in JSON format. You cannot download it again later.
    # If you want to get the value, you can do it in a following way:
    # import json
    # json_key_data = json.loads(key.private_key_data)
    # key_id = json_key_data["private_key_id"]

    return key

REST

projects.serviceAccounts.keys.create 方法會為服務帳戶建立金鑰。

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

  • PROJECT_ID:您的 Google Cloud 專案 ID。專案 ID 為英數字串,例如 my-project
  • SA_NAME:要建立金鑰的服務帳戶名稱。
  • KEY_ALGORITHM:選用。要用於金鑰的金鑰演算法。預設值為 2,048 位元 RSA 金鑰,但可能會變更。如需所有可能值的清單,請參閱 ServiceAccountKeyAlgorithm 參考資料

HTTP 方法和網址:

POST https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com/keys

JSON 要求主體:

{
  "keyAlgorithm": "KEY_ALGORITHM"
}

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

回應內容包含服務帳戶的金鑰。傳回的金鑰格式如下,其中 ENCODED_PRIVATE_KEY 是公開/私密金鑰組的私密部分,並以 Base64 編碼。

{
  "name": "projects/PROJECT_ID/serviceAccounts/SERVICE_ACCOUNT_EMAIL/keys/KEY_ID",
  "privateKeyType": "TYPE_GOOGLE_CREDENTIALS_FILE",
  "privateKeyData": "ENCODED_PRIVATE_KEY",
  "validAfterTime": "DATE",
  "validBeforeTime": "DATE",
  "keyAlgorithm": "KEY_ALG_RSA_2048"
}

如要建立可用於以服務帳戶身分驗證的金鑰檔案,請解碼私密金鑰資料並儲存至檔案:

Linux

執行下列指令:

echo 'ENCODED_PRIVATE_KEY' | base64 --decode > PATH

PATH 替換為您要儲存金鑰的檔案路徑。使用 .json 副檔名。

macOS

執行下列指令:

echo 'ENCODED_PRIVATE_KEY' | base64 --decode > PATH

PATH 替換為您要儲存金鑰的檔案路徑。使用 .json 副檔名。

PowerShell

  1. 將編碼後的私密金鑰資料 (ENCODED_PRIVATE_KEY) 儲存至檔案。

  2. 使用 certutil 解碼檔案:

    certutil -decode ENCODED_FILE DECODED_FILE

    替換下列值:

    • ENCODED_FILE:包含編碼私密金鑰資料的檔案路徑。
    • DECODED_FILE:要儲存金鑰的檔案路徑。使用 .json 副檔名。

請務必妥善保存金鑰資料,因為此資料可當做服務帳戶進行驗證。

您可以使用服務帳戶金鑰檔案,做為服務帳戶來驗證應用程式

刪除服務帳戶金鑰

刪除服務帳戶金鑰後,您就無法再透過 Google API 使用金鑰進行驗證。

刪除的金鑰無法復原,刪除金鑰前,建議先停用金鑰,然後等待一段時間,確認不再需要該金鑰後再刪除。接著即可刪除金鑰。

最佳做法是定期輪替服務帳戶金鑰。如要進一步瞭解如何輪替服務帳戶金鑰,請參閱「服務帳戶金鑰輪替」。

控制台

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

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

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

  2. 選取專案。
  3. 在「Service Accounts」(服務帳戶) 頁面中找到您要刪除金鑰的服務帳戶,然後點選該帳戶的電子郵件地址。
  4. 按一下「Keys」(金鑰) 分頁標籤。
  5. 在金鑰清單中,針對您要刪除的每個金鑰按一下「Delete」(刪除) 按鈕。

gcloud

執行 gcloud iam service-accounts keys delete 指令,刪除服務帳戶金鑰。

替換下列值:

  • KEY_ID:要刪除的金鑰 ID。如要找出金鑰 ID,請列出服務帳戶的所有金鑰,找出要刪除的金鑰,然後複製其 ID。
  • SA_NAME:金鑰所屬服務帳戶的名稱。
  • PROJECT_ID:您的 Google Cloud 專案 ID。
gcloud iam service-accounts keys delete KEY_ID \
    --iam-account=SA_NAME@PROJECT_ID.iam.gserviceaccount.com

輸出:

Deleted key [KEY_ID] for service account
[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) {
  iam::IAMClient client(iam::MakeIAMConnection());
  auto response = client.DeleteServiceAccountKey(name);
  if (!response.ok()) throw std::runtime_error(response.message());
  std::cout << "ServiceAccountKey successfully deleted.\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 ServiceAccountKeys
{
    public static void DeleteKey(string fullKeyName)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        service.Projects.ServiceAccounts.Keys.Delete(fullKeyName).Execute();
        Console.WriteLine("Deleted key: " + fullKeyName);
    }
}

Go

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

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

import (
	"context"
	"fmt"
	"io"

	iam "google.golang.org/api/iam/v1"
)

// deleteKey deletes a service account key.
func deleteKey(w io.Writer, fullKeyName string) error {
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return fmt.Errorf("iam.NewService: %w", err)
	}

	_, err = service.Projects.ServiceAccounts.Keys.Delete(fullKeyName).Do()
	if err != nil {
		return fmt.Errorf("Projects.ServiceAccounts.Keys.Delete: %w", err)
	}
	fmt.Fprintf(w, "Deleted key: %v", fullKeyName)
	return nil
}

Java

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

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


import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.iam.admin.v1.DeleteServiceAccountKeyRequest;
import com.google.iam.admin.v1.KeyName;
import java.io.IOException;

public class DeleteServiceAccountKey {

  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 serviceAccountKeyId = "service-account-key-id";

    deleteKey(projectId, serviceAccountName, serviceAccountKeyId);
  }

  // Deletes a service account key.
  public static void deleteKey(String projectId, String accountName,
                               String serviceAccountKeyId) 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()) {

      //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#deleting

      String accountEmail = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);

      String name = KeyName.of(projectId, accountEmail, serviceAccountKeyId).toString();

      DeleteServiceAccountKeyRequest request = DeleteServiceAccountKeyRequest.newBuilder()
              .setName(name)
              .build();

      // Then you can delete the key
      iamClient.deleteServiceAccountKey(request);

      System.out.println("Deleted key: " + serviceAccountKeyId);
    }
  }
}

Python

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

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

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


def delete_key(project_id: str, account: str, key_id: str) -> None:
    """Deletes a key for a service account.

    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.
    key_id: unique ID of the key.
    """

    iam_admin_client = iam_admin_v1.IAMClient()
    request = types.DeleteServiceAccountKeyRequest()
    request.name = f"projects/{project_id}/serviceAccounts/{account}/keys/{key_id}"

    iam_admin_client.delete_service_account_key(request=request)
    print(f"Deleted key: {key_id}")

REST

projects.serviceAccounts.keys.delete 方法會刪除服務帳戶金鑰。

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

  • PROJECT_ID:您的 Google Cloud 專案 ID。專案 ID 為英數字串,例如 my-project
  • SA_NAME:要刪除金鑰的服務帳戶名稱。
  • KEY_ID:要刪除的金鑰 ID。如要找出金鑰 ID,請列出服務帳戶的所有金鑰,找出要刪除的金鑰,然後從 name 欄位結尾複製其 ID。金鑰 ID 是 keys/ 後方的所有內容。

HTTP 方法和網址:

DELETE https://iam.googleapis.com/v1/projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com/keys/KEY_ID

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

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

{
}

後續步驟

歡迎試用

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

免費試用