刪除及取消刪除服務帳戶

本頁說明如何使用 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#

      如要在本機開發環境中使用本頁的 .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 服務帳戶

必要的角色

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

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

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

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

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

刪除服務帳戶

刪除服務帳戶後,應用程式就無法再透過該服務帳戶存取Google Cloud 資源。如果您刪除了預設的 App Engine 和 Compute Engine 服務帳戶,使用這些服務帳戶的 App Engine 應用程式和 Compute Engine VM 執行個體,將無法再存取專案中的資源。

請謹慎刪除服務帳戶。請先確認重要的應用程式不再需要使用服務帳戶,然後再將其刪除。如果您不確定是否會使用服務帳戶,Google 建議您停用服務帳戶,而不是刪除。停用的服務帳戶如果仍要使用,可重新啟用。

如要還原已刪除的服務帳戶,請在刪除服務帳戶後的 30 天內取消刪除。30 天後,IAM 會永久移除服務帳戶。 Google Cloud服務帳戶永久移除後就無法復原,即使提出支援要求也一樣。

如要進一步降低刪除必要服務帳戶的風險,您也可以啟用變更風險建議。當您嘗試刪除 Google Cloud 判定為重要的服務帳戶時,系統會根據風險建議產生警告。

如果您刪除服務帳戶,然後建立具有相同名稱的新服務帳戶,系統會將新服務帳戶視為個別身分,不會沿用已刪除服務帳戶的角色。反之,如果刪除服務帳戶後又取消刪除,服務帳戶的身分不會變更,且會保留角色。

刪除服務帳戶後,並不會立即移除其角色繫結;角色繫結最多於 60 天後將自動從系統中清除。在此之前,服務帳戶會顯示在角色繫結中,並加上 deleted: 前置字元和 ?uid=NUMERIC_ID 後置字元,其中 NUMERIC_ID 是服務帳戶的專屬數字 ID。

已刪除的服務帳戶不會計入服務帳戶配額

控制台

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

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

  2. 選取專案。

  3. 選取要刪除的服務帳戶,然後按一下「刪除」圖示

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 delete 指令,刪除服務帳戶。

    指令:

    gcloud iam service-accounts delete \
        SA_NAME@PROJECT_ID.iam.gserviceaccount.com

    輸出:

    Deleted 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.DeleteServiceAccount(name);
  if (!response.ok()) throw std::runtime_error(response.message());
  std::cout << "ServiceAccount successfully deleted.\n";
}

C#

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

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


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

public partial class ServiceAccounts
{
    public static void DeleteServiceAccount(string email)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        string resource = "projects/-/serviceAccounts/" + email;
        service.Projects.ServiceAccounts.Delete(resource).Execute();
        Console.WriteLine("Deleted service account: " + email);
    }
}

Go

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

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

import (
	"context"
	"fmt"
	"io"

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

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

	_, err = service.Projects.ServiceAccounts.Delete("projects/-/serviceAccounts/" + email).Do()
	if err != nil {
		return fmt.Errorf("Projects.ServiceAccounts.Delete: %w", err)
	}
	fmt.Fprintf(w, "Deleted service account: %v", email)
	return nil
}

Java

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

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

import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.iam.admin.v1.DeleteServiceAccountRequest;
import com.google.iam.admin.v1.ServiceAccountName;
import java.io.IOException;

public class DeleteServiceAccount {

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

    deleteServiceAccount(projectId, serviceAccountName);
  }

  // Deletes a service account.
  public static void deleteServiceAccount(String projectId, String serviceAccountName)
          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 client = IAMClient.create()) {
      String accountName = ServiceAccountName.of(projectId, serviceAccountName).toString();
      String accountEmail = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);
      DeleteServiceAccountRequest request = DeleteServiceAccountRequest.newBuilder()
              .setName(accountEmail)
              .build();
      client.deleteServiceAccount(request);

      System.out.println("Deleted service account: " + serviceAccountName);
    }
  }
}

Python

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

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

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


def delete_service_account(project_id: str, account: str) -> None:
    """Deletes 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.DeleteServiceAccountRequest()
    request.name = f"projects/{project_id}/serviceAccounts/{account}"

    iam_admin_client.delete_service_account(request=request)
    print(f"Deleted a service account: {account}")

REST

serviceAccounts.delete 方法會刪除服務帳戶。

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

  • PROJECT_ID:您的 Google Cloud 專案 ID。專案 ID 為英數字串,例如 my-project
  • SA_ID:服務帳戶的 ID。 這可以是 SA_NAME@PROJECT_ID.iam.gserviceaccount.com 形式的服務帳戶電子郵件地址,也可以是服務帳戶的不重複數字 ID。

HTTP 方法和網址:

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

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

如果成功,回應主體會留白。

取消刪除服務帳戶

在某些情況下,您可以使用 undelete 指令取消刪除服務帳戶。如果已刪除的服務帳戶符合下列條件,通常可以還原:

  • 服務帳戶在 30 天前遭到刪除。

    30 天後,IAM 會永久移除服務帳戶。 Google Cloud 服務帳戶永久移除後,即使提出支援要求也無法復原。

  • 沒有與已刪除服務帳戶同名的現有服務帳戶。

    舉例來說,假設您不慎刪除了服務帳戶 my-service-account@project-id.iam.gserviceaccount.com。您仍需要具有該名稱的服務帳戶,因此請建立同名的新服務帳戶 my-service-account@project-id.iam.gserviceaccount.com

    新服務帳戶不會沿用已刪除服務帳戶的權限。因此與已刪除的服務帳戶完全無關。不過,您無法取消刪除原始服務帳戶,因為新服務帳戶的名稱相同。

    如要解決這個問題,請刪除新的服務帳戶,然後嘗試取消刪除原始服務帳戶。

如果無法取消刪除服務帳戶,您可以建立同名的新服務帳戶,撤銷已刪除服務帳戶的所有角色,然後將相同角色授予新服務帳戶。詳情請參閱「已刪除主體的政策」。

找出已刪除服務帳戶的數字 ID

取消刪除服務帳戶時,您必須提供該帳戶的數字 ID。數字 ID 是 21 位數,例如 123456789012345678901,可做為服務帳戶的專屬 ID。舉例來說,如果您刪除服務帳戶,然後建立同名的新服務帳戶,原始服務帳戶和新服務帳戶的數字 ID 會不同。

如果您知道允許政策中的繫結包含已刪除的服務帳戶,可以取得允許政策,然後在允許政策中找出數字 ID。系統會在已刪除服務帳戶的名稱後方附加數字 ID。舉例來說,在下列允許政策中,已刪除服務帳戶的數字 ID 為 123456789012345678901

{
  "version": 1,
  "etag": "BwUjMhCsNvY=",
  "bindings": [
    {
      "members": [
        "deleted:serviceAccount:my-service-account@project-id.iam.gserviceaccount.com?uid=123456789012345678901"
      ],
      "role": "roles/iam.serviceAccountUser"
    },
  ]
}

系統只會將數字 ID 附加至已刪除主體的名稱。

或者,您也可以在稽核記錄中搜尋刪除服務帳戶的DeleteServiceAccount作業:

  1. 前往 Google Cloud 控制台的「Logs Explorer」頁面。

    前往「Logs explorer」(記錄檔探索工具)

  2. 在查詢編輯器中輸入下列查詢,並將 SERVICE_ACCOUNT_EMAIL 替換為服務帳戶的電子郵件地址 (例如 my-service-account@project-id.iam.gserviceaccount.com):

    resource.type="service_account"
    resource.labels.email_id="SERVICE_ACCOUNT_EMAIL"
    "DeleteServiceAccount"
    
  3. 如果服務帳戶是在超過一小時前刪除,請按一下「過去 1 小時」schedule,從下拉式清單中選取較長的時間範圍,然後按一下「套用」

  4. 按一下 [Run query] (執行查詢)。記錄檔總管會顯示影響服務帳戶的操作,這些帳戶的名稱與您指定的名稱相符。DeleteServiceAccount

  5. 請採取下列任一做法,找出並記下已刪除服務帳戶的數字 ID:

    • 如果搜尋結果只包含一項 DeleteServiceAccount 作業,請在「記錄欄位」窗格的「不重複 ID」欄位中找出數字 ID。

    • 如果搜尋結果顯示多個記錄,請按照下列步驟操作:

      1. 找出正確的記錄項目。如要找出正確的記錄項目,請按一下記錄項目旁的展開箭頭。查看記錄項目的詳細資料,判斷記錄項目是否顯示要復原的作業。重複這個程序,直到找到正確的記錄項目為止。

      2. 在正確的記錄檔項目中,找出服務帳戶的數字 ID。如要找出數字 ID,請展開記錄項目的 protoPayload 欄位,然後找到 resourceName 欄位。

      數字 ID 是「resourceName」欄位中「serviceAccounts」後方的所有內容。

使用數字 ID 取消刪除服務帳戶

找到已刪除服務帳戶的數字 ID 後,您可以嘗試取消刪除服務帳戶。

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 beta iam service-accounts undelete 指令,取消刪除服務帳戶。

    指令:

    gcloud beta iam service-accounts undelete ACCOUNT_ID

    輸出:

    restoredAccount:
        email: SA_NAME@PROJECT_ID.iam.gserviceaccount.com
        etag: BwWWE7zpApg=
        name: projects/PROJECT_ID/serviceAccounts/SA_NAME@PROJECT_ID.iam.gserviceaccount.com
        oauth2ClientId: '123456789012345678901'
        projectId: PROJECT_ID
        uniqueId: 'ACCOUNT_ID'

REST

serviceAccounts.undelete 方法會還原已刪除的服務帳戶。

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

  • PROJECT_ID:您的 Google Cloud 專案 ID。專案 ID 為英數字串,例如 my-project
  • SA_NUMERIC_ID:服務帳戶的專屬數值 ID。

HTTP 方法和網址:

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

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

如果可以取消刪除帳戶,您會收到 200 OK 回應碼,以及已還原服務帳戶的詳細資料,如下所示:

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

後續步驟

歡迎試用

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

免費試用