קבלת מדיניות IAM להחלפת נתונים (גרסה 1)

אחזור מדיניות ה-IAM של מאגר הניתוחים ב-Analysis לחילופי נתונים ב-Analytics Hub.

דוגמת קוד

Go

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Go במדריך למתחילים של BigQuery באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של BigQuery Go API.

כדי לבצע אימות ב-BigQuery, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לספריות לקוח.


import (
	"context"
	"fmt"
	"io"

	analyticshub "cloud.google.com/go/bigquery/analyticshub/apiv1"
	"cloud.google.com/go/iam/apiv1/iampb"
)

// getIamPolicy retrieves the IAM policy for an Analytics Hub data exchange.
func getIamPolicy(ctx context.Context, w io.Writer, projectID string, locationID string, dataExchangeID string) error {
	resource := fmt.Sprintf("projects/%s/locations/%s/dataExchanges/%s", projectID, locationID, dataExchangeID)

	client, err := analyticshub.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("analyticshub.NewClient: %w", err)
	}
	defer client.Close()

	req := &iampb.GetIamPolicyRequest{
		Resource: resource,
	}

	policy, err := client.GetIamPolicy(ctx, req)
	if err != nil {
		return fmt.Errorf("client.GetIamPolicy: %w", err)
	}

	fmt.Fprintf(w, "Retrieved IAM policy for %s\n", resource)
	for _, binding := range policy.GetBindings() {
		fmt.Fprintf(w, "Role: %s, Members: %v\n", binding.GetRole(), binding.GetMembers())
	}

	return nil
}

Java

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Java במדריך למתחילים של BigQuery באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של BigQuery Java API.

כדי לבצע אימות ב-BigQuery, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לספריות לקוח.

import com.google.cloud.bigquery.analyticshub.v1.AnalyticsHubServiceClient;
import com.google.cloud.bigquery.analyticshub.v1.DataExchangeName;
import com.google.iam.v1.GetIamPolicyRequest;
import com.google.iam.v1.Policy;
import java.io.IOException;

public class GetIamPolicy {

  public static void main(String[] args) throws IOException {
    String projectId = "example-project-id";
    String locationId = "example-location-id";
    String dataExchangeId = "example-data-exchange-id";
    getIamPolicy(projectId, locationId, dataExchangeId);
  }

  public static void getIamPolicy(String projectId, String locationId, String dataExchangeId)
      throws IOException {
    try (AnalyticsHubServiceClient client = AnalyticsHubServiceClient.create()) {
      String resource = DataExchangeName.of(projectId, locationId, dataExchangeId).toString();
      GetIamPolicyRequest request = GetIamPolicyRequest.newBuilder().setResource(resource).build();

      Policy policy = client.getIamPolicy(request);

      System.out.printf("Retrieved IAM policy for resource: %s%n", resource);
      System.out.printf("Policy version: %d%n", policy.getVersion());
    }
  }
}

Node.js

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Node.js במדריך למתחילים של BigQuery באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של BigQuery Node.js API.

כדי לבצע אימות ב-BigQuery, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לספריות לקוח.

'use strict';

const {AnalyticsHubServiceClient} = require('@google-cloud/bigquery-analyticshub');
const {status} = require('@grpc/grpc-js');

const client = new AnalyticsHubServiceClient();

/**
 * Retrieves the IAM policy for a specified Analytics Hub data exchange.
 *
 * @param {string} projectId - The Google Cloud project ID.
 * @param {string} locationId - The geographic location where the data exchange resides (for example, 'us' or 'us-central1').
 * @param {string} dataExchangeId - The ID of the data exchange to retrieve the IAM policy for.
 */
async function getIamPolicy(projectId, locationId, dataExchangeId) {
  try {
    const resource = `projects/${projectId}/locations/${locationId}/dataExchanges/${dataExchangeId}`;

    const request = {
      resource: resource,
    };

    const [policy] = await client.getIamPolicy(request);

    console.log(`Retrieved IAM policy for resource: ${resource}`);
    console.log('Policy version:', policy.version);
    console.log('Bindings:');
    if (policy.bindings && policy.bindings.length > 0) {
      for (const binding of policy.bindings) {
        console.log(`  Role: ${binding.role}`);
        console.log(`  Members: ${binding.members.join(', ')}`);
      }
    } else {
      console.log('  No bindings found.');
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Specified resource not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied while retrieving IAM policy: ${err.message}`);
    } else {
      console.error(`Failed to retrieve IAM policy: ${err.message}`);
    }
  }
}

module.exports = { getIamPolicy };

Python

לפני שמנסים את הדוגמה הזו, צריך לפעול לפי הוראות ההגדרה של Python במדריך למתחילים של BigQuery באמצעות ספריות לקוח. למידע נוסף, קראו את מאמרי העזרה של BigQuery Python API.

כדי לבצע אימות ב-BigQuery, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לספריות לקוח.

import google.api_core.exceptions
from google.cloud import bigquery_analyticshub_v1


def get_iam_policy(project_id: str, location_id: str, data_exchange_id: str) -> None:
    """Retrieves the IAM policy for a data exchange resource.

    Args:
        project_id: The Google Cloud project ID hosting the data exchange.
        location_id: The geographic location of the data exchange.
        data_exchange_id: The identifier of the data exchange.
    """
    client = bigquery_analyticshub_v1.AnalyticsHubServiceClient()

    resource = (
        f"projects/{project_id}/locations/{location_id}/dataExchanges/{data_exchange_id}"
    )

    request = {"resource": resource}

    try:
        policy = client.get_iam_policy(request=request)
        print(f"Retrieved IAM policy for resource: {resource}")
        print(f"Policy version: {policy.version}")
        for binding in policy.bindings:
            print(f"Role: {binding.role}")
            for member in binding.members:
                print(f"  Member: {member}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"Failed to retrieve IAM policy: {e}")

המאמרים הבאים

כדי לחפש ולסנן דוגמאות קוד למוצרים אחרים של Google Cloud , ראו דפדפן לדוגמה שלGoogle Cloud .