停用及啟用服務帳戶

本頁說明如何使用 Identity and Access Management (IAM) API、 Google Cloud 控制台和 gcloud CLI 停用及啟用服務帳戶。

事前準備

  • 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. 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. 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. 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. 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. 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 的憑證。

      Install the Google Cloud CLI.

      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」。

  • 瞭解 IAM 服務帳戶

必要的角色

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

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

如要進一步瞭解這個角色,請參閱服務帳戶角色

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

停用服務帳戶

就像刪除服務帳戶一樣,若您停用服務帳戶,應用程式就無法再透過該服務帳戶存取 Google Cloud 資源。如果您停用了預設的 App Engine 和 Compute Engine 服務帳戶,執行個體將無法再存取專案中的資源。若您嘗試停用已經停用的服務帳戶,將不會產生任何作用。

與刪除服務帳戶不同的地方,就是停用的服務帳戶可於必要時輕鬆重新啟用。我們建議您在刪除服務帳戶之前先將其停用,確認沒有重要應用程式使用該服務帳戶。

控制台

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

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

  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 disable 指令,停用服務帳戶。

    指令:

    gcloud iam service-accounts disable SA_NAME@PROJECT_ID.iam.gserviceaccount.com

    輸出:

    Disabled 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());
  google::iam::admin::v1::DisableServiceAccountRequest request;
  request.set_name(name);
  auto response = client.DisableServiceAccount(request);
  if (!response.ok()) throw std::runtime_error(response.message());
  std::cout << "ServiceAccount successfully disabled.\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 void DisableServiceAccount(string email)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new DisableServiceAccountRequest();

        string resource = "projects/-/serviceAccounts/" + email;
        service.Projects.ServiceAccounts.Disable(request, resource).Execute();
        Console.WriteLine("Disabled service account: " + email);
    }
}

Go

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

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

import (
	"context"
	"fmt"
	"io"

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

// disableServiceAccount disables a service account.
func disableServiceAccount(w io.Writer, email string) error {
	// email:= service-account@your-project.iam.gserviceaccount.com
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return fmt.Errorf("iam.NewService: %w", err)
	}

	request := &iam.DisableServiceAccountRequest{}
	_, err = service.Projects.ServiceAccounts.Disable("projects/-/serviceAccounts/"+email, request).Do()
	if err != nil {
		return fmt.Errorf("Projects.ServiceAccounts.Disable: %w", err)
	}
	fmt.Fprintf(w, "Disabled 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.DisableServiceAccountRequest;
import java.io.IOException;

public class DisableServiceAccount {

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

    disableServiceAccount(projectId, serviceAccountName);
  }

  // Disables a service account.
  public static void disableServiceAccount(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()) {
      iamClient.disableServiceAccount(DisableServiceAccountRequest.newBuilder()
              .setName(String.format("projects/%s/serviceAccounts/%s", projectId, email))
              .build());

      System.out.println("Disabled service account: " + accountName);
    }
  }
}

Python

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

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

import time

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


def disable_service_account(project_id: str, account: str) -> types.ServiceAccount:
    """Disables 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.DisableServiceAccountRequest()
    name = f"projects/{project_id}/serviceAccounts/{account}"
    request.name = name

    iam_admin_client.disable_service_account(request=request)
    time.sleep(5)  # waiting to make sure changes applied

    get_request = types.GetServiceAccountRequest()
    get_request.name = name

    service_account = iam_admin_client.get_service_account(request=get_request)
    if service_account.disabled:
        print(f"Disabled service account: {account}")
    return service_account

REST

serviceAccounts.disable 方法會立即停用服務帳戶。

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

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

HTTP 方法和網址:

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

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

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

啟用服務帳戶

啟用已停用的服務帳戶後,應用程式將能再次透過該服務帳戶存取Google Cloud 資源。

您可於需要時隨時啟用已停用的服務帳戶。若您嘗試啟用已經啟用的服務帳戶,將不會產生任何作用。

控制台

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

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

  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 enable 指令以啟用服務帳戶。

    指令:

    gcloud iam service-accounts enable SA_NAME@PROJECT_ID.iam.gserviceaccount.com

    輸出:

    Enabled 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());
  google::iam::admin::v1::EnableServiceAccountRequest request;
  request.set_name(name);
  auto response = client.EnableServiceAccount(request);
  if (!response.ok()) throw std::runtime_error(response.message());
  std::cout << "ServiceAccount successfully enabled.\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 void EnableServiceAccount(string email)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(IamService.Scope.CloudPlatform);
        var service = new IamService(new IamService.Initializer
        {
            HttpClientInitializer = credential
        });

        var request = new EnableServiceAccountRequest();

        string resource = "projects/-/serviceAccounts/" + email;
        service.Projects.ServiceAccounts.Enable(request, resource).Execute();
        Console.WriteLine("Enabled service account: " + email);
    }
}

Go

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

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

import (
	"context"
	"fmt"
	"io"

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

// enableServiceAccount enables a service account.
func enableServiceAccount(w io.Writer, email string) error {
	// email:= service-account@your-project.iam.gserviceaccount.com
	ctx := context.Background()
	service, err := iam.NewService(ctx)
	if err != nil {
		return fmt.Errorf("iam.NewService: %w", err)
	}

	request := &iam.EnableServiceAccountRequest{}
	_, err = service.Projects.ServiceAccounts.Enable("projects/-/serviceAccounts/"+email, request).Do()
	if err != nil {
		return fmt.Errorf("Projects.ServiceAccounts.Enable: %w", err)
	}
	fmt.Fprintf(w, "Enabled 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.EnableServiceAccountRequest;
import java.io.IOException;


public class EnableServiceAccount {

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

    enableServiceAccount(projectId, serviceAccountName);
  }

  // Enables a service account.
  public static void enableServiceAccount(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()) {
      iamClient.enableServiceAccount(EnableServiceAccountRequest.newBuilder()
              .setName(String.format("projects/%s/serviceAccounts/%s", projectId, email))
              .build());

      System.out.println("Enabled service account: " + email);
    }
  }
}

Python

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

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

import time

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


def enable_service_account(project_id: str, account: str) -> types.ServiceAccount:
    """Enables 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.EnableServiceAccountRequest()
    name = f"projects/{project_id}/serviceAccounts/{account}"
    request.name = name

    iam_admin_client.enable_service_account(request=request)
    time.sleep(5)  # waiting to make sure changes applied

    get_request = types.GetServiceAccountRequest()
    get_request.name = name

    service_account = iam_admin_client.get_service_account(request=get_request)
    if not service_account.disabled:
        print(f"Enabled service account: {account}")
    return service_account

REST

serviceAccounts.enable 方法可啟用先前停用的服務帳戶。

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

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

HTTP 方法和網址:

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

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

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

後續步驟

歡迎試用

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

免費試用