使用 IAM 控管資源的存取權

本文件說明如何查看資源目前的存取權政策、如何授予資源存取權,以及如何撤銷資源存取權

本文假設您熟悉 Google Cloud中的身分與存取權管理 (IAM)

必要的角色

如要取得修改資源身分與存取權管理政策所需的權限,請要求管理員為您授予專案的 BigQuery 資料擁有者 (roles/bigquery.dataOwner) 身分與存取權管理角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

這個預先定義的角色具備修改資源 IAM 政策所需的權限。如要查看確切的必要權限,請展開「必要權限」部分:

所需權限

如要修改資源的 IAM 政策,必須具備下列權限:

  • 如要取得資料集的存取權政策,請按照下列步驟操作: bigquery.datasets.get
  • 如何設定資料集的存取權政策: bigquery.datasets.update
  • 如何取得資料集的存取權政策 (僅限Google Cloud 控制台): bigquery.datasets.getIamPolicy
  • 如何設定資料集的存取權政策 (僅限控制台): bigquery.datasets.setIamPolicy
  • 如要取得資料表或檢視表的政策,請按照下列步驟操作: bigquery.tables.getIamPolicy
  • 如要設定資料表或檢視表的政策,請按照下列步驟操作: bigquery.tables.setIamPolicy
  • 如要取得例行工作的存取權政策,請按照下列步驟操作: bigquery.routines.getIamPolicy
  • 如何設定日常安排的存取權政策: bigquery.routines.setIamPolicy
  • 如要建立 bq 工具或 SQL BigQuery 作業 (選用): bigquery.jobs.create

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

查看資源的存取權政策

下列各節將說明如何查看不同資源的存取權政策。

查看資料集的存取權政策

選取下列選項之一:

主控台

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在「Explorer」窗格中展開專案並選取資料集。

  3. 依序按一下 「分享」>「權限」

    資料集存取權政策會顯示在「Dataset Permissions」窗格中。

bq

  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. 如要取得現有政策並將其輸出至 JSON 本機檔案,請在 Cloud Shell 中使用 bq show 指令

    bq show \
       --format=prettyjson \
       PROJECT_ID:DATASET > PATH_TO_FILE

    更改下列內容:

    • PROJECT_ID:您的專案 ID
    • DATASET:資料集名稱
    • PATH_TO_FILE:本機 JSON 檔案的路徑

API

如要查看資料集的存取政策,請呼叫 datasets.get 方法,搭配已定義的 dataset 資源

政策可在傳回的 dataset 資源的 access 屬性中使用。

Go

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Go 設定說明進行操作。詳情請參閱 BigQuery Go API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

呼叫 client.Dataset().Metadata() 函式。存取權政策可在 Access 屬性中使用。
import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/bigquery"
)

// viewDatasetAccessPolicies retrieves the ACL for the given dataset
// For more information on the types of ACLs available see:
// https://cloud.google.com/storage/docs/access-control/lists
func viewDatasetAccessPolicies(w io.Writer, projectID, datasetID string) error {
	// TODO(developer): uncomment and update the following lines:
	// projectID := "my-project-id"
	// datasetID := "mydataset"

	ctx := context.Background()

	// Create new client.
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %w", err)
	}
	defer client.Close()

	// Get dataset's metadata.
	meta, err := client.Dataset(datasetID).Metadata(ctx)
	if err != nil {
		return fmt.Errorf("bigquery.Client.Dataset.Metadata: %w", err)
	}

	fmt.Fprintf(w, "Details for Access entries in dataset %v.\n", datasetID)

	// Iterate over access permissions.
	for _, access := range meta.Access {
		fmt.Fprintln(w)
		fmt.Fprintf(w, "Role: %s\n", access.Role)
		fmt.Fprintf(w, "Entity: %v\n", access.Entity)
	}

	return nil
}

Java

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Java 設定說明進行操作。詳情請參閱 BigQuery Java API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。


import com.google.cloud.bigquery.Acl;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Dataset;
import com.google.cloud.bigquery.DatasetId;
import java.util.List;

public class GetDatasetAccessPolicy {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    // Project and dataset from which to get the access policy.
    String projectId = "MY_PROJECT_ID";
    String datasetName = "MY_DATASET_NAME";
    getDatasetAccessPolicy(projectId, datasetName);
  }

  public static void getDatasetAccessPolicy(String projectId, String datasetName) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      // Create datasetId with the projectId and the datasetName.
      DatasetId datasetId = DatasetId.of(projectId, datasetName);
      Dataset dataset = bigquery.getDataset(datasetId);

      // Show ACL details.
      // Find more information about ACL and the Acl Class here:
      // https://cloud.google.com/storage/docs/access-control/lists
      // https://cloud.google.com/java/docs/reference/google-cloud-bigquery/latest/com.google.cloud.bigquery.Acl
      List<Acl> acls = dataset.getAcl();
      System.out.println("ACLs in dataset \"" + dataset.getDatasetId().getDataset() + "\":");
      System.out.println(acls.toString());
      for (Acl acl : acls) {
        System.out.println();
        System.out.println("Role: " + acl.getRole());
        System.out.println("Entity: " + acl.getEntity());
      }
    } catch (BigQueryException e) {
      System.out.println("ACLs info not retrieved. \n" + e.toString());
    }
  }
}

Node.js

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Node.js 設定說明進行操作。詳情請參閱 BigQuery Node.js API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

使用 Dataset#getMetadata() 函式擷取資料集中繼資料。存取政策可在產生的中繼資料物件存取屬性中找到。

/**
 * TODO(developer): Update and un-comment below lines
 */
// const datasetId = "my_project_id.my_dataset";

const {BigQuery} = require('@google-cloud/bigquery');

// Instantiate a client.
const bigquery = new BigQuery();

async function viewDatasetAccessPolicy() {
  const dataset = bigquery.dataset(datasetId);

  const [metadata] = await dataset.getMetadata();
  const accessEntries = metadata.access || [];

  // Show the list of AccessEntry objects.
  // More details about the AccessEntry object in the BigQuery documentation:
  // https://cloud.google.com/nodejs/docs/reference/bigquery/latest
  console.log(
    `${accessEntries.length} Access entries in dataset '${datasetId}':`
  );
  for (const accessEntry of accessEntries) {
    console.log(`Role: ${accessEntry.role || 'null'}`);
    console.log(`Special group: ${accessEntry.specialGroup || 'null'}`);
    console.log(`User by Email: ${accessEntry.userByEmail || 'null'}`);
  }
}

Python

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Python 設定說明進行操作。詳情請參閱 BigQuery Python API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

呼叫 client.get_dataset() 函式。存取權政策可在 dataset.access_entries 屬性中使用。
from google.cloud import bigquery

# Instantiate a client.
client = bigquery.Client()

# TODO(developer): Update and uncomment the lines below.

# Dataset from which to get the access policy.
# dataset_id = "my_dataset"

# Get a reference to the dataset.
dataset = client.get_dataset(dataset_id)

# Show the list of AccessEntry objects.
# More details about the AccessEntry object here:
# https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.dataset.AccessEntry
print(
    f"{len(dataset.access_entries)} Access entries found "
    f"in dataset '{dataset_id}':"
)

for access_entry in dataset.access_entries:
    print()
    print(f"Role: {access_entry.role}")
    print(f"Special group: {access_entry.special_group}")
    print(f"User by Email: {access_entry.user_by_email}")

查看資料表或檢視表的存取權政策

選取下列選項之一:

主控台

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在「Explorer」窗格中展開專案,然後選取資料表或檢視畫面。

  3. 按一下「分享」圖示

    資料表或檢視權限政策會顯示在「Share」窗格中。

bq

  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. 如要取得現有的存取權政策,並將其輸出至 JSON 格式的本機檔案,請在 Cloud Shell 中使用 bq get-iam-policy 指令

    bq get-iam-policy \
        --table=true \
        PROJECT_ID:DATASET.RESOURCE > PATH_TO_FILE

    更改下列內容:

    • PROJECT_ID:您的專案 ID
    • DATASET:資料集名稱
    • RESOURCE:您要查看政策的資料表或檢視畫面名稱
    • PATH_TO_FILE:本機 JSON 檔案的路徑

API

如要擷取目前的政策,請呼叫 tables.getIamPolicy 方法

Go

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Go 設定說明進行操作。詳情請參閱 BigQuery Go API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

呼叫資源的 IAM().Policy() 函式。接著呼叫 Roles() 函式,即可取得資料表或檢視畫面的存取權政策。
import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/bigquery"
)

// viewTableOrViewAccessPolicies retrieves the ACL for the given resource
// For more information on the types of ACLs available see:
// https://cloud.google.com/storage/docs/access-control/lists
func viewTableOrViewAccessPolicies(w io.Writer, projectID, datasetID, resourceID string) error {
	// Resource can be a table or a view
	//
	// TODO(developer): uncomment and update the following lines:
	// projectID := "my-project-id"
	// datasetID := "my-dataset-id"
	// resourceID := "my-resource-id"

	ctx := context.Background()

	// Create new client.
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %w", err)
	}
	defer client.Close()

	// Get resource's policy access.
	policy, err := client.Dataset(datasetID).Table(resourceID).IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("bigquery.Dataset.Table.IAM.Policy: %w", err)
	}

	fmt.Fprintf(w, "Details for Access entries in table or view %v.\n", resourceID)

	for _, role := range policy.Roles() {
		fmt.Fprintln(w)
		fmt.Fprintf(w, "Role: %s\n", role)
		fmt.Fprintf(w, "Entities: %v\n", policy.Members(role))
	}

	return nil
}

Java

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Java 設定說明進行操作。詳情請參閱 BigQuery Java API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。


import com.google.cloud.Policy;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.TableId;

public class GetTableOrViewAccessPolicy {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    // Project, dataset and resource (table or view) from which to get the access policy.
    String projectId = "MY_PROJECT_ID";
    String datasetName = "MY_DATASET_NAME";
    String resourceName = "MY_RESOURCE_NAME";
    getTableOrViewAccessPolicy(projectId, datasetName, resourceName);
  }

  public static void getTableOrViewAccessPolicy(
      String projectId, String datasetName, String resourceName) {
    try {
      // Initialize client that will be used to send requests. This client only needs
      // to be created once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      // Create table identity given the projectId, the datasetName and the resourceName.
      TableId tableId = TableId.of(projectId, datasetName, resourceName);

      // Get the table IAM policy.
      Policy policy = bigquery.getIamPolicy(tableId);

      // Show policy details.
      // Find more information about the Policy Class here:
      // https://cloud.google.com/java/docs/reference/google-cloud-core/latest/com.google.cloud.Policy
      System.out.println(
          "IAM policy info of resource \"" + resourceName + "\" retrieved succesfully");
      System.out.println();
      System.out.println("IAM policy info: " + policy.toString());
    } catch (BigQueryException e) {
      System.out.println("IAM policy info not retrieved. \n" + e.toString());
    }
  }
}

Node.js

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Node.js 設定說明進行操作。詳情請參閱 BigQuery Node.js API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

使用 Table#getIamPolicy() 函式,擷取資料表或檢視畫面的身分與存取權管理政策。存取權政策詳細資料會顯示在傳回的政策物件中。

/**
 * TODO(developer): Update and un-comment below lines
 */
// const projectId = "YOUR_PROJECT_ID"
// const datasetId = "YOUR_DATASET_ID"
// const resourceName = "YOUR_RESOURCE_NAME";

const {BigQuery} = require('@google-cloud/bigquery');

// Instantiate a client.
const client = new BigQuery();

async function viewTableOrViewAccessPolicy() {
  const dataset = client.dataset(datasetId);
  const table = dataset.table(resourceName);

  // Get the IAM access policy for the table or view.
  const [policy] = await table.getIamPolicy();

  // Initialize bindings if they don't exist
  if (!policy.bindings) {
    policy.bindings = [];
  }

  // Show policy details.
  // Find more details for the Policy object here:
  // https://cloud.google.com/bigquery/docs/reference/rest/v2/Policy
  console.log(`Access Policy details for table or view '${resourceName}'.`);
  console.log(`Bindings: ${JSON.stringify(policy.bindings, null, 2)}`);
  console.log(`etag: ${policy.etag}`);
  console.log(`Version: ${policy.version}`);
}

授予資源存取權

下列各節將說明如何授予不同資源的存取權。

授予資料集存取權

您可以授予 IAM 角色存取資料集的權限,或是使用 IAM 條件條件式授予存取權,以便提供資料集存取權。如要進一步瞭解如何授予條件式存取權,請參閱「使用 IAM 條件控管存取權」。

如要不使用條件授予 IAM 角色資料集存取權,請選取下列其中一個選項:

主控台

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在「Explorer」窗格中展開專案,然後選取要分享的資料集。

  3. 依序按一下「共用」圖示 >「權限」

  4. 按一下 「新增主體」

  5. 在「新增主體」欄位中輸入主體。

  6. 在「選取角色」清單中,選取預先定義的角色或自訂角色。

  7. 按一下 [儲存]

  8. 如要返回資料集資訊,請按一下「關閉」

SQL

如要授予使用者資料集存取權,請使用 GRANT DCL 陳述式

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

    前往 BigQuery

  2. 在查詢編輯器中輸入以下陳述式:

    GRANT `ROLE_LIST`
    ON SCHEMA RESOURCE_NAME
    TO "USER_LIST"

    請依指示取代下列項目:

    • ROLE_LIST:您要授予的角色或以半形逗號分隔的角色清單
    • RESOURCE_NAME:您要授予權限的資源名稱
    • USER_LIST:以半形逗號分隔的清單,當中列有授予角色的使用者

      如需有效格式的清單,請參閱 user_list

  3. 按一下 「Run」

如要進一步瞭解如何執行查詢,請參閱「執行互動式查詢」一文。

以下範例會授予資料集 myDataset 的「資料檢視者」角色:

GRANT `roles/bigquery.dataViewer`
ON SCHEMA `myProject`.myDataset
TO "user:raha@example-pet-store.com", "user:sasha@example-pet-store.com"

bq

  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. 如要將現有的資料集資訊 (包括存取權控管設定) 寫入 JSON 檔案,請使用 bq show 指令

    bq show \
        --format=prettyjson \
        PROJECT_ID:DATASET > PATH_TO_FILE

    更改下列內容:

    • PROJECT_ID:您的專案 ID
    • DATASET:資料集名稱
    • PATH_TO_FILE:本機上 JSON 檔案的路徑
  3. 變更 JSON 檔案的 access 區段。您可以新增至任何 specialGroup 項目:projectOwnersprojectWritersprojectReadersallAuthenticatedUsers。您也可以新增下列任一項目:userByEmailgroupByEmaildomain

    舉例來說,資料集 JSON 檔案中的 access 區段會如下所示:

    {
     "access": [
      {
       "role": "READER",
       "specialGroup": "projectReaders"
      },
      {
       "role": "WRITER",
       "specialGroup": "projectWriters"
      },
      {
       "role": "OWNER",
       "specialGroup": "projectOwners"
      },
      {
       "role": "READER",
       "specialGroup": "allAuthenticatedUsers"
      },
      {
       "role": "READER",
       "domain": "domain_name"
      },
      {
       "role": "WRITER",
       "userByEmail": "user_email"
      },
      {
       "role": "READER",
       "groupByEmail": "group_email"
      }
     ],
     ...
    }
  4. 完成編輯後,請使用 bq update 指令並利用 --source 標記納入 JSON 檔案。如果資料集位於預設專案以外的專案中,請使用下列格式將專案 ID 新增至資料集名稱:PROJECT_ID:DATASET

      bq update 
    --source PATH_TO_FILE
    PROJECT_ID:DATASET

  5. 如要驗證您的存取權控管設定變更,請再次使用 bq show 指令,但不要將資訊寫入檔案:

    bq show --format=prettyjson PROJECT_ID:DATASET

Terraform

使用 google_bigquery_dataset_iam 資源更新資料集存取權。

設定資料集的存取權政策

以下範例說明如何使用 google_bigquery_dataset_iam_policy 資源設定 mydataset 資料集的 IAM 政策。這會取代已附加至資料集的任何現有政策:

# This file sets the IAM policy for the dataset created by
# https://github.com/terraform-google-modules/terraform-docs-samples/blob/main/bigquery/bigquery_create_dataset/main.tf.
# You must place it in the same local directory as that main.tf file,
# and you must have already applied that main.tf file to create
# the "default" dataset resource with a dataset_id of "mydataset".

data "google_iam_policy" "iam_policy" {
  binding {
    role = "roles/bigquery.admin"
    members = [
      "user:hao@altostrat.com",
    ]
  }
  binding {
    role = "roles/bigquery.dataOwner"
    members = [
      "group:dba@altostrat.com",
    ]
  }
  binding {
    role = "roles/bigquery.dataEditor"
    members = [
      "serviceAccount:bqcx-1234567891011-12a3@gcp-sa-bigquery-condel.iam.gserviceaccount.com",
    ]
  }
}

resource "google_bigquery_dataset_iam_policy" "dataset_iam_policy" {
  dataset_id  = google_bigquery_dataset.default.dataset_id
  policy_data = data.google_iam_policy.iam_policy.policy_data
}

設定資料集的角色成員資格

以下範例說明如何使用 google_bigquery_dataset_iam_binding 資源,為 mydataset 資料集設定特定角色的成員資格。這會取代該角色中現有的任何會員資格。資料集的 IAM 政策中保留其他角色:

# This file sets membership in an IAM role for the dataset created by
# https://github.com/terraform-google-modules/terraform-docs-samples/blob/main/bigquery/bigquery_create_dataset/main.tf.
# You must place it in the same local directory as that main.tf file,
# and you must have already applied that main.tf file to create
# the "default" dataset resource with a dataset_id of "mydataset".

resource "google_bigquery_dataset_iam_binding" "dataset_iam_binding" {
  dataset_id = google_bigquery_dataset.default.dataset_id
  role       = "roles/bigquery.jobUser"

  members = [
    "user:raha@altostrat.com",
    "group:analysts@altostrat.com"
  ]
}

為單一主體設定角色成員資格

以下範例說明如何使用 google_bigquery_dataset_iam_member 資源更新 mydataset 資料集的 IAM 政策,為單一主體授予角色。更新這項 IAM 政策不會影響任何其他已獲授權存取資料集的使用者主體。

# This file adds a member to an IAM role for the dataset created by
# https://github.com/terraform-google-modules/terraform-docs-samples/blob/main/bigquery/bigquery_create_dataset/main.tf.
# You must place it in the same local directory as that main.tf file,
# and you must have already applied that main.tf file to create
# the "default" dataset resource with a dataset_id of "mydataset".

resource "google_bigquery_dataset_iam_member" "dataset_iam_member" {
  dataset_id = google_bigquery_dataset.default.dataset_id
  role       = "roles/bigquery.user"
  member     = "user:yuri@altostrat.com"
}

如要在 Google Cloud 專案中套用 Terraform 設定,請完成下列各節中的步驟。

準備 Cloud Shell

  1. 啟動 Cloud Shell
  2. 設定要套用 Terraform 設定的預設 Google Cloud 專案。

    您只需為每個專案執行這個指令一次,而且可以在任何目錄中執行。

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    如果您在 Terraform 設定檔中設定明確的值,系統就會覆寫環境變數。

準備目錄

每個 Terraform 設定檔都必須有自己的目錄 (也稱為根模組)。

  1. Cloud Shell 中建立目錄,並在該目錄中建立新檔案。檔案名稱必須包含 .tf 副檔名,例如 main.tf。在本教學課程中,檔案稱為 main.tf
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. 如果您正在參考教學課程,可以複製各個章節或步驟中的程式碼範例。

    將範例程式碼複製到新建立的 main.tf 中。

    您可以視需要從 GitHub 複製程式碼。如果 Terraform 程式碼片段是端對端解決方案的一部分,建議您採用這種做法。

  3. 查看並修改要套用至環境的範例參數。
  4. 儲存變更。
  5. 初始化 Terraform。這項操作只需對每個目錄執行一次。
    terraform init

    如要使用最新版的 Google 供應器,您可以選擇加入 -upgrade 選項:

    terraform init -upgrade

套用變更

  1. 檢查設定,確認 Terraform 要建立或更新的資源符合您的預期:
    terraform plan

    視需要修正設定。

  2. 執行下列指令,並在提示中輸入 yes,即可套用 Terraform 設定:
    terraform apply

    等待 Terraform 顯示「Apply complete!」(套用完成) 訊息。

  3. 開啟 Google Cloud 專案即可查看結果。在 Google Cloud 控制台中,前往 UI 中的資源,確認 Terraform 已建立或更新這些資源。

API

如要在建立資料集時套用存取權控管,請使用定義的資料集資源呼叫 datasets.insert 方法。如要更新存取權控管設定,請呼叫 datasets.patch 方法,並使用 Dataset 資源中的 access 屬性。

由於 datasets.update 方法會取代整個資料集的資源,因此建議您使用 datasets.patch 方法來更新存取權控管設定。

Go

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Go 設定說明進行操作。詳情請參閱 BigQuery Go API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

設定新的存取清單,方法是使用 DatasetMetadataToUpdate 類型將新項目附加至現有清單。然後呼叫 dataset.Update() 函式來更新屬性。
import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/bigquery"
)

// grantAccessToDataset creates a new ACL conceding the READER role to the group "example-analyst-group@google.com"
// For more information on the types of ACLs available see:
// https://cloud.google.com/storage/docs/access-control/lists
func grantAccessToDataset(w io.Writer, projectID, datasetID string) error {
	// TODO(developer): uncomment and update the following lines:
	// projectID := "my-project-id"
	// datasetID := "mydataset"

	ctx := context.Background()

	// Create BigQuery handler.
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %w", err)
	}
	defer client.Close()

	// Create dataset handler
	dataset := client.Dataset(datasetID)

	// Get metadata
	meta, err := dataset.Metadata(ctx)
	if err != nil {
		return fmt.Errorf("bigquery.Dataset.Metadata: %w", err)
	}

	// Find more details about BigQuery Entity Types here:
	// https://pkg.go.dev/cloud.google.com/go/bigquery#EntityType
	//
	// Find more details about BigQuery Access Roles here:
	// https://pkg.go.dev/cloud.google.com/go/bigquery#AccessRole

	entityType := bigquery.GroupEmailEntity
	entityID := "example-analyst-group@google.com"
	roleType := bigquery.ReaderRole

	// Append a new access control entry to the existing access list.
	update := bigquery.DatasetMetadataToUpdate{
		Access: append(meta.Access, &bigquery.AccessEntry{
			Role:       roleType,
			EntityType: entityType,
			Entity:     entityID,
		}),
	}

	// Leverage the ETag for the update to assert there's been no modifications to the
	// dataset since the metadata was originally read.
	meta, err = dataset.Update(ctx, update, meta.ETag)
	if err != nil {
		return err
	}

	fmt.Fprintf(w, "Details for Access entries in dataset %v.\n", datasetID)
	for _, access := range meta.Access {
		fmt.Fprintln(w)
		fmt.Fprintf(w, "Role: %s\n", access.Role)
		fmt.Fprintf(w, "Entities: %v\n", access.Entity)
	}

	return nil
}

Java

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Java 設定說明進行操作。詳情請參閱 BigQuery Java API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.cloud.bigquery.Acl;
import com.google.cloud.bigquery.Acl.Entity;
import com.google.cloud.bigquery.Acl.Group;
import com.google.cloud.bigquery.Acl.Role;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Dataset;
import com.google.cloud.bigquery.DatasetId;
import java.util.ArrayList;
import java.util.List;

public class GrantAccessToDataset {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    // Project and dataset from which to get the access policy
    String projectId = "MY_PROJECT_ID";
    String datasetName = "MY_DATASET_NAME";
    // Group to add to the ACL
    String entityEmail = "group-to-add@example.com";

    grantAccessToDataset(projectId, datasetName, entityEmail);
  }

  public static void grantAccessToDataset(
      String projectId, String datasetName, String entityEmail) {
    try {
      // Initialize client that will be used to send requests. This client only needs to be created
      // once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      // Create datasetId with the projectId and the datasetName.
      DatasetId datasetId = DatasetId.of(projectId, datasetName);
      Dataset dataset = bigquery.getDataset(datasetId);

      // Create a new Entity with the corresponding type and email
      // "user-or-group-to-add@example.com"
      // For more information on the types of Entities available see:
      // https://cloud.google.com/java/docs/reference/google-cloud-bigquery/latest/com.google.cloud.bigquery.Acl.Entity
      // and
      // https://cloud.google.com/java/docs/reference/google-cloud-bigquery/latest/com.google.cloud.bigquery.Acl.Entity.Type
      Entity entity = new Group(entityEmail);

      // Create a new ACL granting the READER role to the group with the entity email
      // "user-or-group-to-add@example.com"
      // For more information on the types of ACLs available see:
      // https://cloud.google.com/storage/docs/access-control/lists
      Acl newEntry = Acl.of(entity, Role.READER);

      // Get a copy of the ACLs list from the dataset and append the new entry.
      List<Acl> acls = new ArrayList<>(dataset.getAcl());
      acls.add(newEntry);

      // Update the ACLs by setting the new list.
      Dataset updatedDataset = bigquery.update(dataset.toBuilder().setAcl(acls).build());
      System.out.println(
          "ACLs of dataset \""
              + updatedDataset.getDatasetId().getDataset()
              + "\" updated successfully");
    } catch (BigQueryException e) {
      System.out.println("ACLs were not updated \n" + e.toString());
    }
  }
}

Node.js

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Node.js 設定說明進行操作。詳情請參閱 BigQuery Node.js API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

設定新的存取清單,方法是使用 Dataset#metadata 方法,將新項目附加至現有清單。然後呼叫 Dataset#setMetadata() 函式來更新屬性。

/**
 * TODO(developer): Update and un-comment below lines.
 */

// const datasetId = "my_project_id.my_dataset_name";

// ID of the user or group from whom you are adding access.
// const entityId = "user-or-group-to-add@example.com";

// One of the "Basic roles for datasets" described here:
// https://cloud.google.com/bigquery/docs/access-control-basic-roles#dataset-basic-roles
// const role = "READER";

const {BigQuery} = require('@google-cloud/bigquery');

// Instantiate a client.
const client = new BigQuery();

// Type of entity you are granting access to.
// Find allowed allowed entity type names here:
// https://cloud.google.com/bigquery/docs/reference/rest/v2/datasets#resource:-dataset
const entityType = 'groupByEmail';

async function grantAccessToDataset() {
  const [dataset] = await client.dataset(datasetId).get();

  // The 'access entries' array is immutable. Create a copy for modifications.
  const entries = [...dataset.metadata.access];

  // Append an AccessEntry to grant the role to a dataset.
  // Find more details about the AccessEntry object in the BigQuery documentation:
  // https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.dataset.AccessEntry
  entries.push({
    role,
    [entityType]: entityId,
  });

  // Assign the array of AccessEntries back to the dataset.
  const metadata = {
    access: entries,
  };

  // Update will only succeed if the dataset
  // has not been modified externally since retrieval.
  //
  // See the BigQuery client library documentation for more details on metadata updates:
  // https://cloud.google.com/nodejs/docs/reference/bigquery/latest

  // Update just the 'access entries' property of the dataset.
  await client.dataset(datasetId).setMetadata(metadata);

  console.log(
    `Role '${role}' granted for entity '${entityId}' in '${datasetId}'.`
  );
}

Python

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Python 設定說明進行操作。詳情請參閱 BigQuery Python API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

設定資料集的存取權控管,dataset.access_entries 屬性。然後呼叫 client.update_dataset() 函式來更新屬性。
from google.api_core.exceptions import PreconditionFailed
from google.cloud import bigquery
from google.cloud.bigquery.enums import EntityTypes

# TODO(developer): Update and uncomment the lines below.

# ID of the dataset to grant access to.
# dataset_id = "my_project_id.my_dataset"

# ID of the user or group receiving access to the dataset.
# Alternatively, the JSON REST API representation of the entity,
# such as the view's table reference.
# entity_id = "user-or-group-to-add@example.com"

# One of the "Basic roles for datasets" described here:
# https://cloud.google.com/bigquery/docs/access-control-basic-roles#dataset-basic-roles
# role = "READER"

# Type of entity you are granting access to.
# Find allowed allowed entity type names here:
# https://cloud.google.com/python/docs/reference/bigquery/latest/enums#class-googlecloudbigqueryenumsentitytypesvalue
entity_type = EntityTypes.GROUP_BY_EMAIL

# Instantiate a client.
client = bigquery.Client()

# Get a reference to the dataset.
dataset = client.get_dataset(dataset_id)

# The `access_entries` list is immutable. Create a copy for modifications.
entries = list(dataset.access_entries)

# Append an AccessEntry to grant the role to a dataset.
# Find more details about the AccessEntry object here:
# https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.dataset.AccessEntry
entries.append(
    bigquery.AccessEntry(
        role=role,
        entity_type=entity_type,
        entity_id=entity_id,
    )
)

# Assign the list of AccessEntries back to the dataset.
dataset.access_entries = entries

# Update will only succeed if the dataset
# has not been modified externally since retrieval.
#
# See the BigQuery client library documentation for more details on `update_dataset`:
# https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.client.Client#google_cloud_bigquery_client_Client_update_dataset
try:
    # Update just the `access_entries` property of the dataset.
    dataset = client.update_dataset(
        dataset,
        ["access_entries"],
    )

    # Show a success message.
    full_dataset_id = f"{dataset.project}.{dataset.dataset_id}"
    print(
        f"Role '{role}' granted for entity '{entity_id}'"
        f" in dataset '{full_dataset_id}'."
    )
except PreconditionFailed:  # A read-modify-write error
    print(
        f"Dataset '{dataset.dataset_id}' was modified remotely before this update. "
        "Fetch the latest version and retry."
    )

授予資料表或檢視表的存取權

選取下列選項之一:

主控台

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在「Explorer」窗格中展開專案,然後選取要分享的資料表或檢視畫面。

  3. 按一下「分享」圖示

  4. 按一下 「新增主體」

  5. 在「新增主體」欄位中輸入主體。

  6. 在「選取角色」清單中,選取預先定義的角色或自訂角色。

  7. 按一下 [儲存]

  8. 如要返回資料表或查看詳細資料,請按一下「關閉」

SQL

如要授予使用者存取資料表或檢視表的權限,請使用 GRANT DCL 陳述式

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

    前往 BigQuery

  2. 在查詢編輯器中輸入以下陳述式:

    GRANT `ROLE_LIST`
    ON RESOURCE_TYPE RESOURCE_NAME
    TO "USER_LIST"

    請依指示取代下列項目:

    • ROLE_LIST:您要授予的角色或以半形逗號分隔的角色清單
    • RESOURCE_TYPE:角色套用的資源類型

      支援的值包括 TABLEVIEWMATERIALIZED VIEWEXTERNAL TABLE

    • RESOURCE_NAME:您要授予權限的資源名稱
    • USER_LIST:以半形逗號分隔的清單,當中列有授予角色的使用者

      如需有效格式的清單,請參閱 user_list

  3. 按一下 「Run」

如要進一步瞭解如何執行查詢,請參閱「執行互動式查詢」一文。

以下範例會授予資料檢視者角色至資料表 myTable

GRANT `roles/bigquery.dataViewer`
ON TABLE `myProject`.myDataset.myTable
TO "user:raha@example-pet-store.com", "user:sasha@example-pet-store.com"

bq

  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. 如要授予資料表或檢視表的存取權,請使用 bq add-iam-policy-binding 指令

    bq add-iam-policy-binding --member=MEMBER_TYPE:MEMBER --role=ROLE
      --table=true RESOURCE

    更改下列內容:

    • MEMBER_TYPE:成員的類型,例如 usergroupserviceAccountdomain
    • MEMBER:成員的電子郵件地址或網域名稱。
    • ROLE:您要授予成員的角色。
    • RESOURCE:要更新政策的資料表或檢視表名稱。

Terraform

使用 google_bigquery_table_iam 資源更新資料表的存取權。

設定資料表的存取權政策

以下範例說明如何使用 google_bigquery_table_iam_policy 資源設定 mytable 資料表的 IAM 政策。這會取代已附加至資料表的任何現有政策:

# This file sets the IAM policy for the table created by
# https://github.com/terraform-google-modules/terraform-docs-samples/blob/main/bigquery/bigquery_create_table/main.tf.
# You must place it in the same local directory as that main.tf file,
# and you must have already applied that main.tf file to create
# the "default" table resource with a table_id of "mytable".

data "google_iam_policy" "iam_policy" {
  binding {
    role = "roles/bigquery.dataOwner"
    members = [
      "user:raha@altostrat.com",
    ]
  }
}

resource "google_bigquery_table_iam_policy" "table_iam_policy" {
  dataset_id  = google_bigquery_table.default.dataset_id
  table_id    = google_bigquery_table.default.table_id
  policy_data = data.google_iam_policy.iam_policy.policy_data
}

設定表格的角色成員資格

以下範例說明如何使用 google_bigquery_table_iam_binding 資源,為 mytable 資料表中的特定角色設定成員資格。這會取代該角色中現有的任何會員資格。資料表的 IAM 政策中保留其他角色。

# This file sets membership in an IAM role for the table created by
# https://github.com/terraform-google-modules/terraform-docs-samples/blob/main/bigquery/bigquery_create_table/main.tf.
# You must place it in the same local directory as that main.tf file,
# and you must have already applied that main.tf file to create
# the "default" table resource with a table_id of "mytable".

resource "google_bigquery_table_iam_binding" "table_iam_binding" {
  dataset_id = google_bigquery_table.default.dataset_id
  table_id   = google_bigquery_table.default.table_id
  role       = "roles/bigquery.dataOwner"

  members = [
    "group:analysts@altostrat.com",
  ]
}

為單一主體設定角色成員資格

以下範例說明如何使用 google_bigquery_table_iam_member 資源更新 mytable 資料表的 IAM 政策,為單一主體授予角色。更新這項 IAM 政策不會影響任何其他已獲授權存取資料集的使用者主體。

# This file adds a member to an IAM role for the table created by
# https://github.com/terraform-google-modules/terraform-docs-samples/blob/main/bigquery/bigquery_create_table/main.tf.
# You must place it in the same local directory as that main.tf file,
# and you must have already applied that main.tf file to create
# the "default" table resource with a table_id of "mytable".

resource "google_bigquery_table_iam_member" "table_iam_member" {
  dataset_id = google_bigquery_table.default.dataset_id
  table_id   = google_bigquery_table.default.table_id
  role       = "roles/bigquery.dataEditor"
  member     = "serviceAccount:bqcx-1234567891011-12a3@gcp-sa-bigquery-condel.iam.gserviceaccount.com"
}

如要在 Google Cloud 專案中套用 Terraform 設定,請完成下列各節中的步驟。

準備 Cloud Shell

  1. 啟動 Cloud Shell
  2. 設定要套用 Terraform 設定的預設 Google Cloud 專案。

    您只需為每個專案執行這個指令一次,而且可以在任何目錄中執行。

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    如果您在 Terraform 設定檔中設定明確的值,系統就會覆寫環境變數。

準備目錄

每個 Terraform 設定檔都必須有自己的目錄 (也稱為根模組)。

  1. Cloud Shell 中建立目錄,並在該目錄中建立新檔案。檔案名稱必須包含 .tf 副檔名,例如 main.tf。在本教學課程中,檔案稱為 main.tf
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. 如果您正在參考教學課程,可以複製各個章節或步驟中的程式碼範例。

    將範例程式碼複製到新建立的 main.tf 中。

    您可以視需要從 GitHub 複製程式碼。如果 Terraform 程式碼片段是端對端解決方案的一部分,建議您採用這種做法。

  3. 查看並修改要套用至環境的範例參數。
  4. 儲存變更。
  5. 初始化 Terraform。這項操作只需對每個目錄執行一次。
    terraform init

    如要使用最新版的 Google 供應器,您可以選擇加入 -upgrade 選項:

    terraform init -upgrade

套用變更

  1. 檢查設定,確認 Terraform 要建立或更新的資源符合您的預期:
    terraform plan

    視需要修正設定。

  2. 執行下列指令,並在提示中輸入 yes,即可套用 Terraform 設定:
    terraform apply

    等待 Terraform 顯示「Apply complete!」(套用完成) 訊息。

  3. 開啟 Google Cloud 專案即可查看結果。在 Google Cloud 控制台中,前往 UI 中的資源,確認 Terraform 已建立或更新這些資源。

API

  1. 如要擷取目前的政策,請呼叫 tables.getIamPolicy 方法

  2. 編輯政策,新增成員或繫結,或同時新增兩者。如要瞭解政策所需的格式,請參閱「政策」參考主題。

  3. 呼叫 tables.setIamPolicy 以寫入更新的政策。

Go

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Go 設定說明進行操作。詳情請參閱 BigQuery Go API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

呼叫資源的 IAM().SetPolicy() 函式,即可儲存資料表或檢視表的存取權政策變更。
import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/bigquery"
	"cloud.google.com/go/iam"
)

// grantAccessToResource creates a new ACL conceding the VIEWER role to the group "example-analyst-group@google.com"
// For more information on the types of ACLs available see:
// https://cloud.google.com/storage/docs/access-control/lists
func grantAccessToResource(w io.Writer, projectID, datasetID, resourceID string) error {
	// Resource can be a table or a view
	//
	// TODO(developer): uncomment and update the following lines:
	// projectID := "my-project-id"
	// datasetID := "mydataset"
	// resourceID := "myresource"

	ctx := context.Background()

	// Create new client
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %w", err)
	}
	defer client.Close()

	// Get resource policy.
	policy, err := client.Dataset(datasetID).Table(resourceID).IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("bigquery.Dataset.Table.IAM.Policy: %w", err)
	}

	// Find more details about IAM Roles here:
	// https://pkg.go.dev/cloud.google.com/go/iam#RoleName
	entityID := "example-analyst-group@google.com"
	roleType := iam.Viewer

	// Add new policy.
	policy.Add(fmt.Sprintf("group:%s", entityID), roleType)

	// Update resource's policy.
	err = client.Dataset(datasetID).Table(resourceID).IAM().SetPolicy(ctx, policy)
	if err != nil {
		return fmt.Errorf("bigquery.Dataset.Table.IAM.Policy: %w", err)
	}

	// Get resource policy again expecting the update.
	policy, err = client.Dataset(datasetID).Table(resourceID).IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("bigquery.Dataset.Table.IAM.Policy: %w", err)
	}

	fmt.Fprintf(w, "Details for Access entries in table or view %v.\n", resourceID)

	for _, role := range policy.Roles() {
		fmt.Fprintln(w)
		fmt.Fprintf(w, "Role: %s\n", role)
		fmt.Fprintf(w, "Entities: %v\n", policy.Members(role))
	}

	return nil
}

Java

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Java 設定說明進行操作。詳情請參閱 BigQuery Java API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.cloud.Identity;
import com.google.cloud.Policy;
import com.google.cloud.Role;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.TableId;

public class GrantAccessToTableOrView {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    // Project, dataset and resource (table or view) from which to get the access policy.
    String projectId = "MY_PROJECT_ID";
    String datasetName = "MY_DATASET_NAME";
    String resourceName = "MY_TABLE_NAME";
    // Role to add to the policy access
    Role role = Role.of("roles/bigquery.dataViewer");
    // Identity to add to the policy access
    Identity identity = Identity.user("user-add@example.com");
    grantAccessToTableOrView(projectId, datasetName, resourceName, role, identity);
  }

  public static void grantAccessToTableOrView(
      String projectId, String datasetName, String resourceName, Role role, Identity identity) {
    try {
      // Initialize client that will be used to send requests. This client only needs
      // to be created once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      // Create table identity given the projectId, the datasetName and the resourceName.
      TableId tableId = TableId.of(projectId, datasetName, resourceName);

      // Add new user identity to current IAM policy.
      Policy policy = bigquery.getIamPolicy(tableId);
      policy = policy.toBuilder().addIdentity(role, identity).build();

      // Update the IAM policy by setting the new one.
      bigquery.setIamPolicy(tableId, policy);

      System.out.println("IAM policy of resource \"" + resourceName + "\" updated successfully");
    } catch (BigQueryException e) {
      System.out.println("IAM policy was not updated. \n" + e.toString());
    }
  }
}

Node.js

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Node.js 設定說明進行操作。詳情請參閱 BigQuery Node.js API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

請呼叫 Table#getIamPolicy() 函式,擷取資料表或檢視表的目前 IAM 政策,然後新增繫結來修改政策,再使用 Table#setIamPolicy() 函式儲存對存取權政策的變更。

/**
 * TODO(developer): Update and un-comment below lines
 */
// const projectId = "YOUR_PROJECT_ID";
// const datasetId = "YOUR_DATASET_ID";
// const tableId = "YOUR_TABLE_ID";
// const principalId = "YOUR_PRINCIPAL_ID";
// const role = "YOUR_ROLE";

const {BigQuery} = require('@google-cloud/bigquery');

// Instantiate a client.
const client = new BigQuery();

async function grantAccessToTableOrView() {
  const dataset = client.dataset(datasetId);
  const table = dataset.table(tableId);

  // Get the IAM access policy for the table or view.
  const [policy] = await table.getIamPolicy();

  // Initialize bindings array.
  if (!policy.bindings) {
    policy.bindings = [];
  }

  // To grant access to a table or view
  // add bindings to the Table or View policy.
  //
  // Find more details about Policy and Binding objects here:
  // https://cloud.google.com/security-command-center/docs/reference/rest/Shared.Types/Policy
  // https://cloud.google.com/security-command-center/docs/reference/rest/Shared.Types/Binding
  const binding = {
    role,
    members: [principalId],
  };
  policy.bindings.push(binding);

  // Set the IAM access policy with updated bindings.
  await table.setIamPolicy(policy);

  // Show a success message.
  console.log(
    `Role '${role}' granted for principal '${principalId}' on resource '${datasetId}.${tableId}'.`
  );
}

await grantAccessToTableOrView();

Python

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Python 設定說明進行操作。詳情請參閱 BigQuery Python API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

呼叫 client.set_iam_policy() 函式,即可儲存對資料表或檢視畫面存取權政策的變更。
from google.cloud import bigquery

# TODO(developer): Update and uncomment the lines below.

# Google Cloud Platform project.
# project_id = "my_project_id"

# Dataset where the table or view is.
# dataset_id = "my_dataset"

# Table or view name to get the access policy.
# resource_name = "my_table"

# Principal to grant access to a table or view.
# For more information about principal identifiers see:
# https://cloud.google.com/iam/docs/principal-identifiers
# principal_id = "user:bob@example.com"

# Role to grant to the principal.
# For more information about BigQuery roles see:
# https://cloud.google.com/bigquery/docs/access-control
# role = "roles/bigquery.dataViewer"

# Instantiate a client.
client = bigquery.Client()

# Get the full table or view name.
full_resource_name = f"{project_id}.{dataset_id}.{resource_name}"

# Get the IAM access policy for the table or view.
policy = client.get_iam_policy(full_resource_name)

# To grant access to a table or view, add bindings to the IAM policy.
#
# Find more details about Policy and Binding objects here:
# https://cloud.google.com/security-command-center/docs/reference/rest/Shared.Types/Policy
# https://cloud.google.com/security-command-center/docs/reference/rest/Shared.Types/Binding
binding = {
    "role": role,
    "members": [principal_id, ],
}
policy.bindings.append(binding)

# Set the IAM access policy with updated bindings.
updated_policy = client.set_iam_policy(full_resource_name, policy)

# Show a success message.
print(
    f"Role '{role}' granted for principal '{principal_id}'"
    f" on resource '{full_resource_name}'."
)

授予處理常式的存取權

如要針對這項功能提供意見回饋或尋求支援,請傳送電子郵件至 bq-govsec-eng@google.com

選取下列選項之一:

主控台

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在「Explorer」窗格中展開專案和資料集,然後選取要分享的日常安排。

  3. 按一下「分享」圖示

  4. 按一下 「新增成員」

  5. 在「新增成員」欄位中輸入主體。

  6. 在「選取角色」清單中,選取預先定義的角色或自訂角色。

  7. 按一下 [儲存]

  8. 如要返回日常安排資訊,請按一下「完成」

bq

  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. 如要將現有的例行工作資訊 (包括存取權控管設定) 寫入 JSON 檔案,請使用 bq get-iam-policy 指令

    bq get-iam-policy \
        PROJECT_ID:DATASET.ROUTINE \
        > PATH_TO_FILE

    更改下列內容:

    • PROJECT_ID:您的專案 ID
    • DATASET:包含要更新的常式資料集名稱
    • ROUTINE:要更新的資源名稱
    • PATH_TO_FILE:本機上 JSON 檔案的路徑
  3. 變更 JSON 檔案的 bindings 區段。繫結會將一或多個 members (或主體) 繫結至單一 role。主體可以是使用者帳戶、服務帳戶、Google 群組和網域。舉例來說,例行動作 JSON 檔案的 bindings 區段會如下所示:

    {
      "bindings": [
        {
          "role": "roles/bigquery.dataViewer",
          "members": [
            "user:izumi@example.com",
            "group:admins@example.com",
            "domain:google.com",
          ]
        },
      ],
      "etag": "BwWWja0YfJA=",
      "version": 1
    }
  4. 如要更新存取權政策,請使用 bq set-iam-policy 指令:

    bq set-iam-policy PROJECT_ID:DATASET.ROUTINE PATH_TO_FILE
  5. 如要驗證您的存取權控管變更,請再次使用 bq get-iam-policy 指令,但不要將資訊寫入檔案:

    bq get-iam-policy --format=prettyjson \\
        PROJECT_ID:DATASET.ROUTINE

API

  1. 如要擷取目前的政策,請呼叫 routines.getIamPolicy 方法

  2. 編輯政策,新增成員或繫結,或同時新增這兩者。如要瞭解政策所需的格式,請參閱「政策」參考主題。

  3. 呼叫 routines.setIamPolicy 以寫入更新的政策。

撤銷資源存取權

下列各節將說明如何撤銷不同資源的存取權。

撤銷資料集存取權

選取下列選項之一:

主控台

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在「Explorer」面板中展開專案並選取資料集。

  3. 在詳細資料面板中,依序點選「共用」>「權限」

  4. 在「Dataset Permissions」對話方塊中,展開您要撤銷存取權的主體。

  5. 按一下 「移除管理員」

  6. 在「Remove role from principal?」對話方塊中,按一下「Remove」

  7. 如要返回資料集詳細資料,請按一下「關閉」

SQL

如要移除實體的資料集存取權,請使用 REVOKE DCL 陳述式

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

    前往 BigQuery

  2. 在查詢編輯器中輸入以下陳述式:

    REVOKE `ROLE_LIST`
    ON SCHEMA RESOURCE_NAME
    FROM "USER_LIST"

    請依指示取代下列項目:

    • ROLE_LIST:您要撤銷的角色或以半形逗號分隔的角色清單
    • RESOURCE_NAME:您要撤銷權限的資源名稱
    • USER_LIST:以半形逗號分隔的清單,列出將撤銷角色的使用者

      如需有效格式的清單,請參閱 user_list

  3. 按一下 「Run」

如要進一步瞭解如何執行查詢,請參閱「執行互動式查詢」一文。

以下範例會撤銷資料集 myDataset 的「管理員」角色:

REVOKE `roles/bigquery.admin`
ON SCHEMA `myProject`.myDataset
FROM "group:example-team@example-pet-store.com", "serviceAccount:user@test-project.iam.gserviceaccount.com"

bq

  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. 如要將現有的資料集資訊 (包括存取權控管設定) 寫入 JSON 檔案,請使用 bq show 指令

    bq show \
        --format=prettyjson \
        PROJECT_ID:DATASET > PATH_TO_FILE

    更改下列內容:

    • PROJECT_ID:您的專案 ID
    • DATASET:資料集名稱
    • PATH_TO_FILE:本機上 JSON 檔案的路徑
  3. 變更 JSON 檔案的 access 區段。您可以移除任何 specialGroup 項目:projectOwnersprojectWritersprojectReadersallAuthenticatedUsers。您也可以移除下列任一項目:userByEmailgroupByEmaildomain

    舉例來說,資料集 JSON 檔案中的 access 區段會如下所示:

    {
     "access": [
      {
       "role": "READER",
       "specialGroup": "projectReaders"
      },
      {
       "role": "WRITER",
       "specialGroup": "projectWriters"
      },
      {
       "role": "OWNER",
       "specialGroup": "projectOwners"
      },
      {
       "role": "READER",
       "specialGroup": "allAuthenticatedUsers"
      },
      {
       "role": "READER",
       "domain": "domain_name"
      },
      {
       "role": "WRITER",
       "userByEmail": "user_email"
      },
      {
       "role": "READER",
       "groupByEmail": "group_email"
      }
     ],
     ...
    }
  4. 完成編輯後,請使用 bq update 指令並利用 --source 標記納入 JSON 檔案。如果資料集位於預設專案以外的專案中,請使用下列格式將專案 ID 新增至資料集名稱:PROJECT_ID:DATASET

      bq update 
    --source PATH_TO_FILE
    PROJECT_ID:DATASET

  5. 如要驗證您的存取權控管設定變更,請再次使用 show 指令,但不要將資訊寫入檔案:

    bq show --format=prettyjson PROJECT_ID:DATASET

API

呼叫 datasets.patch 並使用 Dataset 資源中的 access 屬性,即可更新存取權控管設定。

由於 datasets.update 方法會取代整個資料集的資源,因此建議您使用 datasets.patch 方法來更新存取權控管設定。

Go

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Go 設定說明進行操作。詳情請參閱 BigQuery Go API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

設定新的存取清單,方法是從現有清單中移除使用 DatasetMetadataToUpdate 類型 的項目。然後呼叫 dataset.Update() 函式來更新屬性。
import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/bigquery"
)

// revokeAccessToDataset creates a new ACL removing the dataset access to "example-analyst-group@google.com" entity
// For more information on the types of ACLs available see:
// https://cloud.google.com/storage/docs/access-control/lists
func revokeAccessToDataset(w io.Writer, projectID, datasetID, entity string) error {
	// TODO(developer): uncomment and update the following lines:
	// projectID := "my-project-id"
	// datasetID := "mydataset"
	// entity := "user@mydomain.com"

	ctx := context.Background()

	// Create BigQuery client.
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %w", err)
	}
	defer client.Close()

	// Get dataset handler
	dataset := client.Dataset(datasetID)

	// Get dataset metadata
	meta, err := dataset.Metadata(ctx)
	if err != nil {
		return err
	}

	// Create new access entry list by copying the existing and omiting the access entry entity value
	var newAccessList []*bigquery.AccessEntry
	for _, entry := range meta.Access {
		if entry.Entity != entity {
			newAccessList = append(newAccessList, entry)
		}
	}

	// Only proceed with update if something in the access list was removed.
	// Additionally, we use the ETag from the initial metadata to ensure no
	// other changes were made to the access list in the interim.
	if len(newAccessList) < len(meta.Access) {
		update := bigquery.DatasetMetadataToUpdate{
			Access: newAccessList,
		}
		meta, err = dataset.Update(ctx, update, meta.ETag)
		if err != nil {
			return err
		}
	} else {
		return fmt.Errorf("any access entry was revoked")
	}

	fmt.Fprintf(w, "Details for Access entries in dataset %v.\n", datasetID)

	for _, access := range meta.Access {
		fmt.Fprintln(w)
		fmt.Fprintf(w, "Role: %s\n", access.Role)
		fmt.Fprintf(w, "Entity: %v\n", access.Entity)
	}

	return nil
}

Java

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Java 設定說明進行操作。詳情請參閱 BigQuery Java API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。


import com.google.cloud.bigquery.Acl;
import com.google.cloud.bigquery.Acl.Entity;
import com.google.cloud.bigquery.Acl.Group;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.Dataset;
import com.google.cloud.bigquery.DatasetId;
import java.util.List;

public class RevokeDatasetAccess {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    // Project and dataset from which to get the access policy.
    String projectId = "MY_PROJECT_ID";
    String datasetName = "MY_DATASET_NAME";
    // Group to remove from the ACL
    String entityEmail = "group-to-remove@example.com";

    revokeDatasetAccess(projectId, datasetName, entityEmail);
  }

  public static void revokeDatasetAccess(String projectId, String datasetName, String entityEmail) {
    try {
      // Initialize client that will be used to send requests. This client only needs
      // to be created once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      // Create datasetId with the projectId and the datasetName.
      DatasetId datasetId = DatasetId.of(projectId, datasetName);
      Dataset dataset = bigquery.getDataset(datasetId);

      // Create a new Entity with the corresponding type and email
      // "user-or-group-to-remove@example.com"
      // For more information on the types of Entities available see:
      // https://cloud.google.com/java/docs/reference/google-cloud-bigquery/latest/com.google.cloud.bigquery.Acl.Entity
      // and
      // https://cloud.google.com/java/docs/reference/google-cloud-bigquery/latest/com.google.cloud.bigquery.Acl.Entity.Type
      Entity entity = new Group(entityEmail);

      // To revoke access to a dataset, remove elements from the Acl list.
      // Find more information about ACL and the Acl Class here:
      // https://cloud.google.com/storage/docs/access-control/lists
      // https://cloud.google.com/java/docs/reference/google-cloud-bigquery/latest/com.google.cloud.bigquery.Acl
      // Remove the entity from the ACLs list.
      List<Acl> acls =
          dataset.getAcl().stream().filter(acl -> !acl.getEntity().equals(entity)).toList();

      // Update the ACLs by setting the new list.
      bigquery.update(dataset.toBuilder().setAcl(acls).build());
      System.out.println("ACLs of \"" + datasetName + "\" updated successfully");
    } catch (BigQueryException e) {
      System.out.println("ACLs were not updated \n" + e.toString());
    }
  }
}

Node.js

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Node.js 設定說明進行操作。詳情請參閱 BigQuery Node.js API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

更新資料集存取清單,方法是使用 Dataset#get() 方法從現有清單中移除指定的項目,藉此擷取目前的中繼資料。修改存取權屬性以排除所需實體,然後呼叫 Dataset#setMetadata() 函式,套用更新後的存取權清單。

/**
 * TODO(developer): Update and un-comment below lines
 */

// const datasetId = "my_project_id.my_dataset"

// ID of the user or group from whom you are revoking access.
// const entityId = "user-or-group-to-remove@example.com"

const {BigQuery} = require('@google-cloud/bigquery');

// Instantiate a client.
const bigquery = new BigQuery();

async function revokeDatasetAccess() {
  const [dataset] = await bigquery.dataset(datasetId).get();

  // To revoke access to a dataset, remove elements from the access list.
  //
  // See the BigQuery client library documentation for more details on access entries:
  // https://cloud.google.com/nodejs/docs/reference/bigquery/latest

  // Filter access entries to exclude entries matching the specified entity_id
  // and assign a new list back to the access list.
  dataset.metadata.access = dataset.metadata.access.filter(entry => {
    return !(
      entry.entity_id === entityId ||
      entry.userByEmail === entityId ||
      entry.groupByEmail === entityId
    );
  });

  // Update will only succeed if the dataset
  // has not been modified externally since retrieval.
  //
  // See the BigQuery client library documentation for more details on metadata updates:
  // https://cloud.google.com/bigquery/docs/updating-datasets

  // Update just the 'access entries' property of the dataset.
  await dataset.setMetadata(dataset.metadata);

  console.log(`Revoked access to '${entityId}' from '${datasetId}'.`);
}

Python

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Python 設定說明進行操作。詳情請參閱 BigQuery Python API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

設定資料集的存取權控管,dataset.access_entries 屬性。然後呼叫 client.update_dataset() 函式來更新屬性。
from google.cloud import bigquery
from google.api_core.exceptions import PreconditionFailed

# TODO(developer): Update and uncomment the lines below.

# ID of the dataset to revoke access to.
# dataset_id = "my-project.my_dataset"

# ID of the user or group from whom you are revoking access.
# Alternatively, the JSON REST API representation of the entity,
# such as a view's table reference.
# entity_id = "user-or-group-to-remove@example.com"

# Instantiate a client.
client = bigquery.Client()

# Get a reference to the dataset.
dataset = client.get_dataset(dataset_id)

# To revoke access to a dataset, remove elements from the AccessEntry list.
#
# See the BigQuery client library documentation for more details on `access_entries`:
# https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.dataset.Dataset#google_cloud_bigquery_dataset_Dataset_access_entries

# Filter `access_entries` to exclude entries matching the specified entity_id
# and assign a new list back to the AccessEntry list.
dataset.access_entries = [
    entry for entry in dataset.access_entries
    if entry.entity_id != entity_id
]

# Update will only succeed if the dataset
# has not been modified externally since retrieval.
#
# See the BigQuery client library documentation for more details on `update_dataset`:
# https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.client.Client#google_cloud_bigquery_client_Client_update_dataset
try:
    # Update just the `access_entries` property of the dataset.
    dataset = client.update_dataset(
        dataset,
        ["access_entries"],
    )

    # Notify user that the API call was successful.
    full_dataset_id = f"{dataset.project}.{dataset.dataset_id}"
    print(f"Revoked dataset access for '{entity_id}' to ' dataset '{full_dataset_id}.'")
except PreconditionFailed:  # A read-modify-write error.
    print(
        f"Dataset '{dataset.dataset_id}' was modified remotely before this update. "
        "Fetch the latest version and retry."
    )

撤銷資料表或檢視表的存取權

選取下列選項之一:

主控台

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在「Explorer」面板中展開專案,然後選取資料表或檢視畫面。

  3. 在詳細資料面板中,按一下「分享」

  4. 在「Share」對話方塊中,展開您要撤銷存取權的主體。

  5. 按一下 「刪除」

  6. 在「Remove role from principal?」對話方塊中,按一下「Remove」

  7. 如要返回資料表或查看詳細資料,請按一下「關閉」

SQL

如要從主體移除對資料表或檢視表的存取權,請使用 REVOKE DCL 陳述式

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

    前往 BigQuery

  2. 在查詢編輯器中輸入以下陳述式:

    REVOKE `ROLE_LIST`
    ON RESOURCE_TYPE RESOURCE_NAME
    FROM "USER_LIST"

    請依指示取代下列項目:

    • ROLE_LIST:您要撤銷的角色或以半形逗號分隔的角色清單
    • RESOURCE_TYPE:從哪個資源中撤銷角色

      支援的值包括 TABLEVIEWMATERIALIZED VIEWEXTERNAL TABLE

    • RESOURCE_NAME:您要撤銷權限的資源名稱
    • USER_LIST:以半形逗號分隔的使用者清單,列出將撤銷角色的使用者

      如需有效格式的清單,請參閱 user_list

  3. 按一下 「Run」

如要進一步瞭解如何執行查詢,請參閱「執行互動式查詢」一文。

以下範例會撤銷資料表 myTable 的「管理員」角色:

REVOKE `roles/bigquery.admin`
ON TABLE `myProject`.myDataset.myTable
FROM "group:example-team@example-pet-store.com", "serviceAccount:user@test-project.iam.gserviceaccount.com"

bq

  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. 如要撤銷對資料表或檢視表的存取權,請使用 bq remove-iam-policy-binding 指令

    bq remove-iam-policy-binding --member=MEMBER_TYPE:MEMBER --role=ROLE
    --table=true RESOURCE

    更改下列內容:

    • MEMBER_TYPE:成員的類型,例如 usergroupserviceAccountdomain
    • MEMBER:成員的電子郵件地址或網域名稱。
    • ROLE:您要從成員身上撤銷的角色。
    • RESOURCE:要更新政策的資料表或檢視表名稱。

API

  1. 如要擷取目前的政策,請呼叫 tables.getIamPolicy 方法

  2. 編輯政策,移除成員或繫結 (或兩者皆移除)。如要瞭解政策所需的格式,請參閱「政策」參考主題。

  3. 呼叫 tables.setIamPolicy 以寫入更新的政策。

Go

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Go 設定說明進行操作。詳情請參閱 BigQuery Go API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

呼叫 policy.Remove() 函式,即可移除存取權。接著呼叫 IAM().SetPolicy() 函式,儲存資料表或檢視畫面的存取權政策變更。
import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/bigquery"
	"cloud.google.com/go/iam"
)

// revokeTableOrViewAccessPolicies creates a new ACL removing the VIEWER role to group "example-analyst-group@google.com"
// For more information on the types of ACLs available see:
// https://cloud.google.com/storage/docs/access-control/lists
func revokeTableOrViewAccessPolicies(w io.Writer, projectID, datasetID, resourceID string) error {
	// Resource can be a table or a view
	//
	// TODO(developer): uncomment and update the following lines:
	// projectID := "my-project-id"
	// datasetID := "mydataset"
	// resourceID := "myresource"

	ctx := context.Background()

	// Create new client
	client, err := bigquery.NewClient(ctx, projectID)
	if err != nil {
		return fmt.Errorf("bigquery.NewClient: %w", err)
	}
	defer client.Close()

	// Get resource policy.
	policy, err := client.Dataset(datasetID).Table(resourceID).IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("bigquery.Dataset.Table.IAM.Policy: %w", err)
	}

	// Find more details about IAM Roles here:
	// https://pkg.go.dev/cloud.google.com/go/iam#RoleName
	entityID := "example-analyst-group@google.com"
	roleType := iam.Viewer

	// Revoke policy access.
	policy.Remove(fmt.Sprintf("group:%s", entityID), roleType)

	// Update resource's policy.
	err = client.Dataset(datasetID).Table(resourceID).IAM().SetPolicy(ctx, policy)
	if err != nil {
		return fmt.Errorf("bigquery.Dataset.Table.IAM.Policy: %w", err)
	}

	// Get resource policy again expecting the update.
	policy, err = client.Dataset(datasetID).Table(resourceID).IAM().Policy(ctx)
	if err != nil {
		return fmt.Errorf("bigquery.Dataset.Table.IAM.Policy: %w", err)
	}

	fmt.Fprintf(w, "Details for Access entries in table or view %v.\n", resourceID)

	for _, role := range policy.Roles() {
		fmt.Fprintln(w)
		fmt.Fprintf(w, "Role: %s\n", role)
		fmt.Fprintf(w, "Entities: %v\n", policy.Members(role))
	}

	return nil
}

Java

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Java 設定說明進行操作。詳情請參閱 BigQuery Java API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

import com.google.cloud.Identity;
import com.google.cloud.Policy;
import com.google.cloud.Role;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.BigQueryOptions;
import com.google.cloud.bigquery.TableId;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class RevokeAccessToTableOrView {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    // Project, dataset and resource (table or view) from which to get the access policy
    String projectId = "MY_PROJECT_ID";
    String datasetName = "MY_DATASET_NAME";
    String resourceName = "MY_RESOURCE_NAME";
    // Role to remove from the access policy
    Role role = Role.of("roles/bigquery.dataViewer");
    // Identity to remove from the access policy
    Identity user = Identity.user("user-add@example.com");
    revokeAccessToTableOrView(projectId, datasetName, resourceName, role, user);
  }

  public static void revokeAccessToTableOrView(
      String projectId, String datasetName, String resourceName, Role role, Identity identity) {
    try {
      // Initialize client that will be used to send requests. This client only needs
      // to be created once, and can be reused for multiple requests.
      BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();

      // Create table identity given the projectId, the datasetName and the resourceName.
      TableId tableId = TableId.of(projectId, datasetName, resourceName);

      // Remove either identities or roles, or both from bindings and replace it in
      // the current IAM policy.
      Policy policy = bigquery.getIamPolicy(tableId);
      // Create a copy of an immutable map.
      Map<Role, Set<Identity>> bindings = new HashMap<>(policy.getBindings());

      // Remove all identities with a specific role.
      bindings.remove(role);
      // Update bindings.
      policy = policy.toBuilder().setBindings(bindings).build();

      // Remove one identity in all the existing roles.
      for (Role roleKey : bindings.keySet()) {
        if (bindings.get(roleKey).contains(identity)) {
          // Create a copy of an immutable set if the identity is present in the role.
          Set<Identity> identities = new HashSet<>(bindings.get(roleKey));
          // Remove identity.
          identities.remove(identity);
          bindings.put(roleKey, identities);
          if (bindings.get(roleKey).isEmpty()) {
            // Remove the role if it has no identities.
            bindings.remove(roleKey);
          }
        }
      }
      // Update bindings.
      policy = policy.toBuilder().setBindings(bindings).build();

      // Update the IAM policy by setting the new one.
      bigquery.setIamPolicy(tableId, policy);

      System.out.println("IAM policy of resource \"" + resourceName + "\" updated successfully");
    } catch (BigQueryException e) {
      System.out.println("IAM policy was not updated. \n" + e.toString());
    }
  }
}

Node.js

在嘗試這個範例之前,請先按照 BigQuery 快速入門:使用用戶端程式庫中的 Node.js 設定說明進行操作。詳情請參閱 BigQuery Node.js API 參考說明文件

如要向 BigQuery 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證機制」。

使用 Table#getIamPolicy() 方法,擷取資料表或檢視畫面的目前 IAM 政策。修改政策以移除所需角色或主體,然後使用 Table#setIamPolicy() 方法套用更新後的政策。

/**
 * TODO(developer): Update and un-comment below lines
 */
// const projectId = "YOUR_PROJECT_ID"
// const datasetId = "YOUR_DATASET_ID"
// const tableId = "YOUR_TABLE_ID"
// const roleToRemove = "YOUR_ROLE"
// const principalToRemove = "YOUR_PRINCIPAL_ID"

const {BigQuery} = require('@google-cloud/bigquery');

// Instantiate a client.
const client = new BigQuery();

async function revokeAccessToTableOrView() {
  const dataset = client.dataset(datasetId);
  const table = dataset.table(tableId);

  // Get the IAM access policy for the table or view.
  const [policy] = await table.getIamPolicy();

  // Initialize bindings array.
  if (!policy.bindings) {
    policy.bindings = [];
  }

  // To revoke access to a table or view,
  // remove bindings from the Table or View policy.
  //
  // Find more details about Policy objects here:
  // https://cloud.google.com/security-command-center/docs/reference/rest/Shared.Types/Policy

  if (principalToRemove) {
    // Create a copy of bindings for modifications.
    const bindings = [...policy.bindings];

    // Filter out the principal from each binding.
    for (const binding of bindings) {
      if (binding.members) {
        binding.members = binding.members.filter(
          m => m !== principalToRemove
        );
      }
    }

    // Filter out bindings with empty members.
    policy.bindings = bindings.filter(
      binding => binding.members && binding.members.length > 0
    );
  }

  if (roleToRemove) {
    // Filter out all bindings with the roleToRemove
    // and assign a new list back to the policy bindings.
    policy.bindings = policy.bindings.filter(b => b.role !== roleToRemove);
  }

  // Set the IAM access policy with updated bindings.
  await table.setIamPolicy(policy);

  // Both role and principal are removed
  if (roleToRemove !== null && principalToRemove !== null) {
    console.log(
      `Role '${roleToRemove}' revoked for principal '${principalToRemove}' on resource '${datasetId}.${tableId}'.`
    );
  }

  // Only role is removed
  if (roleToRemove !== null && principalToRemove === null) {
    console.log(
      `Role '${roleToRemove}' revoked for all principals on resource '${datasetId}.${tableId}'.`
    );
  }

  // Only principal is removed
  if (roleToRemove === null && principalToRemove !== null) {
    console.log(
      `Access revoked for principal '${principalToRemove}' on resource '${datasetId}.${tableId}'.`
    );
  }

  // No changes were made
  if (roleToRemove === null && principalToRemove === null) {
    console.log(
      `No changes made to access policy for '${datasetId}.${tableId}'.`
    );
  }
}

撤銷處理常式的存取權

如要針對這項功能提供意見回饋或尋求支援,請傳送電子郵件至 bq-govsec-eng@google.com

選取下列選項之一:

主控台

  1. 前往「BigQuery」頁面

    前往 BigQuery

  2. 在「Explorer」面板中展開專案,然後選取日常安排。

  3. 在詳細資料面板中,依序點選「共用」>「權限」

  4. 在「日常安排權限」對話方塊中,展開您要撤銷存取權的主體。

  5. 按一下 「移除管理員」

  6. 在「Remove role from principal?」對話方塊中,按一下「Remove」

  7. 按一下 [關閉]

bq

  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. 如要將現有的例行動作資訊 (包括存取權控管設定) 寫入 JSON 檔案,請使用 bq get-iam-policy 指令

    bq get-iam-policy --routine PROJECT_ID:DATASET.ROUTINE > PATH_TO_FILE

    更改下列內容:

    • PROJECT_ID:您的專案 ID
    • DATASET:包含要更新的例行程的資料集名稱
    • ROUTINE:要更新的資源名稱
    • PATH_TO_FILE:本機上 JSON 檔案的路徑

  3. 變更 JSON 檔案的 access 區段。您可以移除任何 specialGroup 項目:projectOwnersprojectWritersprojectReadersallAuthenticatedUsers。您也可以移除下列任一項目:userByEmailgroupByEmaildomain。舉例來說,日常生活的 JSON 檔案中 access 區段會如下所示:

    {
     "bindings": [
       {
         "role": "roles/bigquery.dataViewer",
         "members": [
           "user:izumi@example.com",
           "group:admins@example.com",
           "domain:google.com",
         ]
       },
     ],
     "etag": "BwWWja0YfJA=",
     "version": 1
    }

  4. 如要更新存取權政策,請使用 bq set-iam-policy 指令:

     bq set-iam-policy --routine PROJECT_ID:DATASET.ROUTINE PATH_TO_FILE

  5. 如要驗證您的存取權控管設定變更,請再次使用 get-iam-policy 指令,但不要將資訊寫入檔案:

    bq get-iam-policy --routine --format=prettyjson \
        PROJECT_ID:DATASET.ROUTINE

API

  1. 如要擷取目前的政策,請呼叫 routines.getIamPolicy 方法
  2. 編輯政策,新增成員或繫結,或同時新增兩者。如要瞭解政策所需的格式,請參閱「政策」參考主題。

拒絕存取資源

IAM 拒絕政策可讓您設定 BigQuery 資源存取權的安全防護措施。您可以定義拒絕規則,無論主體獲得何種角色,都能限制特定主體使用特定權限

如要瞭解如何建立、更新及刪除拒絕政策,請參閱「拒絕資源存取權」一文。

特殊情況

針對幾項 BigQuery 權限建立IAM 拒絕政策時,請考量以下情況:

  • 您可以存取已授權的資源 (檢視畫面處理常式資料集預存程序),建立刪除操控資料表,以及讀取及修改資料表資料,即使您沒有直接執行這些作業的權限也一樣。它也可以取得模型資料或中繼資料,並在基礎資料表上叫用其他儲存程序。這項功能表示授權資源具有下列權限:

    • bigquery.tables.get
    • bigquery.tables.list
    • bigquery.tables.getData
    • bigquery.tables.updateData
    • bigquery.tables.create
    • bigquery.tables.delete
    • bigquery.routines.get
    • bigquery.routines.list
    • bigquery.datasets.get
    • bigquery.models.getData
    • bigquery.models.getMetadata

    如要拒絕存取這些授權資源,請在建立拒絕政策時,將下列任一值新增至 deniedPrincipal 欄位:

    用途
    principalSet://goog/public:all 封鎖所有主體,包括已授權的資源。
    principalSet://bigquery.googleapis.com/projects/PROJECT_NUMBER/* 封鎖指定專案中的所有 BigQuery 授權資源。PROJECT_NUMBER 是系統為 INT64 類型專案自動產生的專屬 ID。
  • 如要將特定主體排除在拒絕政策之外,請在拒絕政策的 exceptionPrincipals 欄位中指定這些主體。例如:exceptionPrincipals: "principalSet://bigquery.googleapis.com/projects/1234/*"

  • BigQuery 會快取工作擁有者的查詢結果 24 小時,工作擁有者可以存取這些結果,而不需要在包含資料的資料表上擁有 bigquery.tables.getData 權限。因此,在 bigquery.tables.getData 權限中加入 IAM 拒絕政策,不會阻止工作擁有者存取快取結果,除非快取內容過期。如要封鎖工作擁有者存取快取結果的權限,請針對 bigquery.jobs.create 權限建立個別的拒絕政策。

  • 為避免在使用拒絕政策封鎖資料讀取作業時,發生非預期的資料存取行為,建議您一併檢查及撤銷資料集的任何現有訂閱項目。

  • 如要為查看資料集存取權控管建立身分與存取權管理拒絕政策,請拒絕下列權限:

    • bigquery.datasets.get
    • bigquery.datasets.getIamPolicy
  • 如要建立 IAM 拒絕政策來更新資料集存取權控管設定,請拒絕下列權限:

    • bigquery.datasets.update
    • bigquery.datasets.setIamPolicy

限制

  • 複製的日常生活程式中不包含日常生活程式存取控制清單 (ACL)。
  • 外部或已連結資料集內的例行程序不支援存取權控管。
  • 外部或已連結資料集內的資料表不支援存取控制項。
  • 無法使用 Terraform 設定日常安排存取權控管機制。
  • 您無法使用 Google Cloud SDK 設定例行存取控管機制。
  • 您無法使用 BigQuery 資料控管語言 (DCL) 設定例行存取權控管。
  • Data Catalog 不支援例行存取權控管。如果使用者已依條件授予例行工作層級存取權,就不會在 BigQuery 側邊面板中看到自己的例行工作。解決方法是改為授予資料集層級存取權。
  • OBJECT_PRIVILEGES 檢視畫面不會顯示例行存取權控管。

後續步驟

瞭解如何使用 projects.testIamPermissions 方法測試使用者對資源的存取權。