使用 IAM 控管資源的存取權

本文說明如何查看、授予及撤銷 BigQuery 資料集和資料集內資源 (資料表、檢視區塊和常式) 的存取權控管。雖然模型也是資料集層級的資源,但您無法使用 IAM 角色授予個別模型的存取權。

您可以透過 Google Cloud 允許政策,授予資源的存取權。這類政策又稱為 Identity and Access Management (IAM) 政策,會附加於資源。每項資源只能附加一項允許政策。 允許政策可控管資源本身的存取權,以及沿用允許政策的資源後代。

如要進一步瞭解允許政策,請參閱 IAM 說明文件中的「政策結構」。

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

限制

  • 複製的日常安排不會包含日常安排存取控管清單 (ACL)。
  • 外部或連結資料集中的常式不支援存取控制項。
  • 外部或連結資料集中的資料表不支援存取控制項。
  • 無法使用 Terraform 設定日常安排存取權控管。
  • 您無法使用 Google Cloud SDK 設定日常安排存取控管機制。
  • 您無法使用 BigQuery 資料控管語言 (DCL) 設定例行存取權控管機制。
  • Data Catalog 不支援例行存取控管。如果使用者獲得的常式層級存取權設有條件,就不會在 BigQuery 側邊面板中看到常式。如要解決這個問題,請改為授予資料集層級的存取權。
  • 「INFORMATION_SCHEMA.OBJECT_PRIVILEGES」檢視畫面不會顯示日常作業的存取權控管設定。

事前準備

授予身分與存取權管理 (IAM) 角色,讓使用者擁有執行本文各項工作所需的權限。

必要的角色

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

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

所需權限

如要修改資源的 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

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

使用資料集存取權控管

您可以授予 IAM 主體預先定義或自訂的角色,決定主體在資料集中的權限,藉此提供資料集存取權。這也稱為將允許政策附加至資源。授予存取權後,您就能查看資料集的存取控管機制,並撤銷資料集的存取權。

授予資料集存取權

使用 BigQuery 網頁版 UI 或 bq 指令列工具建立資料集時,無法授予資料集存取權。您必須先建立資料集,然後授予存取權。 您可以在建立資料集時呼叫 datasets.insert 方法,並定義 資料集資源,藉此授予存取權。

專案是資料集的父項資源,而資料集則是資料表、檢視區塊、常式和模型的父項資源。在專案層級授予角色時,資料集和資料集資源會沿用該角色及其權限。同樣地,在資料集層級授予角色時,資料集內的資源會繼承該角色及其權限。

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

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

控制台

  1. 前往「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」。

    特別標出的「Explorer」窗格按鈕。

    如果沒有看到左側窗格,請按一下 「Expand left pane」(展開左側窗格),開啟窗格。

  3. 在「Explorer」窗格中展開專案,按一下「Datasets」(資料集),然後選取資料集。

  4. 依序點選 「共用」>「權限」。

  5. 按一下「新增主體」。

  6. 在「New principals」(新增主體) 欄位中輸入主體。

  7. 在「Select a role」(選取角色) 清單中,選取預先定義的角色或自訂角色。

  8. 按一下 [儲存]。

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

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. 按一下「執行」。

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

下列範例會將 BigQuery 資料檢視者角色授予 myDataset:

GRANT `roles/bigquery.dataViewer`
ON SCHEMA `myProject`.myDataset
TO "user:user@example.com", "user:user2@example.com"

bq

  1. 在 Google Cloud 控制台中啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

  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 項目:projectOwners、projectWriters、projectReaders 和 allAuthenticatedUsers。你也可以新增下列任一項:userByEmail、groupByEmail 和 domain。

    舉例來說,資料集 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 檔案。如果資料集位於預設專案以外的專案,請按照「PROJECT_ID:DATASET」格式,在資料集名稱中加入專案 ID。

      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:user@example.com",
    ]
  }
  binding {
    role = "roles/bigquery.dataOwner"
    members = [
      "group:data.admin@example.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:user@example.com",
    "group:group@example.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:user@example.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."
    )

可授予資料集存取權的預先定義角色

您可以授予下列 IAM 預先定義的角色資料集存取權。

角色 說明
BigQuery 資料擁有者 (roles/bigquery.dataOwner) 在資料集上授予這個角色時,會授予下列權限:
  • 擁有資料集和資料集內所有資源的權限,包括資料表和檢視區塊、模型和常式。
BigQuery 資料編輯者 (roles/bigquery.dataEditor) 在資料集上授予這個角色時,會授予下列權限:
  • 取得資料集的中繼資料和權限。
  • 資料表和檢視畫面:
    • 建立、更新、取得、列出及刪除資料集的資料表和檢視區塊。
    • 讀取 (查詢)、匯出、複製及更新表格資料。
    • 建立、更新及刪除索引。
    • 建立及還原快照。
  • 具備資料集常式和模型的所有權限。
BigQuery 資料檢視者 (roles/bigquery.dataViewer) 在資料集上授予這個角色時,會授予下列權限:
  • 取得資料集的中繼資料和權限。
  • 列出資料集的資料表、檢視區塊和模型。
  • 取得資料集資料表和檢視表的中繼資料和存取權控管。
  • 讀取 (查詢)、複製及匯出資料表資料,並建立快照。
  • 列出及叫用資料集的處理常式。
BigQuery 中繼資料檢視器 (roles/bigquery.metadataViewer) 在資料集上授予這個角色時,會授予下列權限:
  • 取得資料集的相關中繼資料和存取控管機制。
  • 取得資料表和檢視表的中繼資料和存取權控管。
  • 從資料集的模型和常式取得中繼資料。
  • 列出資料集中的資料表、檢視區塊、模型和常式。

資料集權限

開頭為 bigquery.datasets 的權限大多適用於資料集層級。 bigquery.datasets.create 不會。如要建立資料集,必須在父項容器 (專案) 中,將 bigquery.datasets.create 權限授予角色。

下表列出資料集的全部權限,以及可套用權限的最低層級資源。

權限 資源 動作
bigquery.datasets.create 專案 在專案中建立新資料集。
bigquery.datasets.get 資料集 取得資料集的 metadata 和存取控管機制。在控制台中查看權限也需要 bigquery.datasets.getIamPolicy 權限。
bigquery.datasets.getIamPolicy 資料集 管理中心需要這項權限,才能授予使用者權限,取得資料集的存取控制項。失敗時維持開放狀態。此外,您還需要 bigquery.datasets.get 權限,才能在控制台中查看資料集。
bigquery.datasets.update 資料集 更新資料集的中繼資料和存取權控管。在控制台中更新存取控制項也需要 bigquery.datasets.setIamPolicy 權限。
bigquery.datasets.setIamPolicy 資料集 管理中心需要這項權限,才能授予使用者設定資料集存取控制項的權限。失敗時維持開放狀態。控制台也需要 bigquery.datasets.update 權限才能更新資料集。
bigquery.datasets.delete 資料集 刪除資料集。
bigquery.datasets.createTagBinding 資料集 將標記附加至資料集。
bigquery.datasets.deleteTagBinding 資料集 從資料集卸離標籤。
bigquery.datasets.listTagBindings 資料集 列出資料集的標記。
bigquery.datasets.listEffectiveTags 資料集 列出資料集的有效標記 (已套用和已沿用)。
bigquery.datasets.link 資料集 建立 連結的資料集。
bigquery.datasets.listSharedDatasetUsage 專案 列出您在專案中可存取的資料集共用資料集使用統計資料。如要查詢 INFORMATION_SCHEMA.SHARED_DATASET_USAGE 檢視區塊,必須具備這項權限。

查看資料集的存取權控管

您可以選擇下列任一選項,查看資料集明確設定的存取控管機制。如要查看繼承的角色,請使用 BigQuery 網頁介面。

控制台

  1. 前往「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」。

    特別標出的「Explorer」窗格按鈕。

  3. 在「Explorer」窗格中展開專案,按一下「Datasets」(資料集),然後選取資料集。

  4. 依序點選 「共用」>「權限」。

    資料集的存取權控管設定會顯示在「資料集權限」窗格中。

bq

  1. 在 Google Cloud 控制台中啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

  2. 如要取得現有政策並以 JSON 格式輸出至本機檔案,請在 Cloud Shell 中使用 bq show 指令:

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

    更改下列內容:

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

SQL

查詢 INFORMATION_SCHEMA.OBJECT_PRIVILEGES 檢視區塊。 如要查詢資料集的存取控管機制,必須指定 object_name。

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

    前往「BigQuery」

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

    SELECT
    COLUMN_LIST
    FROM
      PROJECT_ID.`region-REGION`.INFORMATION_SCHEMA.OBJECT_PRIVILEGES
    WHERE
    object_name = "DATASET";

    請替換下列項目:

  3. 按一下「執行」。

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

範例:

這項查詢會取得 mydataset 的存取權控管。

SELECT
object_name, privilege_type, grantee
FROM
my_project.`region-us`.INFORMATION_SCHEMA.OBJECT_PRIVILEGES
WHERE
object_name = "mydataset";

輸出內容應如下所示:

+------------------+-----------------------------+-------------------------+
|   object_name    |  privilege_type             | grantee                 |
+------------------+-----------------------------+-------------------------+
| mydataset        | roles/bigquery.dataOwner    | projectOwner:myproject  |
| mydataset        | roles/bigquery.dataViwer    | user:user@example.com   |
+------------------+-----------------------------+-------------------------+

API

如要查看資料集的存取控制項,請使用已定義的 dataset 資源呼叫 datasets.get 方法。

存取控制項會顯示在 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() 函式擷取資料集的中繼資料。 存取政策位於產生的中繼資料物件的存取權屬性中。 <x0A>

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

    特別標出的「Explorer」窗格按鈕。

  3. 在「Explorer」窗格中展開專案,按一下「Datasets」(資料集),然後選取資料集。

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

  5. 在「資料集權限」對話方塊中,展開要撤銷存取權的主體。

  6. 按一下「移除主體」。

  7. 在「要移除主體的角色嗎?」對話方塊中,按一下「移除」。

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

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. 按一下「執行」。

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

以下範例會撤銷 myDataset 的 BigQuery 資料擁有者角色:

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

bq

  1. 在 Google Cloud 控制台中啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

  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 項目:projectOwners、projectWriters、projectReaders 和 allAuthenticatedUsers。你也可以移除下列任一項目:userByEmail、groupByEmail 和 domain。

    舉例來說,資料集 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 檔案。如果資料集位於預設專案以外的專案,請按照「PROJECT_ID:DATASET」格式,在資料集名稱中加入專案 ID。

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

使用資料表和檢視權限存取控管

在 BigQuery 中,檢視畫面會視為資料表資源。您可以授予 IAM 主體預先定義或自訂的角色,決定主體可對資料表或檢視區塊執行的操作,藉此提供資料表或檢視區塊的存取權。這也稱為將允許政策附加至資源。授予存取權後,您可以查看資料表或檢視表的存取權控管機制,也可以撤銷資料表或檢視表的存取權。

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

如要進行精細的存取權控管,您可以對特定資料表或檢視區塊授予預先定義或自訂的 IAM 角色。資料表或檢視區塊也會沿用在資料集層級和更上層指定的存取控管機制。舉例來說,如果您授予主體資料集的 BigQuery 資料擁有者角色,該主體也會擁有資料集中資料表和檢視區塊的 BigQuery 資料擁有者權限。

如要授予表格或檢視畫面存取權,請選取下列其中一個選項:

控制台

  1. 前往「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」。

    特別標出的「Explorer」窗格按鈕。

  3. 在「Explorer」窗格中展開專案,按一下「Datasets」(資料集),然後選取資料集。

  4. 依序點選「總覽」>「資料表」,然後點選資料表或檢視畫面。

  5. 依序點選「共用」>「管理權限」。

  6. 按一下「新增主體」。

  7. 在「New principals」(新增主體) 欄位中輸入主體。

  8. 在「Select a role」(選取角色) 清單中,選取預先定義的角色或自訂角色。

  9. 按一下 [儲存]。

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

SQL

如要授予主體資料表或檢視區塊的存取權,請使用 GRANT DCL 陳述式:

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

    前往「BigQuery」

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

    GRANT `ROLE_LIST`
    ON RESOURCE_TYPE RESOURCE_NAME
    TO "USER_LIST"

    請替換下列項目:

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

      支援的值包括 TABLE、VIEW、MATERIALIZED VIEW 和 EXTERNAL TABLE。

    • RESOURCE_NAME:要授予權限的資源名稱
    • USER_LIST:以半形逗號分隔的使用者清單,這些使用者會獲得角色

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

  3. 按一下「執行」。

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

以下範例會授予 myTable 的 BigQuery 資料檢視者角色:

GRANT `roles/bigquery.dataViewer`
ON TABLE `myProject`.myDataset.myTable
TO "user:user@example.com", "user:user2@example.com"

bq

  1. 在 Google Cloud 控制台中啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

  2. 如要授予資料表或檢視表的存取權,請使用 bq add-iam-policy-binding 指令:

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

    更改下列內容:

    • MEMBER_TYPE:成員類型,例如 user、group、serviceAccount 或 domain。
    • 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:user@example.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:group@example.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}'."
)

可授予資料表和檢視畫面存取權的預先定義角色

在 BigQuery 中,檢視畫面會視為資料表資源。如要精細控管存取權,您可以對特定資料表或檢視畫面授予預先定義或自訂的 IAM 角色。資料表或檢視區塊也會沿用在資料集層級和更上層指定的存取控管機制。舉例來說,如果您授予主體資料集的 BigQuery 資料擁有者角色,該主體也會擁有資料集中資料表和檢視區塊的資料擁有者權限。

下列預先定義的 IAM 角色具有資料表或檢視區塊的權限。

角色 說明
BigQuery 資料擁有者 (roles/bigquery.dataOwner) 如果授予資料表或檢視畫面,這個角色會授予下列權限:
  • 資料表或檢視區塊的所有權限。
  • 除了覆寫時間回溯限制的權限外,資料列存取政策的所有權限。
  • 設定類別和資料欄層級資料政策。
BigQuery 資料編輯者 (roles/bigquery.dataEditor) 如果授予資料表或檢視畫面,這個角色會授予下列權限:
  • 取得中繼資料、更新中繼資料、取得存取控管,以及刪除資料表或檢視畫面。
  • 取得 (查詢)、匯出、複製及更新表格資料。
  • 建立、更新及刪除索引。
  • 建立及還原快照。
BigQuery 資料檢視者 (roles/bigquery.dataViewer) 如果授予資料表或檢視畫面,這個角色會授予下列權限:
  • 取得資料表或檢視區塊的中繼資料和存取控制項。
  • 取得 (查詢)、匯出及複製表格資料。
  • 建立快照。
BigQuery 中繼資料檢視器 (roles/bigquery.metadataViewer) 如果授予資料表或檢視畫面,這個角色會授予下列權限:
  • 取得資料表或檢視區塊的中繼資料和存取控制項。

資料表和檢視表的權限

在 BigQuery 中,檢視畫面會視為資料表資源。所有資料表層級的權限都適用於檢視畫面。

開頭為 bigquery.tables 的權限大多適用於資料表層級。 bigquery.tables.create 和 bigquery.tables.list。如要建立及列出資料表或檢視區塊,必須在父項容器 (資料集或專案) 中,將 bigquery.tables.create 和 bigquery.tables.list 權限授予角色。

下表列出資料表和檢視區塊的所有權限,以及可授予權限的最低層級資源。

權限 資源 動作
bigquery.tables.create 資料集 在資料集中建立新資料表。
bigquery.tables.createIndex 資料表 在資料表上建立搜尋索引。
bigquery.tables.deleteIndex 資料表 刪除資料表的搜尋索引。
bigquery.tables.createSnapshot 資料表 建立資料表快照。如要建立快照,您必須在資料表和資料集層級具備多項額外權限。詳情請參閱「權限和角色」一文,瞭解如何建立表格快照。
bigquery.tables.deleteSnapshot 資料表 刪除表格快照。
bigquery.tables.delete 資料表 刪除資料表。
bigquery.tables.createTagBinding 資料表 在資料表上建立資源標記繫結。
bigquery.tables.deleteTagBinding 資料表 刪除資料表中的資源標記繫結。
bigquery.tables.listTagBindings 資料表 在表格中列出資源標籤繫結。
bigquery.tables.listEffectiveTags 資料表 資料表的有效標記清單 (已套用和已繼承)。
bigquery.tables.export 資料表 匯出表格資料。執行擷取作業也需要 bigquery.jobs.create 權限。
bigquery.tables.get 資料表 取得資料表的中繼資料。
bigquery.tables.getData 資料表 查詢資料表資料。執行查詢工作也需要 bigquery.jobs.create 權限。
bigquery.tables.getIamPolicy 資料表 取得表格的存取控制項。
bigquery.tables.list 資料集 列出資料集中的所有資料表和資料表的中繼資料。
bigquery.tables.replicateData 資料表 複製資料表資料。建立 materialized view 副本時,必須具備這項權限。
bigquery.tables.restoreSnapshot 資料表 還原資料表快照。
bigquery.tables.setCategory 資料表 在資料表的結構定義中設定政策標記。
bigquery.tables.setColumnDataPolicy 資料表 在資料表上設定資料欄層級的存取權政策。
bigquery.tables.setIamPolicy 資料表 設定表格的存取控管機制。
bigquery.tables.update 資料表 更新表格。metadata. bigquery.tables.get也必須在控制台中更新資料表的中繼資料。
bigquery.tables.updateData 資料表 更新資料表資料。
bigquery.tables.updateIndex 資料表 更新資料表的搜尋索引。

查看資料表或檢視區塊的存取權控管

如要查看資料表或檢視區塊的存取控制項,請選擇下列其中一個選項:

控制台

  1. 前往「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」。

    特別標出的「Explorer」窗格按鈕。

  3. 在「Explorer」窗格中展開專案,按一下「Datasets」(資料集),然後選取資料集。

  4. 依序點選「總覽」>「資料表」,然後點選資料表或檢視畫面。

  5. 按一下「分享」圖示 。

    表格或檢視權限控制項會顯示在「共用」窗格中。

bq

  1. 在 Google Cloud 控制台中啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

  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 檔案的路徑

SQL

查詢 INFORMATION_SCHEMA.OBJECT_PRIVILEGES 檢視區塊。 如要擷取資料表或檢視表的存取控制項,查詢必須指定 object_schema 和 object_name。

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

    前往「BigQuery」

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

    SELECT
    COLUMN_LIST
    FROM
      PROJECT_ID.`region-REGION`.INFORMATION_SCHEMA.OBJECT_PRIVILEGES
    WHERE
    object_schema = "DATASET" AND object_name = "TABLE";

    請替換下列項目:

  3. 按一下「執行」。

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

範例:

SELECT
object_name, privilege_type, grantee
FROM
my_project.`region-us`.INFORMATION_SCHEMA.OBJECT_PRIVILEGES
WHERE
object_schema = "mydataset" AND object_name = "mytable";
+------------------+-----------------------------+--------------------------+
|   object_name    |  privilege_type             | grantee                  |
+------------------+-----------------------------+--------------------------+
| mytable          | roles/bigquery.dataEditor   | group:group@example.com|
| mytable          | roles/bigquery.dataOwner    | user:user@example.com|
+------------------+-----------------------------+--------------------------+

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() 函式,擷取資料表或檢視區塊的 IAM 政策。 存取權政策詳細資料會顯示在傳回的政策物件中。

/**
 * 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}`);
}

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

如要撤銷資料表或檢視表的存取權,請選取下列其中一個選項:

控制台

  1. 前往「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」。

    特別標出的「Explorer」窗格按鈕。

  3. 在「Explorer」窗格中展開專案,按一下「Datasets」(資料集),然後選取資料集。

  4. 依序點選「總覽」>「資料表」,然後點選資料表或檢視畫面。

  5. 在詳細資料窗格中,依序點選「共用」>「管理權限」。

  6. 在「共用」對話方塊中,展開要撤銷存取權的主體。

  7. 按一下「刪除」圖示 。

  8. 在「要移除主體的角色嗎?」對話方塊中,按一下「移除」。

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

SQL

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

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

    前往「BigQuery」

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

    REVOKE `ROLE_LIST`
    ON RESOURCE_TYPE RESOURCE_NAME
    FROM "USER_LIST"

    請替換下列項目:

    • ROLE_LIST:要撤銷的角色或以半形逗號分隔的角色清單
    • RESOURCE_TYPE:角色遭撤銷的資源類型

      支援的值包括 TABLE、VIEW、MATERIALIZED VIEW 和 EXTERNAL TABLE。

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

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

  3. 按一下「執行」。

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

以下範例會撤銷 myTable 的 BigQuery 資料擁有者角色:

REVOKE `roles/bigquery.dataOwner`
ON TABLE `myProject`.myDataset.myTable
FROM "group:group@example.com", "serviceAccount:user@myproject.iam.gserviceaccount.com"

bq

  1. 在 Google Cloud 控制台中啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

  2. 如要撤銷資料表或檢視表的存取權,請使用 bq remove-iam-policy-binding 指令:

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

    更改下列內容:

    • MEMBER_TYPE:成員類型,例如 user、group、serviceAccount 或 domain
    • 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}'.`
    );
  }
}

使用日常作業的存取權控管機制

如要提供意見回饋或尋求這項功能的支援,請傳送電子郵件至 bigquery-security@google.com。

您可以將預先定義或自訂的角色授予 IAM 主體,藉此提供日常安排的存取權,並決定主體可對日常安排執行的動作。這也稱為將允許政策附加至資源。授予存取權後,你可以查看日常作業的存取控管設定,並撤銷日常作業的存取權。

授予存取捷徑的權限

如要進行精細的存取權控管,您可以授予特定日常安排預先定義或自訂的 IAM 角色。這項常式也會沿用在資料集層級以上指定的存取控制項。舉例來說,如果您授予主體資料集的 BigQuery 資料擁有者角色,該主體也會擁有資料集中常式的資料擁有者權限。

選取下列選項之一:

控制台

  1. 前往「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」。

    特別標出的「Explorer」窗格按鈕。

  3. 在「Explorer」窗格中展開專案,按一下「Datasets」(資料集),然後選取資料集。

  4. 前往「日常安排」分頁,然後按一下所需日常安排。

  5. 按一下「分享」圖示 。

  6. 按一下「新增成員」。

  7. 在「New members」(新增成員) 欄位中輸入主體。

  8. 在「Select a role」(選取角色) 清單中,選取預先定義的角色或自訂角色。

  9. 按一下 [儲存]。

  10. 如要返回常式資訊,請按一下「完成」。

bq

  1. 在 Google Cloud 控制台中啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

  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 區段。繫結會將一或多個主體繫結至單一 role。主體可以是使用者帳戶、服務帳戶、Google 群組和網域。舉例來說,常式 JSON 檔案的 bindings 區段如下所示:

    {
      "bindings": [
        {
          "role": "roles/bigquery.dataViewer",
          "members": [
            "user:user@example.com",
            "group:group@example.com",
            "domain:example.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 ,寫入更新後的政策。

授予存取常式權限的預先定義角色

如要進行精細的存取權控管,您可以授予特定日常安排預先定義或自訂的 IAM 角色。這項常式也會沿用在資料集層級以上指定的存取控制項。舉例來說,如果您將資料集中的「資料擁有者」角色授予主體,該主體也會透過繼承,取得資料集中常式的「資料擁有者」權限。

下列預先定義的 IAM 角色具有常式權限。

角色 說明
BigQuery 資料擁有者 (roles/bigquery.dataOwner) 如果授予給日常安排,這個角色會授予下列權限:
  • 具備所有日常作業相關權限。

請勿在例行程序層級授予資料擁有者角色。資料編輯者也會獲得所有例行程序權限,但權限較少。

BigQuery 資料編輯者 (roles/bigquery.dataEditor) 如果授予給日常安排,這個角色會授予下列權限:
  • 具備所有日常作業相關權限。
BigQuery 資料檢視者 (roles/bigquery.dataViewer) 如果授予給日常安排,這個角色會授予下列權限:
  • 在查詢中,參照他人建立的常式。
BigQuery 中繼資料檢視器 (roles/bigquery.metadataViewer) 如果授予給日常安排,這個角色會授予下列權限:
  • 在查詢中,參照他人建立的常式。

處理常式權限

開頭為 bigquery.routines 的權限大多適用於日常安排層級。 bigquery.routines.create 和 bigquery.routines.list。如要建立及列出常式,必須在父項容器 (資料集) 中,將 bigquery.routines.create 和 bigquery.routines.list 權限授予角色。

下表列出所有日常作業的權限,以及可授予權限的最低層級資源。

權限 資源 說明
bigquery.routines.create 資料集 在資料集中建立常式。如要執行包含 CREATE FUNCTION 陳述式的工作,也需要這項權限。bigquery.jobs.create
bigquery.routines.delete 處理常式 刪除日常安排。
bigquery.routines.get 處理常式 參考他人建立的日常安排。如要執行參照常式的查詢作業,您也需要 bigquery.jobs.create 權限,且必須有權存取常式參照的任何資源,例如資料表或檢視區塊。
bigquery.routines.list 資料集 列出資料集中的常式,並顯示常式的中繼資料。
bigquery.routines.update 處理常式 更新處理常式定義和中繼資料。
bigquery.routines.getIamPolicy 處理常式 取得日常作業的存取控制項。
bigquery.routines.setIamPolicy 處理常式 設定日常作業的存取控管機制。

查看日常安排的存取權控管機制

如要查看日常作業的存取控制項,請選擇下列任一做法:

控制台

  1. 前往「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」。

    特別標出的「Explorer」窗格按鈕。

  3. 在「Explorer」窗格中展開專案,按一下「Datasets」(資料集),然後選取資料集。

  4. 前往「日常安排」分頁,然後按一下所需日常安排。

  5. 按一下「分享」圖示 。

    例行事項的存取權控管選項會顯示在「共用」窗格中。

bq

bq get-iam-policy 指令不支援查看日常作業的存取權控管設定。

SQL

「INFORMATION_SCHEMA.OBJECT_PRIVILEGES」檢視畫面不會顯示日常作業的存取權控管設定。

API

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

撤銷日常安排的存取權

如要撤銷常式存取權,請選取下列其中一個選項:

控制台

  1. 前往「BigQuery」頁面。

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」。

    特別標出的「Explorer」窗格按鈕。

  3. 在「Explorer」窗格中展開專案,按一下「Datasets」(資料集),然後選取資料集。

  4. 前往「日常安排」分頁,然後按一下所需日常安排。

  5. 在詳細資料窗格中,依序點選「共用」>「權限」。

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

  7. 按一下「移除主體」。

  8. 在「要移除主體的角色嗎?」對話方塊中,按一下「移除」。

  9. 按一下 [關閉]。

�

bq

  1. 在 Google Cloud 控制台中啟用 Cloud Shell。

    啟用 Cloud Shell

    Google Cloud 控制台底部會開啟 Cloud Shell 工作階段,並顯示指令列提示。Cloud Shell 是已安裝 Google Cloud CLI 的殼層環境,並已設定適用於您目前專案的值。工作階段可能要幾秒鐘的時間才能初始化。

  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 檔案的路徑

    在政策檔案中,version 的值仍為 1。這個數字是指 IAM 政策結構定義版本,而非政策版本。etag 值是政策版本號碼。

  3. 變更 JSON 檔案的 access 區段。您可以移除任何 specialGroup 項目:projectOwners、projectWriters、projectReaders 和 allAuthenticatedUsers。您也可以移除下列任一項目:userByEmail、groupByEmail 和 domain。

    舉例來說,例行事項 JSON 檔案的 access 區段如下所示:

    {
     "bindings": [
       {
         "role": "roles/bigquery.dataViewer",
         "members": [
           "user:user@example.com",
           "group:group@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. 編輯政策,新增主體或繫結,或兩者皆新增。 如要瞭解政策的必要格式,請參閱「政策」參考主題。

查看資源的繼承存取控管

您可以使用 BigQuery 網頁介面,檢查資源的 IAM 角色繼承情形。您必須具備適當的權限,才能在控制台中查看繼承設定。如要檢查資料集、資料表、檢視區塊或常式的繼承項目,請按照下列步驟操作:

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

    前往「BigQuery」

  2. 點選左側窗格中的 「Explorer」。

    特別標出的「Explorer」窗格按鈕。

  3. 在「Explorer」窗格中展開專案,點選「資料集」,然後選取資料集,或選取資料集中的資料表、檢視區塊或常式。

  4. 依序點選「共用」>「管理權限」。

  5. 確認已啟用「在表格中顯示繼承的角色」選項。

    控制台中的「在表格顯示繼承的角色」選項

  6. 展開表格中的角色。

  7. 在「繼承」欄中,六邊形圖示會指出角色是否繼承自父項資源。

    「繼承自父項資源」圖示

拒絕存取資源

IAM 拒絕政策可讓您設定 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 封鎖所有主體,包括 BigQuery 資源。
    principalSet://bigquery.googleapis.com/projects/PROJECT_NUMBER/* 封鎖指定專案中的所有 BigQuery 授權資源。PROJECT_NUMBER 是系統自動為 INT64 類型專案產生的專屬 ID。

    如要查看允許的主體清單,請參閱「拒絕政策的主體 ID」。

  • 檢視授權是在資料集層級授予。因此,如果對資料集中的特定資料表套用 IAM 拒絕政策,使用者仍可透過授權 view 查詢該資料表。如要封鎖存取權,請在資料集層級套用標記,拒絕資料集中的所有資料表檢視權限。

  • 如要從拒絕政策中排除特定資源 (主體),請在拒絕政策的 exceptionPrincipals 欄位中指定這些主體。您可以免除指定專案中的所有資源。

    如要指定目標資源,請使用下列格式:

    格式 說明
    principalSet://bigquery.googleapis.com/projects/PROJECT_NUMBER/* 免除指定專案中的所有資源。

    更改下列內容:

  • BigQuery 會將工作擁有者的查詢結果快取 24 小時,工作擁有者可存取這些結果,不必具備含有資料的資料表 bigquery.tables.getData 權限。因此,在 bigquery.tables.getData 權限中新增 IAM 拒絕政策後,系統不會封鎖作業擁有者存取快取結果,直到快取過期為止。如要禁止作業擁有者存取快取結果,請在 bigquery.jobs.create 權限中建立個別的拒絕政策。

  • 使用拒絕政策封鎖資料讀取作業時,為避免資料遭到未經授權的存取,建議您一併檢查並撤銷資料集上的所有現有訂閱項目。

  • 如要建立 IAM 拒絕政策,禁止使用者查看資料集存取權控管,請拒絕下列權限:

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

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

後續步驟

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