Mengontrol akses ke resource dengan IAM

Dokumen ini menjelaskan cara melihat kebijakan akses resource saat ini, cara memberikan akses ke resource, dan cara mencabut akses ke resource.

Dokumen ini mengasumsikan Anda telah memahami sistem Identity and Access Management (IAM) di Google Cloud.

Peran yang diperlukan

Untuk mendapatkan izin yang Anda perlukan untuk mengubah kebijakan IAM untuk resource, minta administrator untuk memberi Anda peran IAM BigQuery Data Owner (roles/bigquery.dataOwner) pada project. Untuk mengetahui informasi selengkapnya tentang cara memberikan peran, lihat Mengelola akses ke project, folder, dan organisasi.

Peran yang telah ditentukan ini berisi izin yang diperlukan untuk mengubah kebijakan IAM untuk resource. Untuk melihat izin yang benar-benar diperlukan, luaskan bagian Izin yang diperlukan:

Izin berikut diperlukan guna mengubah kebijakan IAM untuk resource:

  • Untuk mendapatkan kebijakan akses set data: bigquery.datasets.get
  • Untuk menetapkan kebijakan akses set data: bigquery.datasets.update
  • Untuk mendapatkan kebijakan akses set data (khusus konsol Google Cloud): bigquery.datasets.getIamPolicy
  • Untuk menetapkan kebijakan akses set data (khusus konsol): bigquery.datasets.setIamPolicy
  • Untuk mendapatkan kebijakan tabel atau tabel virtual: bigquery.tables.getIamPolicy
  • Untuk menyetel kebijakan tabel atau tabel virtual: bigquery.tables.setIamPolicy
  • Untuk membuat alat bq atau tugas BigQuery SQL (opsional): bigquery.jobs.create

Anda mungkin juga bisa mendapatkan izin ini dengan peran khusus atau peran bawaan lainnya.

Melihat kebijakan akses resource

Bagian berikut menjelaskan cara melihat kebijakan akses dari berbagai resource.

Melihat kebijakan akses set data

Pilih salah satu opsi berikut:

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel Explorer, luaskan project Anda dan pilih set data.

  3. Klik Sharing > Permissions.

    Kebijakan akses set data akan muncul di panel Dataset Permissions.

  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. Untuk mendapatkan kebijakan yang ada dan menghasilkannya ke file lokal di JSON, gunakan perintah bq show di Cloud Shell:

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

    Ganti kode berikut:

    • PROJECT_ID: project ID Anda
    • DATASET: nama set data Anda
    • PATH_TO_FILE: jalur ke file JSON di komputer lokal Anda

Untuk melihat kebijakan akses set data, panggil metode datasets.get dengan resource dataset yang ditentukan.

Kebijakan tersedia di properti access dari resource dataset yang ditampilkan.

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Go API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Panggil fungsi client.Dataset().Metadata(). Kebijakan akses tersedia di properti 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
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Java API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.


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());
    }
  }
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Node.js API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Ambil metadata set data menggunakan fungsi Dataset#getMetadata(). Kebijakan akses tersedia di properti akses objek metadata yang dihasilkan.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Python API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Panggil fungsi client.get_dataset(). Kebijakan akses tersedia di properti 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}")

Melihat kebijakan akses tabel atau tabel virtual

Pilih salah satu opsi berikut:

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel Explorer, luaskan project Anda dan pilih tabel atau tabel virtual.

  3. Klik Share.

    Kebijakan akses tabel atau tabel virtual akan muncul di panel Share.

  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. Untuk mendapatkan kebijakan akses yang ada dan menghasilkannya ke file lokal di JSON, gunakan perintah bq get-iam-policy di Cloud Shell:

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

    Ganti kode berikut:

    • PROJECT_ID: project ID Anda
    • DATASET: nama set data Anda
    • RESOURCE: nama tabel atau tabel virtual yang kebijakannya ingin Anda lihat
    • PATH_TO_FILE: jalur ke file JSON di komputer lokal Anda

Untuk mengambil kebijakan saat ini, panggil metode tables.getIamPolicy.

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Go API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Panggil fungsi IAM().Policy() resource. Kemudian, panggil fungsi Roles() untuk mendapatkan kebijakan akses untuk tabel atau tampilan.
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
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Java API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.


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());
    }
  }
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Node.js API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Ambil kebijakan IAM untuk tabel atau tampilan menggunakan fungsi Table#getIamPolicy(). Detail kebijakan akses tersedia di objek kebijakan yang ditampilkan.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Python API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Panggil fungsi client.get_iam_policy() untuk mendapatkan kebijakan akses untuk tabel atau tampilan.

Argumen full_resource_id harus berupa string dalam format 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}")

Memberikan akses ke resource

Bagian berikut menjelaskan cara memberikan akses ke berbagai resource.

Memberikan akses ke set data

Anda dapat memberikan akses ke set data dengan memberikan izin peran IAM untuk mengakses set data atau dengan memberikan akses secara bersyarat menggunakan kondisi IAM. Untuk mengetahui informasi selengkapnya tentang cara memberikan akses bersyarat, lihat Mengontrol akses dengan Kondisi IAM.

Untuk memberikan akses peran IAM ke set data tanpa kondisi, pilih salah satu opsi berikut:

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel Explorer, luaskan project Anda dan pilih set data untuk dibagikan.

  3. Klik Sharing > Permissions.

  4. Klik Add principal.

  5. Di kolom New principals, masukkan akun utama.

  6. Di daftar Select a role, pilih peran yang telah ditetapkan atau peran khusus.

  7. Klik Save.

  8. Untuk kembali ke info set data, klik Close.

Untuk memberikan akses ke set data kepada akun utama, gunakan pernyataan DCL GRANT:

  1. Di konsol Google Cloud, buka halaman BigQuery Studio.

    Buka BigQuery Studio

  2. Di editor kueri, masukkan pernyataan berikut:

    GRANT `ROLE_LIST`
    ON SCHEMA RESOURCE_NAME
    TO "USER_LIST"

    Ganti kode berikut:

    • ROLE_LIST: peran atau daftar peran yang dipisahkan koma yang ingin Anda berikan
    • RESOURCE_NAME: nama resource yang ingin Anda beri izin
    • USER_LIST: daftar pengguna yang dipisahkan koma yang diberi peran

      Untuk daftar format yang valid, lihat user_list.

  3. Klik Run.

Untuk informasi selengkapnya tentang cara menjalankan kueri, lihat Menjalankan kueri interaktif.

Contoh berikut memberikan peran Data Viewer pada set data myDataset:

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

  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. Untuk menulis informasi set data yang ada (termasuk kontrol akses) ke file JSON, gunakan perintah bq show:

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

    Ganti kode berikut:

    • PROJECT_ID: project ID Anda
    • DATASET: nama set data Anda
    • PATH_TO_FILE: jalur ke file JSON di komputer lokal Anda
  3. Buat perubahan pada bagian access pada file JSON. Anda dapat menambahkan ke salah satu entri specialGroup: projectOwners, projectWriters, projectReaders, dan allAuthenticatedUsers. Anda juga dapat menambahkan salah satu dari: userByEmail, groupByEmail, dan domain.

    Misalnya, bagian access pada file JSON set data akan terlihat seperti berikut:

    {
     "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. Setelah pengeditan selesai, gunakan perintah bq update dan sertakan file JSON menggunakan flag --source. Jika set data berada dalam project selain project default Anda, tambahkan project ID ke nama set data dalam format berikut: PROJECT_ID:DATASET.

    bq update \
    --source PATH_TO_FILE \
    PROJECT_ID:DATASET
  5. Untuk memverifikasi perubahan kontrol akses, gunakan kembali perintah bq show tanpa perlu menulis informasi tersebut ke file:

    bq show --format=prettyjson PROJECT_ID:DATASET

Gunakan resource google_bigquery_dataset_iam untuk memperbarui akses ke set data.

Menetapkan kebijakan akses untuk set data

Contoh berikut menunjukkan cara menggunakan resource google_bigquery_dataset_iam_policy untuk menetapkan kebijakan IAM untuk set data mydataset. Tindakan ini akan menggantikan kebijakan apa pun yang sudah ada dan telah dilampirkan ke set data:

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

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

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

Menetapkan keanggotaan peran untuk set data

Contoh berikut menunjukkan cara menggunakan resource google_bigquery_dataset_iam_binding untuk menetapkan keanggotaan dalam peran tertentu untuk set data mydataset. Tindakan ini akan menggantikan keanggotaan yang ada dalam peran tersebut. Peran lain dalam kebijakan IAM untuk set data dipertahankan:

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

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

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

Menetapkan keanggotaan peran untuk satu akun utama

Contoh berikut menunjukkan cara menggunakan resource google_bigquery_dataset_iam_member untuk memperbarui kebijakan IAM untuk set data mydataset guna memberikan peran kepada satu akun utama. Memperbarui kebijakan IAM ini tidak akan memengaruhi akses untuk akun utama lain yang telah diberi peran tersebut untuk set data.

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

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

Untuk menerapkan konfigurasi Terraform di project Google Cloud, selesaikan langkah-langkah di bagian berikut.

Menyiapkan Cloud Shell

  1. Luncurkan Cloud Shell.
  2. Tetapkan project Google Cloud default tempat Anda ingin menerapkan konfigurasi Terraform.

    Anda hanya perlu menjalankan perintah ini sekali per project, dan dapat dijalankan di direktori mana pun.

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    Variabel lingkungan akan diganti jika Anda menetapkan nilai eksplisit dalam file konfigurasi Terraform.

Menyiapkan direktori

Setiap file konfigurasi Terraform harus memiliki direktorinya sendiri (juga disebut modul root).

  1. Di Cloud Shell, buat direktori dan file baru di dalam direktori tersebut. Nama file harus memiliki ekstensi .tf—misalnya main.tf. Dalam tutorial ini, file ini disebut sebagai main.tf.
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. Jika mengikuti tutorial, Anda dapat menyalin kode contoh di setiap bagian atau langkah.

    Salin kode contoh ke dalam main.tf yang baru dibuat.

    Atau, salin kode dari GitHub. Tindakan ini direkomendasikan jika cuplikan Terraform adalah bagian dari solusi menyeluruh.

  3. Tinjau dan ubah contoh parameter untuk diterapkan pada lingkungan Anda.
  4. Simpan perubahan Anda.
  5. Lakukan inisialisasi Terraform. Anda hanya perlu melakukan ini sekali per direktori.
    terraform init

    Secara opsional, untuk menggunakan versi penyedia Google terbaru, sertakan opsi -upgrade:

    terraform init -upgrade

Menerapkan perubahan

  1. Tinjau konfigurasi dan pastikan resource yang akan dibuat atau diupdate oleh Terraform sesuai yang Anda inginkan:
    terraform plan

    Koreksi konfigurasi jika diperlukan.

  2. Terapkan konfigurasi Terraform dengan menjalankan perintah berikut dan memasukkan yes pada prompt:
    terraform apply

    Tunggu hingga Terraform menampilkan pesan "Apply complete!".

  3. Buka project Google Cloud Anda untuk melihat hasilnya. Di Konsol Google Cloud, buka resource Anda di UI untuk memastikan bahwa Terraform telah membuat atau mengupdatenya.

Untuk menerapkan kontrol akses saat set data dibuat, panggil metode datasets.insert dengan resource set data yang ditentukan. Untuk memperbarui kontrol akses, panggil metode datasets.patch dan gunakan properti access di resource Dataset.

Karena metode datasets.update menggantikan seluruh resource set data, datasets.patch adalah metode yang lebih disukai untuk memperbarui kontrol akses.

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Go API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Tetapkan daftar akses baru dengan menambahkan entri baru ke daftar yang ada dengan jenis DatasetMetadataToUpdate . Kemudian, panggil fungsi dataset.Update() untuk memperbarui properti.
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
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Java API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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());
    }
  }
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Node.js API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Tetapkan daftar akses baru dengan menambahkan entri baru ke daftar yang ada menggunakan metode Dataset#metadata. Kemudian, panggil fungsi Dataset#setMetadata() untuk memperbarui properti.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Python API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Tetapkan properti dataset.access_entries dengan kontrol akses untuk set data. Kemudian, panggil fungsi client.update_dataset() untuk memperbarui properti.
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."
    )

Memberikan akses ke tabel atau tabel virtual

Pilih salah satu opsi berikut:

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel Explorer, luaskan project Anda dan pilih tabel atau tabel virtual untuk dibagikan.

  3. Klik Share.

  4. Klik Add principal.

  5. Di kolom New principals, masukkan akun utama.

  6. Di daftar Select a role, pilih peran yang telah ditetapkan atau peran khusus.

  7. Klik Save.

  8. Untuk kembali ke tabel atau melihat detail, klik Close.

Untuk memberikan akses ke tabel atau tabel virtual kepada akun utama, gunakan pernyataan DCL GRANT:

  1. Di konsol Google Cloud, buka halaman BigQuery Studio.

    Buka BigQuery Studio

  2. Di editor kueri, masukkan pernyataan berikut:

    GRANT `ROLE_LIST`
    ON RESOURCE_TYPE RESOURCE_NAME
    TO "USER_LIST"

    Ganti kode berikut:

    • ROLE_LIST: peran atau daftar peran yang dipisahkan koma yang ingin Anda berikan
    • RESOURCE_TYPE: jenis resource tempat peran diterapkan

      Nilai yang didukung mencakup TABLE, VIEW, MATERIALIZED VIEW, dan EXTERNAL TABLE.

    • RESOURCE_NAME: nama resource yang ingin Anda beri izin
    • USER_LIST: daftar pengguna yang dipisahkan koma yang diberi peran

      Untuk daftar format yang valid, lihat user_list.

  3. Klik Run.

Untuk informasi selengkapnya tentang cara menjalankan kueri, lihat Menjalankan kueri interaktif.

Contoh berikut memberikan peran Data Viewer pada tabel myTable:

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

  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. Untuk memberikan akses ke tabel atau tampilan, gunakan perintah bq add-iam-policy-binding:

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

    Ganti kode berikut:

    • MEMBER_TYPE: jenis anggota, seperti user, group, serviceAccount, atau domain.
    • MEMBER: alamat email atau nama domain anggota.
    • ROLE: peran yang ingin Anda berikan kepada anggota.
    • RESOURCE: nama tabel atau tampilan yang kebijakannya ingin Anda perbarui.

Gunakan resource google_bigquery_table_iam untuk memperbarui akses ke tabel.

Menetapkan kebijakan akses untuk tabel

Contoh berikut menunjukkan cara menggunakan resource google_bigquery_table_iam_policy untuk menetapkan kebijakan IAM untuk tabel mytable. Tindakan ini akan menggantikan kebijakan apa pun yang sudah ada dan telah dilampirkan ke tabel:

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

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

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

Menetapkan keanggotaan peran untuk tabel

Contoh berikut menunjukkan cara menggunakan resource google_bigquery_table_iam_binding untuk menetapkan keanggotaan dalam peran tertentu untuk tabel mytable. Tindakan ini akan menggantikan keanggotaan yang ada dalam peran tersebut. Peran lain dalam kebijakan IAM untuk tabel dipertahankan.

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

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

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

Menetapkan keanggotaan peran untuk satu akun utama

Contoh berikut menunjukkan cara menggunakan resource google_bigquery_table_iam_member untuk memperbarui kebijakan IAM untuk tabel mytable guna memberikan peran kepada satu akun utama. Memperbarui kebijakan IAM ini tidak akan memengaruhi akses untuk akun utama lain yang telah diberi peran tersebut untuk set data.

# 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"
}

Untuk menerapkan konfigurasi Terraform di project Google Cloud, selesaikan langkah-langkah di bagian berikut.

Menyiapkan Cloud Shell

  1. Luncurkan Cloud Shell.
  2. Tetapkan project Google Cloud default tempat Anda ingin menerapkan konfigurasi Terraform.

    Anda hanya perlu menjalankan perintah ini sekali per project, dan dapat dijalankan di direktori mana pun.

    export GOOGLE_CLOUD_PROJECT=PROJECT_ID

    Variabel lingkungan akan diganti jika Anda menetapkan nilai eksplisit dalam file konfigurasi Terraform.

Menyiapkan direktori

Setiap file konfigurasi Terraform harus memiliki direktorinya sendiri (juga disebut modul root).

  1. Di Cloud Shell, buat direktori dan file baru di dalam direktori tersebut. Nama file harus memiliki ekstensi .tf—misalnya main.tf. Dalam tutorial ini, file ini disebut sebagai main.tf.
    mkdir DIRECTORY && cd DIRECTORY && touch main.tf
  2. Jika mengikuti tutorial, Anda dapat menyalin kode contoh di setiap bagian atau langkah.

    Salin kode contoh ke dalam main.tf yang baru dibuat.

    Atau, salin kode dari GitHub. Tindakan ini direkomendasikan jika cuplikan Terraform adalah bagian dari solusi menyeluruh.

  3. Tinjau dan ubah contoh parameter untuk diterapkan pada lingkungan Anda.
  4. Simpan perubahan Anda.
  5. Lakukan inisialisasi Terraform. Anda hanya perlu melakukan ini sekali per direktori.
    terraform init

    Secara opsional, untuk menggunakan versi penyedia Google terbaru, sertakan opsi -upgrade:

    terraform init -upgrade

Menerapkan perubahan

  1. Tinjau konfigurasi dan pastikan resource yang akan dibuat atau diupdate oleh Terraform sesuai yang Anda inginkan:
    terraform plan

    Koreksi konfigurasi jika diperlukan.

  2. Terapkan konfigurasi Terraform dengan menjalankan perintah berikut dan memasukkan yes pada prompt:
    terraform apply

    Tunggu hingga Terraform menampilkan pesan "Apply complete!".

  3. Buka project Google Cloud Anda untuk melihat hasilnya. Di Konsol Google Cloud, buka resource Anda di UI untuk memastikan bahwa Terraform telah membuat atau mengupdatenya.

  1. Untuk mengambil kebijakan saat ini, panggil metode tables.getIamPolicy.
  2. Edit kebijakan untuk menambahkan anggota atau binding, atau keduanya. Untuk format yang diperlukan untuk kebijakan, lihat topik referensi Kebijakan.

  3. Panggil tables.setIamPolicy untuk menulis kebijakan yang diperbarui. Catatan: Binding kosong tanpa anggota tidak diizinkan dan akan menghasilkan error.

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Go API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Panggil fungsi IAM().SetPolicy() resource untuk menyimpan perubahan pada kebijakan akses untuk tabel atau tampilan.
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
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Java API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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());
    }
  }
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Node.js API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Panggil fungsi Table#getIamPolicy() untuk mengambil kebijakan IAM saat ini untuk tabel atau tampilan, ubah kebijakan dengan menambahkan binding baru, lalu gunakan fungsi Table#setIamPolicy() untuk menyimpan perubahan pada kebijakan akses.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Python API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Panggil fungsi client.set_iam_policy() untuk menyimpan perubahan pada kebijakan akses untuk tabel atau tampilan.
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}'."
)

Mencabut akses ke resource

Bagian berikut menjelaskan cara mencabut akses ke berbagai resource.

Mencabut akses ke set data

Pilih salah satu opsi berikut:

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel Explorer, luaskan project Anda dan pilih set data.

  3. Di panel detail, klik Sharing > Permissions.

  4. Pada dialog Dataset Permissions, luaskan akun utama yang aksesnya ingin Anda cabut.

  5. Klik Remove principal.

  6. Pada dialog Hapus peran dari akun utama?, klik Hapus.

  7. Untuk kembali ke detail set data, klik Close.

Untuk menghapus akses ke set data dari akun utama, gunakan pernyataan DCL REVOKE:

  1. Di konsol Google Cloud, buka halaman BigQuery Studio.

    Buka BigQuery Studio

  2. Di editor kueri, masukkan pernyataan berikut:

    REVOKE `ROLE_LIST`
    ON SCHEMA RESOURCE_NAME
    FROM "USER_LIST"

    Ganti kode berikut:

    • ROLE_LIST: peran atau daftar peran yang dipisahkan koma yang ingin Anda cabut
    • RESOURCE_NAME: nama resource yang izinnya ingin Anda cabut
    • USER_LIST: daftar pengguna yang dipisahkan koma yang perannya akan dicabut

      Untuk daftar format yang valid, lihat user_list.

  3. Klik Run.

Untuk informasi selengkapnya tentang cara menjalankan kueri, lihat Menjalankan kueri interaktif.

Contoh berikut mencabut peran Admin pada set data myDataset:

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

  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. Untuk menulis informasi set data yang ada (termasuk kontrol akses) ke file JSON, gunakan perintah bq show:

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

    Ganti kode berikut:

    • PROJECT_ID: project ID Anda
    • DATASET: nama set data Anda
    • PATH_TO_FILE: jalur ke file JSON di komputer lokal Anda
  3. Buat perubahan pada bagian access pada file JSON. Anda dapat menghapus salah satu entri specialGroup: projectOwners, projectWriters, projectReaders, dan allAuthenticatedUsers. Anda juga dapat menghapus salah satu dari: userByEmail, groupByEmail, dan domain.

    Misalnya, bagian access pada file JSON set data akan terlihat seperti berikut:

    {
     "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. Setelah pengeditan selesai, gunakan perintah bq update dan sertakan file JSON menggunakan flag --source. Jika set data berada dalam project selain project default Anda, tambahkan project ID ke nama set data dalam format berikut: PROJECT_ID:DATASET.

    bq update \
        --source PATH_TO_FILE \
        PROJECT_ID:DATASET
  5. Untuk memverifikasi perubahan kontrol akses, gunakan kembali perintah show tanpa perlu menulis informasi tersebut ke file:

    bq show --format=prettyjson PROJECT_ID:DATASET

Panggil datasets.patch dan gunakan properti access di resource Dataset untuk memperbarui kontrol akses.

Karena metode datasets.update menggantikan seluruh resource set data, datasets.patch adalah metode yang lebih disukai untuk memperbarui kontrol akses.

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Go API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Tetapkan daftar akses baru dengan menghapus entri dari daftar yang ada dengan jenis DatasetMetadataToUpdate . Kemudian, panggil fungsi dataset.Update() untuk memperbarui properti.
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
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Java API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.


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());
    }
  }
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Node.js API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Perbarui daftar akses set data dengan menghapus entri yang ditentukan dari daftar yang ada menggunakan metode Dataset#get() untuk mengambil metadata saat ini. Ubah properti akses untuk mengecualikan entity yang diinginkan, lalu panggil fungsi Dataset#setMetadata() untuk menerapkan daftar akses yang diperbarui.

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

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Python API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Tetapkan properti dataset.access_entries dengan kontrol akses untuk set data. Kemudian, panggil fungsi client.update_dataset() untuk memperbarui properti.
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."
    )

Mencabut akses ke tabel atau tabel virtual

Pilih salah satu opsi berikut:

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel Explorer, luaskan project Anda dan pilih tabel atau tabel virtual.

  3. Di panel detail, klik Share.

  4. Pada dialog Share, luaskan akun utama yang aksesnya ingin Anda cabut.

  5. Klik Delete.

  6. Pada dialog Hapus peran dari akun utama?, klik Hapus.

  7. Untuk kembali ke tabel atau melihat detail, klik Close.

Untuk menghapus akses ke tabel atau tabel virtual dari akun utama, gunakan pernyataan DCL REVOKE:

  1. Di konsol Google Cloud, buka halaman BigQuery Studio.

    Buka BigQuery Studio

  2. Di editor kueri, masukkan pernyataan berikut:

    REVOKE `ROLE_LIST`
    ON RESOURCE_TYPE RESOURCE_NAME
    FROM "USER_LIST"

    Ganti kode berikut:

    • ROLE_LIST: peran atau daftar peran yang dipisahkan koma yang ingin Anda cabut
    • RESOURCE_TYPE: jenis resource tempat peran dicabut

      Nilai yang didukung mencakup TABLE, VIEW, MATERIALIZED VIEW, dan EXTERNAL TABLE.

    • RESOURCE_NAME: nama resource yang izinnya ingin Anda cabut
    • USER_LIST: daftar pengguna yang dipisahkan koma yang perannya akan dicabut

      Untuk daftar format yang valid, lihat user_list.

  3. Klik Run.

Untuk informasi selengkapnya tentang cara menjalankan kueri, lihat Menjalankan kueri interaktif.

Contoh berikut mencabut peran Admin pada tabel myTable:

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

  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. Untuk mencabut akses ke tabel atau tabel virtual, gunakan perintah bq remove-iam-policy-binding:

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

    Ganti kode berikut:

    • MEMBER_TYPE: jenis anggota, seperti user, group, serviceAccount, atau domain.
    • MEMBER: alamat email atau nama domain anggota.
    • ROLE: peran yang ingin Anda cabut dari anggota.
    • RESOURCE: nama tabel atau tampilan yang kebijakannya ingin Anda perbarui.

  1. Untuk mengambil kebijakan saat ini, panggil metode tables.getIamPolicy.
  2. Edit kebijakan untuk menghapus anggota atau binding, atau keduanya. Untuk format yang diperlukan untuk kebijakan, lihat topik referensi Kebijakan.

  3. Panggil tables.setIamPolicy untuk menulis kebijakan yang diperbarui. Catatan: Binding kosong tanpa anggota tidak diizinkan dan akan menghasilkan error.

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Go di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Go API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Panggil fungsi policy.Remove() untuk menghapus akses. Kemudian, panggil fungsi IAM().SetPolicy() untuk menyimpan perubahan pada kebijakan akses untuk tabel atau tampilan.
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
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Java di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Java API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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());
    }
  }
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Node.js di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Node.js API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Mengambil kebijakan IAM saat ini untuk tabel atau tampilan menggunakan metode Table#getIamPolicy(). Ubah kebijakan untuk menghapus peran atau akun utama yang diinginkan, lalu terapkan kebijakan yang diperbarui menggunakan metode 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}'.`
    );
  }
}

Sebelum mencoba contoh ini, ikuti petunjuk penyiapan Python di Panduan memulai BigQuery menggunakan library klien. Untuk mengetahui informasi selengkapnya, lihat Dokumentasi referensi BigQuery Python API.

Untuk melakukan autentikasi ke BigQuery, siapkan Kredensial Default Aplikasi. Untuk informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

Panggil fungsi client.set_iam_policy() untuk menyimpan perubahan pada kebijakan akses untuk tabel atau tampilan.
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:alice@example.com"

# 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)

Menolak akses ke resource

Kebijakan tolak IAM dapat Anda gunakan untuk menetapkan batasan pada akses ke resource BigQuery. Anda dapat menentukan aturan tolak yang mencegah akun utama yang dipilih menggunakan izin tertentu, terlepas dari peran yang diberikan.

Untuk informasi tentang cara membuat, memperbarui, dan menghapus kebijakan tolak, lihat Menolak akses ke resource.

Kasus khusus

Pertimbangkan skenario berikut saat Anda membuat kebijakan penolakan IAM pada beberapa izin BigQuery:

  • Akses ke resource yang diotorisasi (tampilan, rutinitas, set data, atau prosedur tersimpan) memungkinkan Anda membuat, menghapus, atau memanipulasi tabel, beserta membaca dan mengubah data tabel, meskipun Anda tidak memiliki izin langsung untuk melakukan operasi tersebut. Fungsi ini juga dapat mendapatkan data atau metadata model dan memanggil prosedur tersimpan lainnya di tabel pokok. Kemampuan ini menyiratkan bahwa resource yang diotorisasi memiliki izin berikut:

    • 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

    Untuk menolak akses ke resource yang diotorisasi ini, tambahkan salah satu nilai berikut ke kolom deniedPrincipal saat Anda membuat kebijakan penolakan:

    Nilai Kasus penggunaan
    principalSet://goog/public:all Memblokir semua akun utama termasuk resource yang diotorisasi.
    principalSet://bigquery.googleapis.com/projects/PROJECT_NUMBER/* Memblokir semua resource BigQuery yang diotorisasi dalam project yang ditentukan. PROJECT_NUMBER adalah ID unik yang dibuat secara otomatis untuk project Anda dari jenis INT64.
  • Untuk mengecualikan akun utama tertentu dari kebijakan tolak, tentukan akun utama tersebut dalam kolom exceptionPrincipals kebijakan tolak Anda. Misalnya, exceptionPrincipals: "principalSet://bigquery.googleapis.com/projects/1234/*".

  • BigQuery meng-cache hasil kueri pemilik tugas selama 24 jam, yang dapat diakses oleh pemilik tugas tanpa memerlukan izin bigquery.tables.getData di tabel yang berisi data. Oleh karena itu, menambahkan kebijakan penolakan IAM ke izin bigquery.tables.getData tidak memblokir akses ke hasil yang di-cache untuk pemilik tugas hingga masa berlaku cache berakhir. Untuk memblokir akses pemilik tugas ke hasil yang di-cache, buat kebijakan tolak terpisah pada izin bigquery.jobs.create.

  • Untuk mencegah akses data yang tidak diinginkan saat menggunakan kebijakan tolak untuk memblokir operasi pembacaan data, sebaiknya Anda juga meninjau dan mencabut langganan yang ada di set data.

  • Untuk membuat kebijakan penolakan IAM guna melihat kontrol akses set data, tolak izin berikut:

    • bigquery.datasets.get
    • bigquery.datasets.getIamPolicy
  • Untuk membuat kebijakan penolakan IAM guna memperbarui kontrol akses set data, tolak izin berikut:

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