管理專案、資料夾和組織的存取權

本頁說明如何授予、變更及撤銷專案、資料夾和機構的存取權。授予專案、資料夾和機構的存取權時,您也會授予其中資源的存取權。

如要瞭解如何管理其他資源的存取權,請參閱下列指南:

在 Identity and Access Management (IAM) 中,存取權是透過允許政策 (也稱為 IAM 政策) 授予。允許政策會附加至Google Cloud 資源。每項允許政策都包含一組角色繫結,可將一或多個主體 (例如使用者或服務帳戶) 與 IAM 角色建立關聯。這些角色繫結會將指定角色授予主體,包括附加允許政策的資源,以及該資源的所有子系。如要進一步瞭解允許政策,請參閱瞭解允許政策

您可以透過Google Cloud 控制台、Google Cloud CLI、REST API 或 Resource Manager 用戶端程式庫,管理專案、資料夾和機構的存取權。

事前準備

  • Enable the Resource Manager 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」。

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

必要 IAM 角色

建立專案、資料夾或機構時,系統會自動授予您可管理該資源存取權的角色。詳情請參閱預設政策

如果您不是專案、資料夾或機構的建立者,請確認您具備管理該資源存取權的角色。

如要取得管理專案、資料夾或機構存取權所需的權限,請要求管理員在您要管理存取權的資源 (專案、資料夾或機構) 上,授予下列 IAM 角色:

  • 如要管理專案存取權: 專案 IAM 管理員 (roles/resourcemanager.projectIamAdmin)
  • 如要管理資料夾的存取權: 資料夾管理員 (roles/resourcemanager.folderAdmin)
  • 如要管理專案、資料夾和機構的存取權: 機構管理員 (roles/resourcemanager.organizationAdmin)
  • 如要管理幾乎所有 Google Cloud 資源的存取權: 安全管理員 (roles/iam.securityAdmin)

這些預先定義的角色具備管理專案、資料夾或機構存取權所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要管理專案、資料夾或機構的存取權,您必須具備下列權限:

  • 如要管理專案存取權,請按照下列步驟操作:
    • resourcemanager.projects.getIamPolicy
    • resourcemanager.projects.setIamPolicy
  • 如何管理資料夾的存取權:
    • resourcemanager.folders.getIamPolicy
    • resourcemanager.folders.setIamPolicy
  • 如何管理機構的存取權:
    • resourcemanager.organizations.getIamPolicy
    • resourcemanager.organizations.setIamPolicy

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

查看目前的存取權

您可以使用 Google Cloud 控制台、gcloud CLI、REST API 或 Resource Manager 用戶端程式庫,查看哪些人有權存取專案、資料夾或機構。

控制台

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

    前往 IAM

  2. 選取專案、資料夾或機構。

    Google Cloud 主控台會列出所有已獲授專案、資料夾或機構角色的主體。這份清單包含從父項資源繼承資源角色的主體。如要進一步瞭解政策沿用機制,請參閱「政策沿用機制和資源階層」一文。

  3. 選用:如要查看服務代理程式的角色授予項目,請選取「包含 Google 提供的角色授予項目」 Google核取方塊

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. 如要查看哪些人有權存取專案、資料夾或機構,請取得資源的允許政策。如要瞭解如何解讀允許政策,請參閱瞭解允許政策

    如要取得資源的允許政策,請為該資源執行 get-iam-policy 指令:

    gcloud RESOURCE_TYPE get-iam-policy RESOURCE_ID --format=FORMAT > PATH

    提供以下這些值:

    • RESOURCE_TYPE:您要查看存取權的資源類型。請使用下列其中一個值:projectsresource-manager foldersorganizations

    • RESOURCE_ID:您的 Google Cloud 專案、資料夾或機構 ID。專案 ID 為英數字元,例如 my-project。資料夾和機構 ID 是數字,例如 123456789012

    • FORMAT:政策的所需格式。使用 jsonyaml

    • PATH:政策的新輸出檔案路徑。

    舉例來說,以下指令會取得專案 my-project 的政策,並以 JSON 格式儲存至您的主目錄:

    gcloud projects get-iam-policy my-project --format=json > ~/policy.json

C#

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

如要查看哪些人有權存取專案、資料夾或機構,請取得資源的允許政策。如要瞭解如何解讀允許政策,請參閱瞭解允許政策

以下範例說明如何取得專案的允許政策。如要瞭解如何取得資料夾或機構的允許政策,請參閱您所用程式設計語言的Resource Manager 用戶端程式庫文件


using Google.Apis.Auth.OAuth2;
using Google.Apis.CloudResourceManager.v1;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy GetPolicy(string projectId)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);
        var service = new CloudResourceManagerService(
            new CloudResourceManagerService.Initializer
            {
                HttpClientInitializer = credential
            });

        var policy = service.Projects.GetIamPolicy(new GetIamPolicyRequest(),
            projectId).Execute();
        return policy;
    }
}

Java

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

如要查看哪些人有權存取專案、資料夾或機構,請取得資源的允許政策。如要瞭解如何解讀允許政策,請參閱瞭解允許政策

以下範例說明如何取得專案的允許政策。如要瞭解如何取得資料夾或機構的允許政策,請參閱您所用程式設計語言的Resource Manager 用戶端程式庫文件

import com.google.cloud.resourcemanager.v3.ProjectsClient;
import com.google.iam.admin.v1.ProjectName;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import java.io.IOException;

public class GetProjectPolicy {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    // TODO: Replace with your project ID.
    String projectId = "your-project-id";

    getProjectPolicy(projectId);
  }

  // Gets a project's policy.
  public static Policy getProjectPolicy(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 (ProjectsClient projectsClient = ProjectsClient.create()) {
      GetIamPolicyRequest request = GetIamPolicyRequest.newBuilder()
              .setResource(ProjectName.of(projectId).toString())
              .build();
      return projectsClient.getIamPolicy(request);
    }
  }
}

Python

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

如要查看哪些人有權存取專案、資料夾或機構,請取得資源的允許政策。如要瞭解如何解讀允許政策,請參閱瞭解允許政策

以下範例說明如何取得專案的允許政策。如要瞭解如何取得資料夾或機構的允許政策,請參閱您所用程式設計語言的Resource Manager 用戶端程式庫文件

from google.cloud import resourcemanager_v3
from google.iam.v1 import iam_policy_pb2, policy_pb2


def get_project_policy(project_id: str) -> policy_pb2.Policy:
    """Get policy for project.

    project_id: ID or number of the Google Cloud project you want to use.
    """

    client = resourcemanager_v3.ProjectsClient()
    request = iam_policy_pb2.GetIamPolicyRequest()
    request.resource = f"projects/{project_id}"

    policy = client.get_iam_policy(request)
    print(f"Policy retrieved: {policy}")

    return policy

REST

如要查看哪些人有權存取專案、資料夾或機構,請取得資源的允許政策。如要瞭解如何解讀允許政策,請參閱瞭解允許政策

Resource Manager API 的 getIamPolicy 方法會取得專案、資料夾或機構的允許政策。

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

  • API_VERSION:要使用的 API 版本。如果是專案和機構,請使用 v1。如果是資料夾,請使用 v2
  • RESOURCE_TYPE:您要管理的政策所屬資源類型。請使用 projectsfoldersorganizations 值。
  • RESOURCE_ID:您的 Google Cloud專案、機構或資料夾 ID。專案 ID 為英數字串,例如 my-project。資料夾和機構 ID 為數字,例如 123456789012
  • POLICY_VERSION:要傳回的政策版本。要求應指定最新政策版本,即政策版本 3。詳情請參閱在取得政策時指定政策版本

HTTP 方法和網址:

POST https://cloudresourcemanager.googleapis.com/API_VERSION/RESOURCE_TYPE/RESOURCE_ID:getIamPolicy

JSON 要求主體:

{
  "options": {
    "requestedPolicyVersion": POLICY_VERSION
  }
}

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

回覆會包含資源的允許政策。例如:

{
  "version": 1,
  "etag": "BwWKmjvelug=",
  "bindings": [
    {
      "role": "roles/owner",
      "members": [
        "user:my-user@example.com"
      ]
    }
  ]
}

授予或撤銷單一身分與存取權管理角色

您可以使用 Google Cloud 主控台和 gcloud CLI,對單一主體快速授予或撤銷單一角色,而不直接編輯資源的允許政策。 常見的主體類型包括 Google 帳戶、服務帳戶、Google 群組和網域。如需所有主體類型清單,請參閱「主體類型」。

一般而言,政策變更會在 2 分鐘內生效,但在某些情況下,可能需要 7 分鐘以上,系統才會全面套用變更。

如需協助找出最合適的預先定義角色,請參閱「尋找合適的預先定義角色」。

授予單一 IAM 角色

如要將單一角色授予主體,請執行下列操作:

控制台

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

    前往 IAM

  2. 選取專案、資料夾或機構。

  3. 選取要授予角色的主體:

    • 如要將角色授予資源上已有其他角色的主體,請找出包含該主體的列,然後點選該列中的 「Edit principal」(編輯主體),並按一下 「Add another role」(新增其他角色)

      如要將角色授予服務代理,請選取「包含Google提供的角色授權」核取方塊,查看服務代理的電子郵件地址。

    • 如要將角色授予資源上沒有任何角色的主體,請按一下 「授予存取權」,然後輸入主體 ID,例如 my-user@example.com//iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com

  4. 從下拉式清單中選取要授予的角色。為遵循安全性最佳做法,請選擇僅含主體所需權限的角色。

  5. 選用:為角色新增條件

  6. 按一下 [儲存]。主體就會取得指定資源的角色。

如要為多個專案、資料夾或機構的主體授予角色,請按照下列步驟操作:

  1. 前往 Google Cloud 控制台的「管理資源」頁面。

    前往「管理資源」

  2. 選取要授予權限的所有資源。

  3. 如果畫面上未顯示資訊面板,請按一下「Show info panel」(顯示資訊面板)。然後按一下「權限」

  4. 選取要授予角色的主體:

    • 如要將角色授予已有其他角色的主體,請找出包含該主體的列,然後點選該列中的 「Edit principal」(編輯主體),並按一下 「Add another role」(新增其他角色)
    • 如要將角色授予還沒有其他角色的主體,請按一下 「Add principal」(新增主體),然後輸入主體 ID,例如 my-user@example.com//iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com
  5. 從下拉式清單中選取要授予的角色。

  6. 選用:為角色新增條件

  7. 按一下 [儲存]。主體會取得所選資源的選定角色。

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. add-iam-policy-binding 指令可讓您快速將角色授予主體。

    使用下方的任何指令資料之前,請先替換以下項目:

    • RESOURCE_TYPE:您要管理存取權的資源類型。請使用 projectsresource-manager foldersorganizations

    • RESOURCE_ID:您的 Google Cloud 專案、資料夾或機構 ID。專案 ID 為英數字元,例如 my-project。 資料夾和機構 ID 是數字,例如 123456789012

    • PRINCIPAL:主體或成員的 ID,通常採用以下格式: PRINCIPAL_TYPE:ID。 例如 user:my-user@example.comprincipalSet://iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com。如需 PRINCIPAL 可用的完整值清單,請參閱「主體 ID」。

      如果是 user 主體類型,ID 中的網域名稱必須是 Google Workspace 網域或 Cloud Identity 網域。如要瞭解如何設定 Cloud Identity 網域,請參閱 Cloud Identity 總覽

    • ROLE_NAME:要撤銷的角色名稱。請使用下列其中一種格式:

      • 預先定義的角色:roles/SERVICE.IDENTIFIER
      • 專案層級自訂角色:projects/PROJECT_ID/roles/IDENTIFIER
      • 機構層級的自訂角色:organizations/ORG_ID/roles/IDENTIFIER

      如需預先定義角色清單,請參閱「瞭解角色」一文。

    • CONDITION:要新增至角色繫結的條件。如不想新增條件,請使用 None 值。如要進一步瞭解條件,請參閱條件總覽

    執行下列指令:

    Linux、macOS 或 Cloud Shell

    gcloud RESOURCE_TYPE add-iam-policy-binding RESOURCE_ID \
        --member=PRINCIPAL --role=ROLE_NAME \
        --condition=CONDITION

    Windows (PowerShell)

    gcloud RESOURCE_TYPE add-iam-policy-binding RESOURCE_ID `
        --member=PRINCIPAL --role=ROLE_NAME `
        --condition=CONDITION

    Windows (cmd.exe)

    gcloud RESOURCE_TYPE add-iam-policy-binding RESOURCE_ID ^
        --member=PRINCIPAL --role=ROLE_NAME ^
        --condition=CONDITION

    回應會包含更新後的 IAM 政策。

撤銷單一身分與存取權管理角色

如要撤銷主體的單一角色,請執行下列步驟:

控制台

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

    前往「IAM」頁面

  2. 選取專案、資料夾或機構。

  3. 找到包含要撤銷存取權主體的資料列。然後點選該列中的「Edit principal」(編輯主體) 圖示

  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. 如要快速撤銷使用者的某個角色,請執行 remove-iam-policy-binding 指令:

    gcloud RESOURCE_TYPE remove-iam-policy-binding RESOURCE_ID 
    --member=PRINCIPAL --role=ROLE_NAME

    提供以下這些值:

    • RESOURCE_TYPE:您要管理存取權的資源類型。請使用 projectsresource-manager foldersorganizations

    • RESOURCE_ID:您的 Google Cloud 專案、資料夾或機構 ID。專案 ID 為英數字元,例如 my-project。 資料夾和機構 ID 是數字,例如 123456789012

    • PRINCIPAL:主體或成員的 ID,通常採用以下格式: PRINCIPAL_TYPE:ID。 例如 user:my-user@example.comprincipalSet://iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com

      如果是 user 主體類型,ID 中的網域名稱必須是 Google Workspace 網域或 Cloud Identity 網域。如要瞭解如何設定 Cloud Identity 網域,請參閱 Cloud Identity 總覽

    • ROLE_NAME:要撤銷的角色名稱。請使用下列其中一種格式:

      • 預先定義的角色:roles/SERVICE.IDENTIFIER
      • 專案層級自訂角色:projects/PROJECT_ID/roles/IDENTIFIER
      • 機構層級的自訂角色:organizations/ORG_ID/roles/IDENTIFIER

      如需預先定義角色清單,請參閱「瞭解角色」一文。

    舉例來說,如要撤銷專案 example-project 服務帳戶 example-service-account@example-project.iam.gserviceaccount.com 的專案建立者角色:

    gcloud projects remove-iam-policy-binding example-project 
    --member=serviceAccount:example-service-account@example-project.iam.gserviceaccount.com
    --role=roles/resourcemanager.projectCreator

為確保您不會撤銷任何必要角色,可以啟用變更風險建議。當您嘗試撤銷系統Google Cloud 判定為重要的專案層級角色時,變更風險建議會產生警告。

使用 Google Cloud 控制台授予或撤銷多個 IAM 角色

您可以使用 Google Cloud 控制台,為單一主體授予及撤銷多個角色:

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

    前往「IAM」頁面

  2. 選取專案、資料夾或機構。

  3. 選取要修改角色的主體:

    • 如要修改主體在資源上的角色,請找出含有該主體的列,點選該列中的 「Edit principal」(編輯主體),然後按一下 「Add another role」(新增其他角色)

      如要修改服務代理人的角色,請選取「Include Google-provided role grants」(包括 Google 提供的角色授權) Google 核取方塊,查看服務代理人的電子郵件地址。

    • 如要將角色授予資源上沒有任何角色的主體,請按一下 「授予存取權」,然後輸入主體 ID,例如 my-user@example.com//iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com

  4. 修改主體的角色:

    • 如要將角色授予還沒有任何資源角色的主體,請按一下「Select a role」(選取角色),然後從下拉式清單中選取要授予的角色。
    • 如要將其他角色授予主體,請按一下「新增其他角色」,然後從下拉式清單中選取要授予的角色。
    • 如要以其他角色取代主體的其中一個角色,請按一下現有角色,然後從下拉式清單中選擇要授予的角色。
    • 如要撤銷主體的其中一個角色,請針對要撤銷的每個角色按一下「刪除」 按鈕。

    您也可以為角色新增條件修改角色的條件,或移除角色的條件

  5. 按一下 [儲存]

以程式輔助方式授予或撤銷多個 IAM 角色

如要進行大規模存取權變更,包括授予及撤銷多個主體的多個角色,請使用「讀取 - 修改 - 寫入」模式更新資源的允許政策:

  1. 呼叫 getIamPolicy() 讀取目前的允許政策。
  2. 使用文字編輯器或透過程式來編輯允許政策,藉此新增或移除任何主體或角色繫結。
  3. 呼叫 setIamPolicy() 寫入更新後的允許政策。

您可以使用 gcloud CLI、REST API 或 Resource Manager 用戶端程式庫更新允許政策。

一般而言,政策變更會在 2 分鐘內生效,但在某些情況下,可能需要 7 分鐘以上,系統才會全面套用變更。

取得目前的允許政策

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. 如要取得資源的允許政策,請為該資源執行 get-iam-policy 指令:

    gcloud RESOURCE_TYPE get-iam-policy RESOURCE_ID --format=FORMAT > PATH

    提供以下這些值:

    • RESOURCE_TYPE:您要取得允許政策的資源類型。請使用下列其中一個值:projectsresource-manager foldersorganizations

    • RESOURCE_ID:您的 Google Cloud 專案、資料夾或機構 ID。專案 ID 為英數字元,例如 my-project。資料夾和機構 ID 是數字,例如 123456789012

    • FORMAT:允許政策的所需格式。使用 jsonyaml

    • PATH:允許政策的新輸出檔案路徑。

    舉例來說,以下指令會取得專案 my-project 的允許政策,並以 JSON 格式儲存至主目錄:

    gcloud projects get-iam-policy my-project --format json > ~/policy.json

C#

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

以下範例說明如何取得專案的允許政策。如要瞭解如何取得資料夾或機構的允許政策,請參閱程式設計語言的Resource Manager 用戶端程式庫說明文件


using Google.Apis.Auth.OAuth2;
using Google.Apis.CloudResourceManager.v1;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy GetPolicy(string projectId)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);
        var service = new CloudResourceManagerService(
            new CloudResourceManagerService.Initializer
            {
                HttpClientInitializer = credential
            });

        var policy = service.Projects.GetIamPolicy(new GetIamPolicyRequest(),
            projectId).Execute();
        return policy;
    }
}

Java

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

以下範例說明如何取得專案的允許政策。如要瞭解如何取得資料夾或機構的允許政策,請參閱程式設計語言的Resource Manager 用戶端程式庫說明文件

import com.google.cloud.resourcemanager.v3.ProjectsClient;
import com.google.iam.admin.v1.ProjectName;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import java.io.IOException;

public class GetProjectPolicy {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    // TODO: Replace with your project ID.
    String projectId = "your-project-id";

    getProjectPolicy(projectId);
  }

  // Gets a project's policy.
  public static Policy getProjectPolicy(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 (ProjectsClient projectsClient = ProjectsClient.create()) {
      GetIamPolicyRequest request = GetIamPolicyRequest.newBuilder()
              .setResource(ProjectName.of(projectId).toString())
              .build();
      return projectsClient.getIamPolicy(request);
    }
  }
}

Python

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

以下範例說明如何取得專案的允許政策。如要瞭解如何取得資料夾或機構的允許政策,請參閱程式設計語言的Resource Manager 用戶端程式庫說明文件

from google.cloud import resourcemanager_v3
from google.iam.v1 import iam_policy_pb2, policy_pb2


def get_project_policy(project_id: str) -> policy_pb2.Policy:
    """Get policy for project.

    project_id: ID or number of the Google Cloud project you want to use.
    """

    client = resourcemanager_v3.ProjectsClient()
    request = iam_policy_pb2.GetIamPolicyRequest()
    request.resource = f"projects/{project_id}"

    policy = client.get_iam_policy(request)
    print(f"Policy retrieved: {policy}")

    return policy

REST

Resource Manager API 的 getIamPolicy 方法會取得專案、資料夾或機構的允許政策。

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

  • API_VERSION:要使用的 API 版本。如果是專案和機構,請使用 v1。如果是資料夾,請使用 v2
  • RESOURCE_TYPE:您要管理的政策所屬資源類型。請使用 projectsfoldersorganizations 值。
  • RESOURCE_ID:您的 Google Cloud專案、機構或資料夾 ID。專案 ID 為英數字串,例如 my-project。資料夾和機構 ID 為數字,例如 123456789012
  • POLICY_VERSION:要傳回的政策版本。要求應指定最新政策版本,即政策版本 3。詳情請參閱在取得政策時指定政策版本

HTTP 方法和網址:

POST https://cloudresourcemanager.googleapis.com/API_VERSION/RESOURCE_TYPE/RESOURCE_ID:getIamPolicy

JSON 要求主體:

{
  "options": {
    "requestedPolicyVersion": POLICY_VERSION
  }
}

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

回覆會包含資源的允許政策。例如:

{
  "version": 1,
  "etag": "BwWKmjvelug=",
  "bindings": [
    {
      "role": "roles/owner",
      "members": [
        "user:my-user@example.com"
      ]
    }
  ]
}

將回應儲存為適當類型的檔案 (jsonyaml)。

修改允許政策

透過程式或使用文字編輯器修改資源允許政策的本機副本,以反映您要授予或撤銷的角色。

為避免覆寫其他變更,請勿編輯或移除允許政策的 etag 欄位。etag 欄位會指出允許政策的目前狀態。當您設定更新後的允許政策時,IAM 會比較要求中的 etag 值與現有的 etag,並且只會在兩個值相符時才寫入允許政策。

如要編輯允許政策授予的角色,請編輯允許政策中的角色繫結。角色繫結的格式如下:

{
  "role": "ROLE_NAME",
  "members": [
    "PRINCIPAL_1",
    "PRINCIPAL_2",
    ...
    "PRINCIPAL_N"
  ],
  "conditions:" {
    CONDITIONS
  }
}

預留位置的值如下:

  • ROLE_NAME:要授予的角色名稱。請使用下列其中一種格式:

    • 預先定義的角色:roles/SERVICE.IDENTIFIER
    • 專案層級自訂角色:projects/PROJECT_ID/roles/IDENTIFIER
    • 機構層級的自訂角色:organizations/ORG_ID/roles/IDENTIFIER

    如需預先定義角色清單,請參閱「瞭解角色」。

  • PRINCIPAL_1PRINCIPAL_2...PRINCIPAL_N:要授予角色的主體 ID。

    主體 ID 通常採用以下格式: PRINCIPAL-TYPE:ID。 例如 user:my-user@example.comprincipalSet://iam.googleapis.com/locations/global/workforcePools/example-pool/group/example-group@example.com。如需 PRINCIPAL 可用的完整值清單,請參閱「主體 ID」。

    對於主體類型 user,識別碼中的網域名稱必須是 Google Workspace 網域或 Cloud Identity 網域。如要瞭解如何設定 Cloud Identity 網域,請參閱 Cloud Identity 總覽

  • CONDITIONS:選用。指定授予存取權時機的條件

授予 IAM 角色

如要將角色授予主體,請修改允許政策中的角色繫結。 如要瞭解可授予的角色,請參閱「瞭解角色」一文,或查看資源可授予的角色。如需協助找出最合適的預先定義角色,請參閱「找出合適的預先定義角色」。

您也可以選擇使用條件,只在符合特定需求時授予角色。

如要授予已包含在允許政策中的角色,請將主體新增至現有角色繫結:

gcloud

編輯傳回的允許政策,將主體新增至現有的角色繫結。您必須設定更新後的允許政策,這項變更才會生效。

舉例來說,假設允許政策包含下列角色繫結,可將安全性審查者角色 (roles/iam.securityReviewer) 授予 Kai:

{
  "role": "roles/iam.securityReviewer",
  "members": [
    "user:kai@example.com"
  ]
}

如要將相同角色授予 Raha,請將 Raha 的主體 ID 新增至現有角色繫結:

{
  "role": "roles/iam.securityReviewer",
  "members": [
    "user:kai@example.com",
    "user:raha@example.com"
  ]
}

C#

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章


using System.Linq;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy AddMember(Policy policy, string role, string member)
    {
        var binding = policy.Bindings.First(x => x.Role == role);
        binding.Members.Add(member);
        return policy;
    }
}

Go

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

import (
	"fmt"
	"io"

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

// addMember adds a member to a role binding.
func addMember(w io.Writer, policy *iam.Policy, role, member string) {
	for _, binding := range policy.Bindings {
		if binding.Role != role {
			continue
		}
		for _, m := range binding.Members {
			if m != member {
				continue
			}
			fmt.Fprintf(w, "Role %q found. Member already exists.\n", role)
			return
		}
		binding.Members = append(binding.Members, member)
		fmt.Fprintf(w, "Role %q found. Member added.\n", role)
		return
	}
	fmt.Fprintf(w, "Role %q not found. Member not added.\n", role)
}

Java

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import java.util.ArrayList;
import java.util.List;

public class AddMember {
  public static void main(String[] args) {
    // TODO(developer): Replace the variables before running the sample.
    // TODO: Replace with your policy, GetPolicy.getPolicy(projectId, serviceAccount).
    Policy policy = Policy.newBuilder().build();
    // TODO: Replace with your role.
    String role = "roles/existing-role";
    // TODO: Replace with your principal.
    // For examples, see https://cloud.google.com/iam/docs/principal-identifiers
    String member = "principal-id";

    addMember(policy, role, member);
  }

  // Adds a principal to a pre-existing role.
  public static Policy addMember(Policy policy, String role, String member) {
    List<Binding> newBindingsList = new ArrayList<>();

    for (Binding b : policy.getBindingsList()) {
      if (b.getRole().equals(role)) {
        newBindingsList.add(b.toBuilder().addMembers(member).build());
      } else {
        newBindingsList.add(b);
      }
    }

    // Update the policy to add the principal.
    Policy updatedPolicy = policy.toBuilder()
            .clearBindings()
            .addAllBindings(newBindingsList)
            .build();

    System.out.println("Added principal: " + updatedPolicy.getBindingsList());

    return updatedPolicy;
  }
}

Python

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

from google.iam.v1 import policy_pb2
from snippets.get_policy import get_project_policy
from snippets.set_policy import set_project_policy


def modify_policy_add_principal(
    project_id: str, role: str, principal: str
) -> policy_pb2.Policy:
    """Add a principal to certain role in project policy.

    project_id: ID or number of the Google Cloud project you want to use.
    role: role to which principal need to be added.
    principal: The principal requesting access.

    For principal ID formats, see https://cloud.google.com/iam/docs/principal-identifiers
    """
    policy = get_project_policy(project_id)

    for bind in policy.bindings:
        if bind.role == role:
            bind.members.append(principal)
            break

    return set_project_policy(project_id, policy)

REST

編輯傳回的允許政策,將主體新增至現有的角色繫結。您必須設定更新後的允許政策,這項變更才會生效。

舉例來說,假設允許政策包含下列角色繫結,可將安全性審查者角色 (roles/iam.securityReviewer) 授予 Kai:

{
  "role": "roles/iam.securityReviewer",
  "members": [
    "user:kai@example.com"
  ]
}

如要將相同角色授予 Raha,請將 Raha 的主體 ID 新增至現有角色繫結:

{
  "role": "roles/iam.securityReviewer",
  "members": [
    "user:kai@example.com",
    "user:raha@example.com"
  ]
}

如要授予允許政策尚未包含的角色,請新增角色繫結:

gcloud

編輯允許政策,新增角色繫結,將角色授予主體。您必須設定更新後的允許政策,這項變更才會生效。

舉例來說,如要將 Compute Storage Admin 角色 (roles/compute.storageAdmin) 授予 Raha,請將下列角色繫結新增至允許政策的 bindings 陣列:

{
  "role": "roles/compute.storageAdmin",
  "members": [
    "user:raha@example.com"
  ]
}

C#

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

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

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章


using System.Collections.Generic;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy AddBinding(Policy policy, string role, string member)
    {
        var binding = new Binding
        {
            Role = role,
            Members = new List<string> { member }
        };
        policy.Bindings.Add(binding);
        return policy;
    }
}

Java

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

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

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章


import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import java.util.Collections;
import java.util.List;

public class AddBinding {
  public static void main(String[] args) {
    // TODO(developer): Replace the variables before running the sample.
    // TODO: Replace with your policy: GetPolicy.getPolicy(projectId, serviceAccount).
    Policy policy = Policy.newBuilder().build();
    // TODO: Replace with your role.
    String role = "roles/role-to-add";
    // TODO: Replace with your principals.
    // For examples, see https://cloud.google.com/iam/docs/principal-identifiers
    List<String> members = Collections.singletonList("principal-id");

    addBinding(policy, role, members);
  }

  // Adds a principals to a role.
  public static Policy addBinding(Policy policy, String role, List<String> members) {
    Binding binding = Binding.newBuilder()
            .setRole(role)
            .addAllMembers(members)
            .build();

    // Update bindings for the policy.
    Policy updatedPolicy = policy.toBuilder().addBindings(binding).build();

    System.out.println("Added binding: " + updatedPolicy.getBindingsList());

    return updatedPolicy;
  }
}

Python

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

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

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

def modify_policy_add_role(policy: dict, role: str, principal: str) -> dict:
    """Adds a new role binding to a policy."""

    binding = {"role": role, "members": [principal]}
    policy["bindings"].append(binding)
    print(policy)
    return policy

REST

編輯允許政策,新增角色繫結,將角色授予主體。您必須設定更新後的允許政策,這項變更才會生效。

舉例來說,如要將 Compute Storage Admin 角色 (roles/compute.storageAdmin) 授予 Raha,請將下列角色繫結新增至允許政策的 bindings 陣列:

{
  "role": "roles/compute.storageAdmin",
  "members": [
    "user:raha@example.com"
  ]
}

您只能授予有關已啟用 API 服務的角色。如果某個服務 (例如 Compute Engine) 不在使用中狀態,則無法授予與 Compute Engine 完全相關的角色。詳情請參閱啟用和停用 API

在授予專案的權限時,您必須遵守一些獨特的限制,尤其是在授予「擁有者」roles/owner 角色時。詳情請參閱projects.setIamPolicy()參考說明文件

撤銷 IAM 角色

如要撤銷角色,請從角色繫結中移除主體。如果角色繫結中沒有其他主體,請移除整個角色繫結。

gcloud

如要撤銷角色,請編輯 get-iam-policy 指令傳回的 JSON 或 YAML 允許政策。您必須設定更新後的允許政策,這項變更才會生效。

如要撤銷主體的角色,請從允許政策的 bindings 陣列中刪除主體或繫結。

C#

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

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

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章


using System.Linq;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy RemoveMember(Policy policy, string role, string member)
    {
        try
        {
            var binding = policy.Bindings.First(x => x.Role == role);
            if (binding.Members.Count != 0 && binding.Members.Contains(member))
            {
                binding.Members.Remove(member);
            }
            if (binding.Members.Count == 0)
            {
                policy.Bindings.Remove(binding);
            }
            return policy;
        }
        catch (System.InvalidOperationException e)
        {
            System.Diagnostics.Debug.WriteLine("Role does not exist in policy: \n" + e.ToString());
            return policy;
        }
    }
}

Go

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

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

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

import (
	"fmt"
	"io"

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

// removeMember removes a member from a role binding.
func removeMember(w io.Writer, policy *iam.Policy, role, member string) {
	bindings := policy.Bindings
	bindingIndex, memberIndex := -1, -1
	for bIdx := range bindings {
		if bindings[bIdx].Role != role {
			continue
		}
		bindingIndex = bIdx
		for mIdx := range bindings[bindingIndex].Members {
			if bindings[bindingIndex].Members[mIdx] != member {
				continue
			}
			memberIndex = mIdx
			break
		}
	}
	if bindingIndex == -1 {
		fmt.Fprintf(w, "Role %q not found. Member not removed.\n", role)
		return
	}
	if memberIndex == -1 {
		fmt.Fprintf(w, "Role %q found. Member not found.\n", role)
		return
	}

	members := removeIdx(bindings[bindingIndex].Members, memberIndex)
	bindings[bindingIndex].Members = members
	if len(members) == 0 {
		bindings = removeIdx(bindings, bindingIndex)
		policy.Bindings = bindings
	}
	fmt.Fprintf(w, "Role %q found. Member removed.\n", role)
}

// removeIdx removes arr[idx] from arr.
func removeIdx[T any](arr []T, idx int) []T {
	return append(arr[:idx], arr[idx+1:]...)
}

Java

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

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

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class RemoveMember {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    // TODO: Replace with your policy, GetPolicy.getPolicy(projectId, serviceAccount).
    Policy policy = Policy.newBuilder().build();
    // TODO: Replace with your role.
    String role = "roles/existing-role";
    // TODO: Replace with your principal.
    // For examples, see https://cloud.google.com/iam/docs/principal-identifiers
    String member = "principal-id";

    removeMember(policy, role, member);
  }

  // Removes principal from a role; removes binding if binding contains no members.
  public static Policy removeMember(Policy policy, String role, String member) {
    // Creating new builder with all values copied from origin policy
    Policy.Builder policyBuilder = policy.toBuilder();

    // Getting binding with suitable role.
    Binding binding = null;
    for (Binding b : policy.getBindingsList()) {
      if (b.getRole().equals(role)) {
        binding = b;
        break;
      }
    }

    if (binding != null && binding.getMembersList().contains(member)) {
      List<String> newMemberList = new ArrayList<>(binding.getMembersList());
      // Removing principal from the role
      newMemberList.remove(member);

      System.out.println("Member " + member + " removed from " + role);

      // Adding all remaining principals to create new binding
      Binding newBinding = binding.toBuilder()
              .clearMembers()
              .addAllMembers(newMemberList)
              .build();

      List<Binding> newBindingList = new ArrayList<>(policyBuilder.getBindingsList());

      // Removing old binding to replace with new one
      newBindingList.remove(binding);

      // If binding has no more members, binding will not be added
      if (!newBinding.getMembersList().isEmpty()) {
        newBindingList.add(newBinding);
      }

      // Update the policy to remove the principal.
      policyBuilder.clearBindings()
              .addAllBindings(newBindingList);
    }

    Policy updatedPolicy = policyBuilder.build();

    System.out.println("Exising principals: " + updatedPolicy.getBindingsList());

    return updatedPolicy;
  }
}

Python

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

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

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

from google.iam.v1 import policy_pb2
from snippets.get_policy import get_project_policy
from snippets.set_policy import set_project_policy


def modify_policy_remove_principal(
    project_id: str, role: str, principal: str
) -> policy_pb2.Policy:
    """Remove a principal from certain role in project policy.

    project_id: ID or number of the Google Cloud project you want to use.
    role: role to revoke.
    principal: The principal to revoke access from.

    For principal ID formats, see https://cloud.google.com/iam/docs/principal-identifiers
    """
    policy = get_project_policy(project_id)

    for bind in policy.bindings:
        if bind.role == role:
            if principal in bind.members:
                bind.members.remove(principal)
            break

    return set_project_policy(project_id, policy, False)

REST

如要撤銷角色,請編輯 get-iam-policy 指令傳回的 JSON 或 YAML 允許政策。您必須設定更新後的允許政策,這項變更才會生效。

如要撤銷主體的角色,請從允許政策的 bindings 陣列中刪除主體或繫結。

設定允許政策

修改允許政策以授予及撤銷角色後,請呼叫 setIamPolicy() 來更新政策。

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. 如要為資源設定允許政策,請針對該資源執行 set-iam-policy 指令:

    gcloud RESOURCE_TYPE set-iam-policy RESOURCE_ID PATH

    提供以下這些值:

    • RESOURCE_TYPE:您要設定允許政策的資源類型。請使用下列其中一個值:projectsresource-manager foldersorganizations

    • RESOURCE_ID:您的 Google Cloud 專案、資料夾或機構 ID。專案 ID 為英數字元,例如 my-project。資料夾和機構 ID 是數字,例如 123456789012

    • PATH:包含新允許政策的檔案路徑。

    回應會包含更新後的允許政策。

    舉例來說,下列指令會將 policy.json 中儲存的允許政策,設為專案 my-project 的允許政策:

    gcloud projects set-iam-policy my-project ~/policy.json

C#


using Google.Apis.Auth.OAuth2;
using Google.Apis.CloudResourceManager.v1;
using Google.Apis.CloudResourceManager.v1.Data;

public partial class AccessManager
{
    public static Policy SetPolicy(string projectId, Policy policy)
    {
        var credential = GoogleCredential.GetApplicationDefault()
            .CreateScoped(CloudResourceManagerService.Scope.CloudPlatform);
        var service = new CloudResourceManagerService(
            new CloudResourceManagerService.Initializer
            {
                HttpClientInitializer = credential
            });

        return service.Projects.SetIamPolicy(new SetIamPolicyRequest
        {
            Policy = policy
        }, projectId).Execute();
    }
}

Java

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

以下範例說明如何為專案設定允許政策。如要瞭解如何設定資料夾或機構的允許政策,請參閱您所用程式設計語言的資源管理工具用戶端程式庫文件

import com.google.cloud.resourcemanager.v3.ProjectsClient;
import com.google.iam.admin.v1.ProjectName;
import com.google.iam.v1.Policy;
import com.google.iam.v1.SetIamPolicyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class SetProjectPolicy {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace the variables before running the sample.
    // TODO: Replace with your project ID.
    String projectId = "your-project-id";
    // TODO: Replace with your policy, GetPolicy.getPolicy(projectId, serviceAccount).
    Policy policy = Policy.newBuilder().build();

    setProjectPolicy(policy, projectId);
  }

  // Sets a project's policy.
  public static Policy setProjectPolicy(Policy policy, 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 (ProjectsClient projectsClient = ProjectsClient.create()) {
      List<String> paths = Arrays.asList("bindings", "etag");
      SetIamPolicyRequest request = SetIamPolicyRequest.newBuilder()
              .setResource(ProjectName.of(projectId).toString())
              .setPolicy(policy)
              // A FieldMask specifying which fields of the policy to modify. Only
              // the fields in the mask will be modified. If no mask is provided, the
              // following default mask is used:
              // `paths: "bindings, etag"`
              .setUpdateMask(FieldMask.newBuilder().addAllPaths(paths).build())
              .build();

      return projectsClient.setIamPolicy(request);
    }
  }
}

Python

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

如要瞭解如何安裝及使用 Resource Manager 的用戶端程式庫,請參閱這篇文章

以下範例說明如何為專案設定允許政策。如要瞭解如何設定資料夾或機構的允許政策,請參閱您所用程式設計語言的資源管理工具用戶端程式庫文件

from google.cloud import resourcemanager_v3
from google.iam.v1 import iam_policy_pb2, policy_pb2


def set_project_policy(
    project_id: str, policy: policy_pb2.Policy, merge: bool = True
) -> policy_pb2.Policy:
    """
    Set policy for project. Pay attention that previous state will be completely rewritten.
    If you want to update only part of the policy follow the approach read->modify->write.
    For more details about policies check out https://cloud.google.com/iam/docs/policies

    project_id: ID or number of the Google Cloud project you want to use.
    policy: Policy which has to be set.
    merge: The strategy to be used forming the request. CopyFrom is clearing both mutable and immutable fields,
    when MergeFrom is replacing only immutable fields and extending mutable.
    https://googleapis.dev/python/protobuf/latest/google/protobuf/message.html#google.protobuf.message.Message.CopyFrom
    """
    client = resourcemanager_v3.ProjectsClient()

    request = iam_policy_pb2.GetIamPolicyRequest()
    request.resource = f"projects/{project_id}"
    current_policy = client.get_iam_policy(request)

    # Etag should as fresh as possible to lower chance of collisions
    policy.ClearField("etag")
    if merge:
        current_policy.MergeFrom(policy)
    else:
        current_policy.CopyFrom(policy)

    request = iam_policy_pb2.SetIamPolicyRequest()
    request.resource = f"projects/{project_id}"

    # request.etag field also will be merged which means you are secured from collision,
    # but it means that request may fail and you need to leverage exponential retries approach
    # to be sure policy has been updated.
    request.policy.CopyFrom(current_policy)

    policy = client.set_iam_policy(request)
    return policy

REST

Resource Manager API 的 setIamPolicy 方法會將要求中的政策設為專案、資料夾或機構的新允許政策。

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

  • API_VERSION:要使用的 API 版本。如果是專案和機構,請使用 v1。如果是資料夾,請使用 v2
  • RESOURCE_TYPE:您要管理的政策所屬資源類型。請使用 projectsfoldersorganizations 值。
  • RESOURCE_ID:您的 Google Cloud專案、機構或資料夾 ID。專案 ID 為英數字串,例如 my-project。資料夾和機構 ID 為數字,例如 123456789012
  • POLICY:要設定的政策 JSON 表示法。如要進一步瞭解政策格式,請參閱政策參考資料

HTTP 方法和網址:

POST https://cloudresourcemanager.googleapis.com/API_VERSION/RESOURCE_TYPE/RESOURCE_ID:setIamPolicy

JSON 要求主體:

{
  "policy": POLICY
}

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

回應會包含更新後的允許政策。

後續步驟

歡迎試用

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

免費試用