IAM を使用してリソースへのアクセスを制御

このドキュメントでは、リソースの現在のアクセス ポリシーを表示する方法、リソースにアクセス権を付与する方法、そしてリソースへのアクセス権を取り消す方法について説明します。

このドキュメントは、 Google Cloudの Identity and Access Management(IAM)システムに関する知識があることを前提としています。

必要なロール

リソースの IAM ポリシーを変更するために必要な権限を取得するには、プロジェクトに対する BigQuery データオーナーroles/bigquery.dataOwner)IAM ロールを付与するよう管理者に依頼してください。ロールの付与については、プロジェクト、フォルダ、組織へのアクセス権の管理をご覧ください。

この事前定義ロールには、リソースの IAM ポリシーを変更するために必要な権限が含まれています。必要とされる正確な権限については、「必要な権限」セクションを開いてご確認ください。

必要な権限

リソースの IAM ポリシーを変更するには、次の権限が必要です。

  • データセットのアクセス ポリシーを取得するには: bigquery.datasets.get
  • データセットのアクセス ポリシーを設定するには: bigquery.datasets.update
  • データセットのアクセス ポリシーを取得するには(Google Cloud コンソールのみ): bigquery.datasets.getIamPolicy
  • データセットのアクセス ポリシーを設定するには(コンソールのみ): bigquery.datasets.setIamPolicy
  • テーブルまたはビューのポリシーを取得するには: bigquery.tables.getIamPolicy
  • テーブルまたはビューのポリシーを設定するには: bigquery.tables.setIamPolicy
  • bq ツールまたは SQL BigQuery ジョブ(省略可)を作成するには: bigquery.jobs.create

カスタムロールや他の事前定義ロールを使用して、これらの権限を取得することもできます。

リソースのアクセス ポリシーを表示する

以降のセクションでは、さまざまなリソースのアクセス ポリシーを表示する方法について説明します。

データセットのアクセス ポリシーを表示する

次のオプションのいずれかを選択します。

コンソール

  1. [BigQuery] ページに移動します。

    [BigQuery] に移動

  2. [エクスプローラ] ペインでプロジェクトを開いて、データセットを選択します。

  3. [共有] > [権限] の順にクリックします。

    データセットのアクセス ポリシーが [データセットの権限] ペインに表示されます。

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

データセットのアクセス ポリシーを表示するには、定義済みの 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() 関数を使用して、データセットのメタデータを取得します。アクセス ポリシーは、生成されたメタデータ オブジェクトのアクセス プロパティで使用できます。

/**
 * 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. [エクスプローラ] ペインでプロジェクトを開き、テーブルまたはビューを選択します。

  3. [共有] をクリックします。

    テーブルまたはビューのアクセス ポリシーが [共有] ペインに表示されます。

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() 関数を使用して、テーブルまたはビューの 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}`);
}

Python

このサンプルを試す前に、クライアント ライブラリを使用した BigQuery クイックスタートにある Python の設定手順を完了してください。詳細については、BigQuery Python API のリファレンス ドキュメントをご覧ください。

BigQuery に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証情報を設定するをご覧ください。

client.get_iam_policy() 関数を呼び出して、テーブルまたはビューのアクセス ポリシーを取得します。

full_resource_id 引数は、project_id.dataset_id.table_id 形式の文字列にする必要があります。

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

# Table or view from which to get the access policy.
# resource_id = "my_table_id"

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

# Get the full table or view id.
full_resource_id = f"{project_id}.{dataset_id}.{resource_id}"

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

# Show policy details.
# Find more details for the Policy object here:
# https://cloud.google.com/bigquery/docs/reference/rest/v2/Policy
print(f"Access Policy details for table or view '{resource_id}'.")
print(f"Bindings: {policy.bindings}")
print(f"etag: {policy.etag}")
print(f"Version: {policy.version}")

リソースへのアクセス権を付与する

以降のセクションでは、さまざまなリソースへのアクセス権を付与する方法について説明します。

データセットへのアクセス権を付与する

Google Cloud コンソールまたは bq コマンドライン ツールを使用してデータセットを作成するときに、データセットへのアクセス権を付与することはできません。まずデータセットを作成してから、データセットへのアクセス権を付与する必要があります。この API では、定義済みのデータセット リソースを使用して datasets.insert メソッドを呼び出すことで、データセットの作成時にアクセス権を付与できます。

データセットへのアクセス権を付与するには、IAM プリンシパルに、プリンシパルがデータセットに対して実行できる操作を決定するロールを付与します。

IAM 条件を使用して、データセットへのアクセス権を付与することもできます。データセットへの条件付きアクセス権の付与の詳細については、IAM Conditions によるアクセス制御をご覧ください。

条件を使用せずに IAM ロールにデータセットへのアクセス権を付与するには、次のいずれかのオプションを選択します。

コンソール

  1. [BigQuery] ページに移動します。

    [BigQuery] に移動

  2. [エクスプローラ] ペインでプロジェクトを開き、共有するデータセットを選択します。

  3. [共有] > [権限] の順にクリックします。

  4. [ プリンシパルを追加] をクリックします。

  5. [新しいプリンシパル] フィールドに、プリンシパルを入力します。

  6. [ロールを選択] リストで、事前定義ロールまたはカスタムロールを選択します。

  7. [保存] をクリックします。

  8. データセット情報に戻るには、[閉じる] をクリックします。

SQL

プリンシパルにデータセットへのアクセス権を付与するには、GRANT DCL ステートメントを使用します。

  1. Google Cloud コンソールで [BigQuery Studio] ページに移動します。

    [BigQuery Studio] に移動

  2. クエリエディタで次のステートメントを入力します。

    GRANT `ROLE_LIST`
    ON SCHEMA RESOURCE_NAME
    TO "USER_LIST"

    次のように置き換えます。

    • ROLE_LIST: 付与するロールまたはカンマ区切りのロールのリスト
    • RESOURCE_NAME: 権限を付与するリソースの名前
    • USER_LIST: ロールが付与されているユーザーのカンマ区切りのリスト

      有効な形式の一覧については、user_list をご覧ください。

  3. [実行] をクリックします。

クエリの実行方法については、インタラクティブ クエリを実行するをご覧ください。

次の例では、データセット myDataset に対するデータ閲覧者のロールを付与します。

GRANT `roles/bigquery.dataViewer`
ON SCHEMA `myProject`.myDataset
TO "user:[email protected]", "user:[email protected]"

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 ファイルを指定します。データセットがデフォルト プロジェクト以外のプロジェクトにある場合は、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:[email protected]",
    ]
  }
  binding {
    role = "roles/bigquery.dataOwner"
    members = [
      "group:[email protected]",
    ]
  }
  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:[email protected]",
    "group:[email protected]"
  ]
}

単一のプリンシパルのロール メンバーシップを設定する

次の例は、単一のプリンシパルにロールを付与するために、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:[email protected]"
}

Google Cloud プロジェクトで Terraform 構成を適用するには、次のセクションの手順を行います。

Cloud Shell を準備する

  1. Cloud Shell を起動します。
  2. Terraform 構成を適用するデフォルトの Google Cloud プロジェクトを設定します。

    このコマンドは、プロジェクトごとに 1 回だけ実行する必要があります。これは任意のディレクトリで実行できます。

    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 を初期化します。これは、ディレクトリごとに 1 回だけ行います。
    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 "[email protected]"
// 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 := "[email protected]"
	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 = "[email protected]";

    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
      // "[email protected]"
      // 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
      // "[email protected]"
      // 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 = "[email protected]";

// 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 = "[email protected]"

# 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. [エクスプローラ] ペインでプロジェクトを開き、共有するテーブルまたはビューを選択します。

  3. [共有] をクリックします。

  4. [ プリンシパルを追加] をクリックします。

  5. [新しいプリンシパル] フィールドに、プリンシパルを入力します。

  6. [ロールを選択] リストで、事前定義ロールまたはカスタムロールを選択します。

  7. [保存] をクリックします。

  8. テーブルまたはビューの詳細に戻るには、[閉じる] をクリックします。

SQL

プリンシパルにテーブルまたはビューへのアクセス権を付与するには、GRANT DCL ステートメントを使用します。

  1. Google Cloud コンソールで [BigQuery Studio] ページに移動します。

    [BigQuery Studio] に移動

  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. [実行] をクリックします。

クエリの実行方法については、インタラクティブ クエリを実行するをご覧ください。

次の例では、テーブル myTable に対するデータ閲覧者のロールを付与します。

GRANT `roles/bigquery.dataViewer`
ON TABLE `myProject`.myDataset.myTable
TO "user:[email protected]", "user:[email protected]"

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:[email protected]",
    ]
  }
}

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:[email protected]",
  ]
}

単一のプリンシパルのロール メンバーシップを設定する

次の例は、mytable テーブルの IAM ポリシーを更新し、1 つのプリンシパルにロールを付与するための、google_bigquery_table_iam_member リソースの使用方法を示しています。この 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 プロジェクトを設定します。

    このコマンドは、プロジェクトごとに 1 回だけ実行する必要があります。これは任意のディレクトリで実行できます。

    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 を初期化します。これは、ディレクトリごとに 1 回だけ行います。
    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 "[email protected]"
// 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 := "[email protected]"
	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("[email protected]");
    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:[email protected]"

# 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}'."
)

リソースに対するアクセス権の取り消し

以降のセクションでは、さまざまなリソースへのアクセス権を取り消す方法について説明します。

データセットに対するアクセス権の取り消し

次のオプションのいずれかを選択します。

コンソール

  1. [BigQuery] ページに移動します。

    [BigQuery] に移動

  2. [エクスプローラ] パネルでプロジェクトを開いて、データセットを選択します。

  3. 詳細パネルで、[共有 > 権限] をクリックします。

  4. [データセットの権限] ダイアログで、アクセス権を取り消すプリンシパルを開きます。

  5. [ プリンシパルを削除] をクリックします。

  6. [プリンシパルからロールを削除しますか?] ダイアログで、[削除] をクリックします。

  7. データセットの詳細に戻るには、[閉じる] をクリックします。

SQL

プリンシパルからデータセットへのアクセス権を削除するには、REVOKE DCL ステートメントを使用します。

  1. Google Cloud コンソールで [BigQuery Studio] ページに移動します。

    [BigQuery Studio] に移動

  2. クエリエディタで次のステートメントを入力します。

    REVOKE `ROLE_LIST`
    ON SCHEMA RESOURCE_NAME
    FROM "USER_LIST"

    次のように置き換えます。

    • ROLE_LIST: 取り消すロールまたはカンマ区切りのロールのリスト
    • RESOURCE_NAME: 権限を取り消すリソースの名前
    • USER_LIST: ロールが取り消されるユーザーのカンマ区切りのリスト

      有効な形式の一覧については、user_list をご覧ください。

  3. [実行] をクリックします。

クエリの実行方法については、インタラクティブ クエリを実行するをご覧ください。

次の例では、データセット myDataset に対する管理者ロールを取り消します。

REVOKE `roles/bigquery.admin`
ON SCHEMA `myProject`.myDataset
FROM "group:[email protected]", "serviceAccount:[email protected]"

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 ファイルを指定します。データセットがデフォルト プロジェクト以外のプロジェクトにある場合は、PROJECT_ID:DATASET の形式でプロジェクト ID をデータセット名に追加します。

    bq update \
        --source PATH_TO_FILE \
        PROJECT_ID:DATASET
  5. アクセス制御の変更を確認するには、show コマンドをもう一度使用します。ただし、今回は情報をファイルに書き込む指定を省略します。

    bq show --format=prettyjson PROJECT_ID:DATASET

API

アクセス制御を更新するには、Dataset リソースで datasets.patch を呼び出して 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 "[email protected]" 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 := "[email protected]"

	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 = "[email protected]";

    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
      // "[email protected]"
      // 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 = "[email protected]"

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 = "[email protected]"

# 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. [エクスプローラ] パネルでプロジェクトを開き、テーブルまたはビューを選択します。

  3. 詳細パネルで [共有] をクリックします。

  4. [共有] ダイアログで、アクセス権を取り消すプリンシパルを開きます。

  5. [削除] をクリックします。

  6. [プリンシパルからロールを削除しますか?] ダイアログで、[削除] をクリックします。

  7. テーブルまたはビューの詳細に戻るには、[閉じる] をクリックします。

SQL

プリンシパルからテーブルまたはビューへのアクセス権を削除するには、REVOKE DCL ステートメントを使用します。

  1. Google Cloud コンソールで [BigQuery Studio] ページに移動します。

    [BigQuery Studio] に移動

  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. [実行] をクリックします。

クエリの実行方法については、インタラクティブ クエリを実行するをご覧ください。

次の例では、テーブル myTable に対する管理者ロールを取り消します。

REVOKE `roles/bigquery.admin`
ON TABLE `myProject`.myDataset.myTable
FROM "group:[email protected]", "serviceAccount:[email protected]"

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 "[email protected]"
// 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 := "[email protected]"
	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("[email protected]");
    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}'.`
    );
  }
}

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"

# (Optional) Role to remove from the table or view.
# role_to_remove = "roles/bigquery.dataViewer"

# (Optional) Principal to revoke access to the table or view.
# principal_to_remove = "user:[email protected]"

# Find more information about roles and principals (referred to as members) here:
# https://cloud.google.com/security-command-center/docs/reference/rest/Shared.Types/Binding

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

# Get the full table 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 revoke access to a table or view,
# remove bindings from the Table or View IAM policy.
#
# Find more details about the Policy object here:
# https://cloud.google.com/security-command-center/docs/reference/rest/Shared.Types/Policy

if role_to_remove:
    # Filter out all bindings with the `role_to_remove`
    # and assign a new list back to the policy bindings.
    policy.bindings = [b for b in policy.bindings if b["role"] != role_to_remove]

if principal_to_remove:
    # The `bindings` list is immutable. Create a copy for modifications.
    bindings = list(policy.bindings)

    # Filter out the principal for each binding.
    for binding in bindings:
        binding["members"] = [m for m in binding["members"] if m != principal_to_remove]

    # Assign back the modified binding list.
    policy.bindings = bindings

new_policy = client.set_iam_policy(full_resource_name, policy)

リソースへのアクセスを拒否する

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 タイプのプロジェクトに対して自動的に生成される固有識別子です。
  • 特定のプリンシパルを拒否ポリシーから除外するには、拒否ポリシーの exceptionPrincipals フィールドでそのプリンシパルを指定します。例: exceptionPrincipals: "principalSet://bigquery.googleapis.com/projects/1234/*"

  • 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