Mengontrol akses ke resource dengan IAM

Dokumen ini menjelaskan cara melihat, memberikan, dan mencabut kontrol akses untuk set data BigQuery dan untuk resource dalam set data: tabel, tampilan, dan rutin. Meskipun model juga merupakan resource tingkat set data, Anda tidak dapat memberikan akses ke setiap model menggunakan peran IAM.

Anda dapat memberikan akses ke resource Google Cloud menggunakan kebijakan izin, yang juga dikenal sebagai kebijakan Identity and Access Management (IAM), yang terpasang ke resource. Anda hanya dapat memasang satu kebijakan izin ke setiap resource. Kebijakan izin mengontrol akses ke resource itu sendiri, serta ke berbagai turunan resource tersebut yang mewarisi kebijakan izin.

Untuk mengetahui informasi selengkapnya tentang kebijakan izin, lihat Struktur kebijakan dalam dokumentasi IAM.

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

Batasan

  • Daftar kontrol akses (ACL) rutin tidak disertakan dalam rutinitas yang direplikasi.
  • Rutinitas di dalam set data eksternal atau tertaut tidak mendukung kontrol akses.
  • Tabel di dalam set data eksternal atau tertaut tidak mendukung kontrol akses.
  • Kontrol akses rutin tidak dapat ditetapkan dengan Terraform.
  • Kontrol akses rutin tidak dapat ditetapkan dengan Google Cloud SDK.
  • Kontrol akses rutin tidak dapat ditetapkan menggunakan bahasa kontrol data (DCL) BigQuery.
  • Data Catalog tidak mendukung kontrol akses rutin. Jika pengguna telah memberikan akses tingkat rutin secara bersyarat, mereka tidak akan melihat rutinitasnya di panel samping BigQuery. Sebagai solusinya, berikan akses tingkat set data.
  • Tampilan INFORMATION_SCHEMA.OBJECT_PRIVILEGES tidak menampilkan kontrol akses untuk rutinitas.

Sebelum memulai

Memberikan peran Identity and Access Management (IAM) yang memberi izin yang diperlukan kepada pengguna untuk melakukan setiap tugas dalam dokumen ini.

Peran yang diperlukan

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

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

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 konsolGoogle 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 mendapatkan kebijakan akses rutin: bigquery.routines.getIamPolicy
  • Untuk menetapkan kebijakan akses rutin: bigquery.routines.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.

Bekerja dengan kontrol akses set data

Anda dapat memberikan akses ke set data dengan memberikan akun utama IAM peran standar atau kustom yang menentukan apa yang dapat dilakukan akun utama dengan set data. Hal ini juga dikenal sebagai melampirkan kebijakan izin ke resource. Setelah memberikan akses, Anda dapat melihat kontrol akses set data, dan Anda dapat mencabut akses ke set data.

Memberikan akses ke set data

Anda tidak dapat memberikan akses ke set data saat membuatnya menggunakan UI web BigQuery atau alat command line bq. Anda harus membuat set data terlebih dahulu, lalu memberikan akses ke set data tersebut. API memungkinkan Anda memberikan akses selama pembuatan set data dengan memanggil metode datasets.insert dengan resource set data yang ditentukan.

Project adalah resource induk untuk set data, dan set data adalah resource induk untuk tabel dan tampilan, rutinitas, dan model. Saat Anda memberikan peran di level project, peran dan izinnya akan diwarisi oleh set data dan resource set data. Demikian pula, saat Anda memberikan peran di tingkat set data, peran dan izinnya diwarisi oleh resource dalam 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 pemberian akses bersyarat, lihat Mengontrol akses dengan Kondisi IAM.

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

Konsol

  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.

SQL

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

  1. Di Google Cloud konsol, buka halaman BigQuery.

    Buka BigQuery

  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 set data yang aksesnya Anda berikan
    • USER_LIST: daftar pengguna yang dipisahkan koma yang diberi peran

      Untuk mengetahui daftar format yang valid, lihat user_list.

  3. Klik Run.

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

Contoh berikut memberikan peran BigQuery Data Viewer kepada myDataset:

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

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 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
  6. Terraform

    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:user@example.com",
        ]
      }
      binding {
        role = "roles/bigquery.dataOwner"
        members = [
          "group:data.admin@example.com",
        ]
      }
      binding {
        role = "roles/bigquery.dataEditor"
        members = [
          "serviceAccount:bqcx-1234567891011-12a3@gcp-sa-bigquery-condel.iam.gserviceaccount.com",
        ]
      }
    }
    
    resource "google_bigquery_dataset_iam_policy" "dataset_iam_policy" {
      dataset_id  = google_bigquery_dataset.default.dataset_id
      policy_data = data.google_iam_policy.iam_policy.policy_data
    }

    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:user@example.com",
        "group:group@example.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 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:user@example.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 default Google Cloud 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 Google Cloud project Anda untuk melihat hasilnya. Di konsol Google Cloud , buka resource Anda di UI untuk memastikan bahwa Terraform telah membuat atau mengupdatenya.

    API

    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.

    Go

    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 mengetahui 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
    }
    

    Java

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

    Node.js

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

    Python

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

Peran bawaan yang memberikan akses ke set data

Anda dapat memberikan akses ke set data untuk peran bawaan IAM berikut.

Peran Deskripsi
BigQuery Data Owner (roles/bigquery.dataOwner) Jika diberikan pada set data, peran ini memberikan izin berikut:
  • Semua izin untuk set data dan untuk semua resource dalam set data: tabel dan tampilan, model, dan rutinitas.
BigQuery Data Editor (roles/bigquery.dataEditor) Jika diberikan pada set data, peran ini memberikan izin berikut:
  • Mendapatkan metadata dan izin untuk set data.
  • Untuk tabel dan tampilan:
    • Membuat, memperbarui, mendapatkan, mencantumkan, dan menghapus tabel dan tampilan set data.
    • Membaca (membuat kueri), mengekspor, mereplikasi, dan memperbarui data tabel.
    • Membuat, memperbarui, dan menghapus indeks.
    • Membuat dan memulihkan snapshot.
  • Semua izin untuk rutinitas dan model set data.
BigQuery Data Viewer (roles/bigquery.dataViewer) Jika diberikan pada set data, peran ini memberikan izin berikut:
  • Mendapatkan metadata dan izin untuk set data.
  • Mencantumkan tabel, tampilan, dan model set data.
  • Mendapatkan metadata dan kontrol akses untuk tabel dan tampilan set data.
  • Membaca (membuat kueri), mereplikasi, dan mengekspor data tabel serta membuat snapshot.
  • Mencantumkan dan memanggil rutinitas set data.
BigQuery Metadata Viewer (roles/bigquery.metadataViewer) Jika diberikan pada set data, peran ini memberikan izin berikut:
  • Mendapatkan metadata dan kontrol akses untuk set data.
  • Mendapatkan metadata dan kontrol akses untuk tabel dan tampilan.
  • Mendapatkan metadata dari model dan rutinitas set data.
  • Mencantumkan tabel, tampilan, model, dan rutinitas dalam set data.

Izin set data

Sebagian besar izin yang diawali dengan bigquery.datasets berlaku di tingkat set data. bigquery.datasets.create tidak. Untuk membuat set data, izin bigquery.datasets.create harus diberikan ke peran di penampung induk–project.

Tabel berikut mencantumkan semua izin untuk set data dan resource tingkat terendah yang dapat diterapkan izinnya.

Izin Resource Tindakan
bigquery.datasets.create Project Buat set data baru dalam project.
bigquery.datasets.get Set data Mendapatkan metadata dan kontrol akses untuk set data. Melihat izin di konsol juga memerlukan izin bigquery.datasets.getIamPolicy.
bigquery.datasets.getIamPolicy Set data Diperlukan oleh konsol untuk memberikan izin kepada pengguna guna mendapatkan kontrol akses set data. Gagal terbuka. Konsol juga memerlukan izin bigquery.datasets.get untuk melihat set data.
bigquery.datasets.update Set data Perbarui metadata dan kontrol akses untuk set data. Memperbarui kontrol akses di konsol juga memerlukan izin bigquery.datasets.setIamPolicy.
bigquery.datasets.setIamPolicy Set data Diperlukan oleh konsol untuk memberikan izin kepada pengguna untuk menyetel kontrol akses set data. Gagal terbuka. Konsol juga memerlukan izin bigquery.datasets.update untuk memperbarui set data.
bigquery.datasets.delete Set data Menghapus set data.
bigquery.datasets.createTagBinding Set data Pasang tag ke set data.
bigquery.datasets.deleteTagBinding Set data Melepaskan tag dari set data.
bigquery.datasets.listTagBindings Set data Mencantumkan tag untuk set data.
bigquery.datasets.listEffectiveTags Set data Mencantumkan tag efektif (diterapkan dan diwariskan) untuk set data.
bigquery.datasets.link Set data Buat set data tertaut.
bigquery.datasets.listSharedDatasetUsage Project Mencantumkan statistik penggunaan set data bersama untuk set data yang dapat Anda akses dalam project. Izin ini diperlukan untuk membuat kueri tampilan INFORMATION_SCHEMA.SHARED_DATASET_USAGE.

Melihat kontrol akses untuk set data

Anda dapat melihat kontrol akses yang ditetapkan secara eksplisit untuk set data dengan memilih salah satu opsi berikut. Untuk melihat peran yang diwariskan, untuk set data, gunakan UI web BigQuery.

Konsol

  1. Buka halaman BigQuery.

    Buka BigQuery

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

  3. Klik Sharing > Permissions.

    Kontrol akses set data akan muncul di panel Dataset Permissions.

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 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
  3. SQL

    Buat kueri tampilan INFORMATION_SCHEMA.OBJECT_PRIVILEGES. Kueri untuk mengambil kontrol akses bagi set data harus menentukan object_name.

    1. Di Google Cloud konsol, buka halaman BigQuery.

      Buka BigQuery

    2. Di editor kueri, masukkan pernyataan berikut:

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

      Ganti kode berikut:

    3. Klik Run.

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

    Contoh:

    Kueri ini mendapatkan kontrol akses untuk mydataset.

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

    Outputnya akan terlihat seperti berikut ini:

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

    API

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

    Kontrol akses muncul di properti access dari resource dataset.

    Go

    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 mengetahui 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
    }
    

    Java

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

    Node.js

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

    Python

    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 mengetahui 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}")

Mencabut akses ke set data

Untuk mencabut akses ke set data, pilih salah satu opsi berikut:

Konsol

  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.

SQL

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

  1. Di Google Cloud konsol, buka halaman BigQuery.

    Buka BigQuery

  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 mengetahui daftar format yang valid, lihat user_list.

  3. Klik Run.

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

Contoh berikut mencabut peran BigQuery Data Owner dari myDataset:

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

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. 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 Anda, gunakan perintah show tanpa perlu menulis informasi tersebut ke file:

    bq show --format=prettyjson PROJECT_ID:DATASET
  6. API

    Panggil metode 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.

    Go

    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 mengetahui 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
    }
    

    Java

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

    Node.js

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

    Python

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

Bekerja dengan kontrol akses tabel dan tampilan

Tampilan diperlakukan sebagai resource tabel di BigQuery. Anda dapat memberikan akses ke tabel atau tampilan dengan memberikan akun utama IAM peran bawaan atau kustom yang menentukan apa yang dapat dilakukan akun utama dengan tabel atau tampilan. Hal ini juga dikenal sebagai melampirkan kebijakan izin ke resource. Setelah memberikan akses, Anda dapat melihat kontrol akses untuk tabel atau tabel virtual, dan Anda dapat mencabut akses ke tabel atau tabel virtual.

Memberikan akses ke tabel atau tabel virtual

Untuk kontrol akses terperinci, Anda dapat memberikan peran IAM yang telah ditetapkan atau khusus pada tabel atau tampilan tertentu. Tabel atau tampilan juga mewarisi kontrol akses yang ditentukan di tingkat set data dan yang lebih tinggi. Misalnya, jika Anda memberikan peran Pemilik Data BigQuery kepada akun utama di set data, akun utama tersebut juga memiliki izin Pemilik Data BigQuery pada tabel dan tampilan di set data tersebut.

Untuk memberikan akses ke tabel atau tampilan, pilih salah satu opsi berikut:

Konsol

  1. Buka halaman BigQuery.

    Buka BigQuery

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

  3. Klik Bagikan.

  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.

SQL

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

  1. Di Google Cloud konsol, buka halaman BigQuery.

    Buka BigQuery

  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 mengetahui informasi selengkapnya tentang cara menjalankan kueri, lihat artikel Menjalankan kueri interaktif.

Contoh berikut memberikan peran BigQuery Data Viewer pada myTable:

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

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Untuk memberikan akses ke tabel atau tabel virtual, 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.
  3. Terraform

    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:user@example.com",
        ]
      }
    }
    
    resource "google_bigquery_table_iam_policy" "table_iam_policy" {
      dataset_id  = google_bigquery_table.default.dataset_id
      table_id    = google_bigquery_table.default.table_id
      policy_data = data.google_iam_policy.iam_policy.policy_data
    }

    Menetapkan keanggotaan peran untuk tabel

    Contoh berikut menunjukkan cara menggunakan google_bigquery_table_iam_binding resource 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:group@example.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 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 default Google Cloud 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 Google Cloud project Anda untuk melihat hasilnya. Di konsol Google Cloud , buka resource Anda di UI untuk memastikan bahwa Terraform telah membuat atau mengupdatenya.

    API

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

    2. Edit kebijakan untuk menambahkan anggota atau kontrol akses, atau keduanya. Untuk mengetahui format yang diperlukan untuk kebijakan, lihat topik referensi Kebijakan.

    3. Panggil tables.setIamPolicy untuk menulis kebijakan yang diperbarui.

    Go

    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 mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

    Panggil fungsi IAM().SetPolicy() resource untuk menyimpan perubahan pada kebijakan akses tabel atau tabel virtual.
    import (
    	"context"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/bigquery"
    	"cloud.google.com/go/iam"
    )
    
    // grantAccessToResource creates a new ACL conceding the VIEWER role to the group "example-analyst-group@google.com"
    // For more information on the types of ACLs available see:
    // https://cloud.google.com/storage/docs/access-control/lists
    func grantAccessToResource(w io.Writer, projectID, datasetID, resourceID string) error {
    	// Resource can be a table or a view
    	//
    	// TODO(developer): uncomment and update the following lines:
    	// projectID := "my-project-id"
    	// datasetID := "mydataset"
    	// resourceID := "myresource"
    
    	ctx := context.Background()
    
    	// Create new client
    	client, err := bigquery.NewClient(ctx, projectID)
    	if err != nil {
    		return fmt.Errorf("bigquery.NewClient: %w", err)
    	}
    	defer client.Close()
    
    	// Get resource policy.
    	policy, err := client.Dataset(datasetID).Table(resourceID).IAM().Policy(ctx)
    	if err != nil {
    		return fmt.Errorf("bigquery.Dataset.Table.IAM.Policy: %w", err)
    	}
    
    	// Find more details about IAM Roles here:
    	// https://pkg.go.dev/cloud.google.com/go/iam#RoleName
    	entityID := "example-analyst-group@google.com"
    	roleType := iam.Viewer
    
    	// Add new policy.
    	policy.Add(fmt.Sprintf("group:%s", entityID), roleType)
    
    	// Update resource's policy.
    	err = client.Dataset(datasetID).Table(resourceID).IAM().SetPolicy(ctx, policy)
    	if err != nil {
    		return fmt.Errorf("bigquery.Dataset.Table.IAM.Policy: %w", err)
    	}
    
    	// Get resource policy again expecting the update.
    	policy, err = client.Dataset(datasetID).Table(resourceID).IAM().Policy(ctx)
    	if err != nil {
    		return fmt.Errorf("bigquery.Dataset.Table.IAM.Policy: %w", err)
    	}
    
    	fmt.Fprintf(w, "Details for Access entries in table or view %v.\n", resourceID)
    
    	for _, role := range policy.Roles() {
    		fmt.Fprintln(w)
    		fmt.Fprintf(w, "Role: %s\n", role)
    		fmt.Fprintf(w, "Entities: %v\n", policy.Members(role))
    	}
    
    	return nil
    }
    

    Java

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

    Node.js

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

    Python

    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 mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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

Peran bawaan yang memberikan akses ke tabel dan tampilan

Tampilan diperlakukan sebagai resource tabel di BigQuery. Untuk kontrol akses terperinci, Anda dapat memberikan peran IAM standar atau kustom pada tabel atau tampilan tertentu. Tabel atau tampilan juga mewarisi kontrol akses yang ditentukan di tingkat set data dan yang lebih tinggi. Misalnya, jika Anda memberikan peran Pemilik Data BigQuery kepada akun utama di set data, akun utama tersebut juga memiliki izin Pemilik Data pada tabel dan tampilan di set data.

Peran IAM bawaan berikut memiliki izin pada tabel atau tabel virtual.

Peran Deskripsi
BigQuery Data Owner (roles/bigquery.dataOwner) Jika diberikan pada tabel atau tampilan, peran ini memberikan izin berikut:
  • Semua izin untuk tabel atau tampilan.
  • Semua izin untuk kebijakan akses baris, kecuali izin untuk mengganti batasan perjalanan waktu.
  • Tetapkan kategori dan kebijakan data tingkat kolom.
BigQuery Data Editor (roles/bigquery.dataEditor) Jika diberikan pada tabel atau tampilan, peran ini memberikan izin berikut:
  • Mendapatkan metadata, memperbarui metadata, mendapatkan kontrol akses, dan menghapus tabel atau tampilan.
  • Mendapatkan (membuat kueri), mengekspor, mereplikasi, dan memperbarui data tabel.
  • Membuat, memperbarui, dan menghapus indeks.
  • Membuat dan memulihkan snapshot.
BigQuery Data Viewer (roles/bigquery.dataViewer) Jika diberikan pada tabel atau tampilan, peran ini memberikan izin berikut:
  • Mendapatkan metadata dan kontrol akses untuk tabel atau tabel virtual.
  • Mendapatkan (membuat kueri), mengekspor, dan mereplikasi data tabel.
  • Buat snapshot.
BigQuery Metadata Viewer (roles/bigquery.metadataViewer) Jika diberikan pada tabel atau tampilan, peran ini memberikan izin berikut:
  • Mendapatkan metadata dan kontrol akses untuk tabel atau tabel virtual.

Izin untuk tabel dan tampilan

Tampilan diperlakukan sebagai resource tabel di BigQuery. Semua izin tingkat tabel berlaku untuk tampilan.

Sebagian besar izin yang diawali dengan bigquery.tables berlaku di tingkat tabel. bigquery.tables.create dan bigquery.tables.list tidak. Untuk membuat dan mencantumkan tabel atau tampilan, izin bigquery.tables.create dan bigquery.tables.list harus diberikan ke peran pada penampung induk–set data atau project.

Tabel berikut mencantumkan semua izin untuk tabel dan tampilan serta resource tingkat terendah yang dapat diberikan izinnya.

Izin Resource Tindakan
bigquery.tables.create Set data Buat tabel baru dalam set data.
bigquery.tables.createIndex Tabel Buat indeks penelusuran pada tabel.
bigquery.tables.deleteIndex Tabel Hapus indeks penelusuran pada tabel.
bigquery.tables.createSnapshot Tabel Buat snapshot tabel. Membuat snapshot memerlukan beberapa izin tambahan di tingkat tabel dan set data. Untuk mengetahui detailnya, lihat Izin dan peran untuk membuat snapshot tabel.
bigquery.tables.deleteSnapshot Tabel Menghapus snapshot tabel.
bigquery.tables.delete Tabel Menghapus tabel.
bigquery.tables.createTagBinding Tabel Buat binding tag resource pada tabel.
bigquery.tables.deleteTagBinding Tabel Menghapus binding tag resource pada tabel.
bigquery.tables.listTagBindings Tabel Mencantumkan binding tag resource pada tabel.
bigquery.tables.listEffectiveTags Tabel Mencantumkan tag efektif (diterapkan dan diwariskan) untuk tabel.
bigquery.tables.export Tabel Mengekspor data tabel. Menjalankan tugas ekspor juga memerlukan izin bigquery.jobs.create.
bigquery.tables.get Tabel Mendapatkan metadata untuk tabel.
bigquery.tables.getData Tabel Buat kueri data tabel. Menjalankan tugas kueri juga memerlukan izin bigquery.jobs.create.
bigquery.tables.getIamPolicy Tabel Mendapatkan kontrol akses untuk tabel.
bigquery.tables.list Set data Mencantumkan semua tabel dan metadata tabel dalam set data.
bigquery.tables.replicateData Tabel Mereplikasikan data tabel. Izin ini diperlukan untuk membuat replika tampilan terwujud.
bigquery.tables.restoreSnapshot Tabel Memulihkan snapshot tabel.
bigquery.tables.setCategory Tabel Tetapkan tag kebijakan dalam skema tabel.
bigquery.tables.setColumnDataPolicy Tabel Menetapkan kebijakan akses tingkat kolom pada tabel.
bigquery.tables.setIamPolicy Tabel Menetapkan kontrol akses pada tabel.
bigquery.tables.update Tabel Perbarui tabel. metadata. bigquery.tables.get juga diperlukan untuk memperbarui metadata tabel di konsol.
bigquery.tables.updateData Tabel Perbarui data tabel.
bigquery.tables.updateIndex Tabel Perbarui indeks penelusuran pada tabel.

Melihat kontrol akses untuk tabel atau tabel virtual

Untuk melihat kontrol akses untuk tabel atau tampilan, pilih salah satu opsi berikut:

Konsol

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel Explorer, luaskan project Anda, luaskan set data, lalu pilih tabel atau tampilan.

  3. Klik Bagikan.

    Kontrol akses tabel atau tabel virtual akan muncul di panel Bagikan.

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. 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 tampilan yang kebijakannya ingin Anda lihat
    • PATH_TO_FILE: jalur ke file JSON di komputer lokal Anda
  3. SQL

    Buat kueri tampilan INFORMATION_SCHEMA.OBJECT_PRIVILEGES. Kueri untuk mengambil kontrol akses untuk tabel atau tabel virtual harus menentukan object_schema dan object_name.

    1. Di Google Cloud konsol, buka halaman BigQuery.

      Buka BigQuery

    2. Di editor kueri, masukkan pernyataan berikut:

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

      Ganti kode berikut:

    3. Klik Run.

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

    Contoh:

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

    API

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

    Go

    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 mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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

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

    Node.js

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

Mencabut akses ke tabel atau tabel virtual

Untuk mencabut akses ke tabel atau tampilan, pilih salah satu opsi berikut:

Konsol

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel Explorer, luaskan project Anda, luaskan set data, lalu pilih tabel atau tampilan.

  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.

SQL

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

  1. Di Google Cloud konsol, buka halaman BigQuery.

    Buka BigQuery

  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 mengetahui informasi selengkapnya tentang cara menjalankan kueri, lihat artikel Menjalankan kueri interaktif.

Contoh berikut mencabut peran Pemilik Data BigQuery pada myTable:

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

bq

  1. In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

  2. Untuk mencabut akses ke tabel atau tampilan, 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 tabel virtual yang kebijakannya ingin Anda perbarui
  3. API

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

    2. Edit kebijakan untuk menghapus anggota atau binding, atau keduanya. Untuk mengetahui format yang diperlukan untuk kebijakan, lihat topik referensi Kebijakan.

    3. Panggil tables.setIamPolicy untuk menulis kebijakan yang diperbarui.

    Go

    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 mengetahui 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 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
    }
    

    Java

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

    Node.js

    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 mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk library klien.

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

Bekerja dengan kontrol akses untuk rutinitas

Untuk memberikan masukan atau meminta dukungan terkait fitur ini, kirim email ke bq-govsec-eng@google.com.

Anda dapat memberikan akses ke rutinitas dengan memberikan peran bawaan atau kustom ke pokok IAM yang menentukan apa yang dapat dilakukan pokok dengan rutinitas tersebut. Tindakan ini juga dikenal sebagai melampirkan kebijakan izin ke resource. Setelah memberikan akses, Anda dapat melihat kontrol akses untuk rutinitas, dan Anda dapat mencabut akses ke rutinitas.

Memberikan akses ke rutinitas

Untuk kontrol akses yang lebih mendetail, Anda dapat memberikan peran IAM standar atau kustom pada rutinitas tertentu. Rutinitas juga mewarisi kontrol akses yang ditentukan di tingkat set data dan yang lebih tinggi. Misalnya, jika Anda memberikan peran Pemilik Data BigQuery kepada akun utama di set data, akun utama tersebut juga memiliki izin Pemilik Data pada rutinitas di set data tersebut.

Pilih salah satu opsi berikut:

Konsol

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel Explorer, luaskan project Anda, luaskan set data Anda, luaskan Rutinitas, lalu pilih rutinitas.

  3. Klik Bagikan.

  4. Klik Tambahkan anggota.

  5. Di kolom New members, masukkan akun utama.

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

  7. Klik Simpan.

  8. Untuk kembali ke info rutinitas, klik Selesai.

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. Untuk menulis informasi rutin yang ada (termasuk kontrol akses) ke file JSON, gunakan perintah bq get-iam-policy:

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

    Ganti kode berikut:

    • PROJECT_ID: project ID Anda
    • DATASET: nama set data yang berisi rutin yang ingin Anda perbarui
    • ROUTINE: nama resource yang akan diupdate
    • PATH_TO_FILE: jalur ke file JSON di komputer lokal Anda
  3. Buat perubahan pada bagian bindings pada file JSON. Binding mengikat satu atau beberapa akun utama ke satu role. Akun utama dapat berupa akun pengguna, akun layanan, grup Google, dan domain. Misalnya, bagian bindings pada file JSON rutin akan terlihat seperti berikut:

    {
      "bindings": [
        {
          "role": "roles/bigquery.dataViewer",
          "members": [
            "user:user@example.com",
            "group:group@example.com",
            "domain:example.com",
          ]
        },
      ],
      "etag": "BwWWja0YfJA=",
      "version": 1
    }
  4. Untuk memperbarui kebijakan akses, gunakan perintah bq set-iam-policy:

    bq set-iam-policy PROJECT_ID:DATASET.ROUTINE PATH_TO_FILE
  5. Untuk memverifikasi perubahan kontrol akses Anda, gunakan perintah bq get-iam-policy lagi tanpa perlu menulis informasi tersebut ke file:

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

    1. Untuk mengambil kebijakan saat ini, panggil metode routines.getIamPolicy.

    2. Edit kebijakan untuk menambahkan akun utama, binding, atau keduanya. Untuk mengetahui format yang diperlukan untuk kebijakan, lihat topik referensi Kebijakan.

    3. Panggil routines.setIamPolicy untuk menulis kebijakan yang diperbarui.

Peran bawaan yang memberikan akses ke rutinitas

Untuk kontrol akses yang lebih mendetail, Anda dapat memberikan peran IAM standar atau kustom pada rutinitas tertentu. Rutinitas juga mewarisi kontrol akses yang ditentukan di tingkat set data dan yang lebih tinggi. Misalnya, jika Anda memberikan peran Pemilik Data kepada akun utama di set data, akun utama tersebut juga memiliki izin Pemilik Data pada rutinitas di set data melalui pewarisan.

Peran IAM bawaan berikut memiliki izin pada rutinitas.

Peran Deskripsi
BigQuery Data Owner (roles/bigquery.dataOwner) Jika diberikan secara rutin, peran ini memberikan izin berikut:
  • Semua izin untuk rutinitas.

Anda tidak boleh memberikan peran Pemilik Data di tingkat rutin. Editor Data juga memberikan semua izin untuk rutin dan merupakan peran yang kurang permisif.

BigQuery Data Editor (roles/bigquery.dataEditor) Jika diberikan secara rutin, peran ini memberikan izin berikut:
  • Semua izin untuk rutinitas.
BigQuery Data Viewer (roles/bigquery.dataViewer) Jika diberikan secara rutin, peran ini memberikan izin berikut:
  • Dalam kueri, merujuk ke rutinitas yang dibuat oleh orang lain.
BigQuery Metadata Viewer (roles/bigquery.metadataViewer) Jika diberikan secara rutin, peran ini memberikan izin berikut:
  • Dalam kueri, merujuk ke rutinitas yang dibuat oleh orang lain.

Izin untuk rutinitas

Sebagian besar izin yang dimulai dengan bigquery.routines berlaku di tingkat rutinitas. bigquery.routines.create dan bigquery.routines.list tidak. Untuk membuat dan mencantumkan rutinitas, izin bigquery.routines.create dan bigquery.routines.list harus diberikan ke peran pada penampung induk–set data.

Tabel berikut mencantumkan semua izin untuk rutinitas dan resource tingkat terendah yang dapat diberikan izinnya.

Izin Resource Deskripsi
bigquery.routines.create Set data Buat rutinitas dalam set data. Izin ini juga memerlukan bigquery.jobs.create untuk menjalankan tugas kueri yang berisi pernyataan CREATE FUNCTION.
bigquery.routines.delete Rutinitas Menghapus rutinitas.
bigquery.routines.get Rutinitas Mereferensikan rutinitas yang dibuat oleh orang lain. Izin ini juga memerlukan bigquery.jobs.create untuk menjalankan tugas kueri yang mereferensikan rutinitas, dan Anda juga memerlukan izin untuk mengakses resource apa pun yang dirujuk oleh rutinitas, seperti tabel atau tampilan.
bigquery.routines.list Set data Mencantumkan rutinitas dalam set data dan menampilkan metadata untuk rutinitas.
bigquery.routines.update Rutinitas Memperbarui metadata dan definisi rutinitas.
bigquery.routines.getIamPolicy Rutinitas Mendapatkan kontrol akses untuk rutinitas.
bigquery.routines.setIamPolicy Rutinitas Tetapkan kontrol akses untuk rutinitas.

Melihat kontrol akses untuk rutinitas

Untuk melihat kontrol akses rutin, pilih salah satu opsi berikut:

Konsol

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel Explorer, luaskan project Anda, luaskan set data, luaskan Rutinitas, lalu pilih rutinitas.

  3. Klik Bagikan.

    Kontrol akses rutin akan muncul di panel Bagikan.

bq

Perintah bq get-iam-policy tidak memberikan dukungan untuk melihat kontrol akses pada rutinitas.

SQL

Tampilan INFORMATION_SCHEMA.OBJECT_PRIVILEGES tidak menampilkan kontrol akses untuk rutinitas.

API

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

Mencabut akses ke rutinitas

Untuk mencabut akses ke rutinitas, pilih salah satu opsi berikut:

Konsol

  1. Buka halaman BigQuery.

    Buka BigQuery

  2. Di panel Explorer, luaskan project Anda, luaskan set data, luaskan Rutinitas, lalu pilih rutinitas.

  3. Di panel detail, klik Sharing > Permissions.

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

  5. Klik Remove principal.

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

  7. Klik Close.

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. Untuk menulis informasi rutin yang ada (termasuk kontrol akses) ke file JSON, gunakan perintah bq get-iam-policy:

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

    Ganti kode berikut:

    • PROJECT_ID: project ID Anda
    • DATASET: nama set data yang berisi rutin yang ingin Anda perbarui
    • ROUTINE: nama resource yang akan diupdate
    • PATH_TO_FILE: jalur ke file JSON di komputer lokal Anda

    Dalam file kebijakan, nilai untuk version tetap 1. Nomor ini merujuk pada versi skema kebijakan IAM, bukan versi kebijakan. Nilai untuk nilai etag adalah nomor versi kebijakan.

  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 rutin akan terlihat seperti berikut:

    {
     "bindings": [
       {
         "role": "roles/bigquery.dataViewer",
         "members": [
           "user:user@example.com",
           "group:group@example.com",
           "domain:google.com",
         ]
       },
     ],
     "etag": "BwWWja0YfJA=",
     "version": 1
    }
  4. Untuk memperbarui kebijakan akses, gunakan perintah bq set-iam-policy:

    bq set-iam-policy --routine PROJECT_ID:DATASET.ROUTINE PATH_TO_FILE
  5. Untuk memverifikasi perubahan kontrol akses Anda, gunakan kembali perintah get-iam-policy tanpa perlu menulis informasi tersebut ke file:

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

    1. Untuk mengambil kebijakan saat ini, panggil metode routines.getIamPolicy.

    2. Edit kebijakan untuk menambahkan akun utama atau binding, atau keduanya. Untuk mengetahui format yang diperlukan untuk kebijakan, lihat topik referensi Kebijakan.

Melihat kontrol akses yang diwarisi untuk resource

Anda dapat memeriksa peran IAM yang diwariskan untuk resource menggunakan UI web BigQuery. Anda memerlukan izin yang sesuai untuk melihat pewarisan di konsol. Untuk memeriksa pewarisan set data, tabel, tampilan, atau rutinitas:

  1. Di Google Cloud konsol, buka halaman BigQuery.

    Buka BigQuery

  2. Di panel Explorer, pilih set data, atau luaskan set data dan pilih tabel, tampilan, atau rutin.

  3. Untuk set data, klik Berbagi. Untuk tabel, tampilan, atau rutinitas, klik Bagikan.

  4. Pastikan opsi Show inherited roles in table diaktifkan.

    Opsi Tampilkan peran yang diwariskan dalam tabel di konsol

  5. Luaskan peran dalam tabel.

  6. Di kolom Pewarisan, ikon heksagonal menunjukkan apakah peran diwarisi dari resource induk.

    Ikon Diwarisi dari resource induk

Menolak akses ke resource

Kebijakan penolakan IAM memungkinkan Anda 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 mengetahui 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, rutin, set data, atau prosedur tersimpan) memungkinkan Anda membuat, menghapus, atau memanipulasi tabel, serta membaca dan mengubah data tabel, meskipun Anda tidak memiliki izin langsung untuk melakukan operasi tersebut. Prosedur ini juga dapat mendapatkan data atau metadata model dan memanggil prosedur tersimpan lainnya di tabel pokok. Kemampuan ini menunjukkan bahwa resource yang diberi otorisasi 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 diberi otorisasi ini, tambahkan salah satu nilai berikut ke kolom deniedPrincipal saat Anda membuat kebijakan penolakan:

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

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

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

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

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

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

Langkah berikutnya

Pelajari cara menggunakan metode projects.testIamPermissions untuk menguji akses pengguna ke resource.