IAM 정책을 비동기적으로 분석하고 BigQuery에 출력

IAM 정책을 비동기적으로 분석한 후 BigQuery에 결과 출력

코드 샘플


Cloud 애셋 인벤토리용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud 애셋 인벤토리 클라이언트 라이브러리를 참조하세요.

Cloud 애셋 인벤토리에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

using Google.Cloud.Asset.V1;

public class AnalyzeIamPolicyLongrunningBigquerySample
    public AnalyzeIamPolicyLongrunningResponse AnalyzeIamPolicyLongrunning(
      string scope, string fullResourceName, string dataset, string tablePrefix)
        // Create the client.
        AssetServiceClient client = AssetServiceClient.Create();

        // Build the request.
        AnalyzeIamPolicyLongrunningRequest request = new AnalyzeIamPolicyLongrunningRequest
            AnalysisQuery = new IamPolicyAnalysisQuery
                Scope = scope,
                ResourceSelector = new IamPolicyAnalysisQuery.Types.ResourceSelector
                    FullResourceName = fullResourceName,
                Options = new IamPolicyAnalysisQuery.Types.Options
                    ExpandGroups = true,
                    OutputGroupEdges = true,
            OutputConfig = new IamPolicyAnalysisOutputConfig
                BigqueryDestination = new IamPolicyAnalysisOutputConfig.Types.BigQueryDestination
                    Dataset = dataset,
                    TablePrefix = tablePrefix,

        // Start the analyze long-running operation
        var operation = client.AnalyzeIamPolicyLongrunning(request);
        // Wait for it to complete
        operation = operation.PollUntilCompleted();

        // Return the operation result. If the operation has failed
        // calling Result will throw.
        return operation.Result;


Cloud 애셋 인벤토리용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud 애셋 인벤토리 클라이언트 라이브러리를 참조하세요.

Cloud 애셋 인벤토리에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Sample analyze_iam_policy_longrunning analyzes accessible IAM policies that match a request.
package main

import (

	asset "cloud.google.com/go/asset/apiv1"

func main() {
	scope := flag.String("scope", "", "Scope of the analysis.")
	fullResourceName := flag.String("fullResourceName", "", "Query resource.")
	dataset := flag.String("dataset", "", "Output Bigquery Dataset.")
	tablePrefix := flag.String("tablePrefix", "", "Output Bigquery table prefix.")
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatalf("asset.NewClient: %v", err)
	defer client.Close()

	req := &assetpb.AnalyzeIamPolicyLongrunningRequest{
		AnalysisQuery: &assetpb.IamPolicyAnalysisQuery{
			Scope: *scope,
			ResourceSelector: &assetpb.IamPolicyAnalysisQuery_ResourceSelector{
				FullResourceName: *fullResourceName,
			Options: &assetpb.IamPolicyAnalysisQuery_Options{
				ExpandGroups:     true,
				OutputGroupEdges: true,
		OutputConfig: &assetpb.IamPolicyAnalysisOutputConfig{
			Destination: &assetpb.IamPolicyAnalysisOutputConfig_BigqueryDestination{
				BigqueryDestination: &assetpb.IamPolicyAnalysisOutputConfig_BigQueryDestination{
					Dataset:     *dataset,
					TablePrefix: *tablePrefix,

	op, err := client.AnalyzeIamPolicyLongrunning(ctx, req)
	if err != nil {
		log.Fatalf("AnalyzeIamPolicyLongrunning: %v", err)

	// Wait for the longrunning operation complete.
	resp, err := op.Wait(ctx)
	if err != nil && !op.Done() {
		fmt.Println("failed to fetch operation status", err)
	if err != nil && op.Done() {
		fmt.Println("operation completed with error", err)
	fmt.Println("operation completed successfully", resp)


Cloud 애셋 인벤토리용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud 애셋 인벤토리 클라이언트 라이브러리를 참조하세요.

Cloud 애셋 인벤토리에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import com.google.api.gax.rpc.ApiException;
import com.google.cloud.asset.v1.AnalyzeIamPolicyLongrunningRequest;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.IamPolicyAnalysisOutputConfig;
import com.google.cloud.asset.v1.IamPolicyAnalysisOutputConfig.BigQueryDestination;
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery;
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.Options;
import com.google.cloud.asset.v1.IamPolicyAnalysisQuery.ResourceSelector;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class AnalyzeIamPolicyLongrunningBigqueryExample {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String scope = "organizations/ORG_ID";
    String fullResourceName = "//cloudresourcemanager.googleapis.com/projects/PROJ_ID";
    String dataset = "projects/PROJ_ID/datasets/DATASET_ID";
    String tablePrefix = "TABLE_PREFIX";
    analyzeIamPolicyLongrunning(scope, fullResourceName, dataset, tablePrefix);

  // Analyzes accessible IAM policies that match a request.
  public static void analyzeIamPolicyLongrunning(
      String scope, String fullResourceName, String dataset, String tablePrefix) {
    ResourceSelector resourceSelector =
    Options options = Options.newBuilder().setExpandGroups(true).setOutputGroupEdges(true).build();
    IamPolicyAnalysisQuery query =

    BigQueryDestination bigQueryDestination =
    IamPolicyAnalysisOutputConfig outputConfig =

    AnalyzeIamPolicyLongrunningRequest request =

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AssetServiceClient client = AssetServiceClient.create()) {
          "Analyze completed successfully:\n"
              + client.analyzeIamPolicyLongrunningAsync(request).getMetadata().get());
    } catch (IOException e) {
      System.out.println("Failed to create client:\n" + e.toString());
    } catch (InterruptedException e) {
      System.out.println("Operation was interrupted:\n" + e.toString());
    } catch (ExecutionException e) {
      System.out.println("Operation was aborted:\n" + e.toString());
    } catch (ApiException e) {
      System.out.println("Error during AnalyzeIamPolicyLongrunning:\n" + e.toString());


Cloud 애셋 인벤토리용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud 애셋 인벤토리 클라이언트 라이브러리를 참조하세요.

Cloud 애셋 인벤토리에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

const util = require('util');
const {AssetServiceClient} = require('@google-cloud/asset');

const client = new AssetServiceClient();
const projectId = await client.getProjectId();

async function analyzeIamPolicyLongrunningBigquery() {
  // TODO(developer): choose the dataset and table prefix
  // const datasetId = ''
  // const tablePrefix = ''

  const request = {
    analysisQuery: {
      scope: `projects/${projectId}`,
      resourceSelector: {
        fullResourceName: `//cloudresourcemanager.googleapis.com/projects/${projectId}`,
      options: {
        expandGroups: true,
        outputGroupEdges: true,
    outputConfig: {
      bigqueryDestination: {
        dataset: `projects/${projectId}/datasets/${datasetId}`,
        tablePrefix: tablePrefix,

  // Handle the operation using the promise pattern.
  const [operation] = await client.analyzeIamPolicyLongrunning(request);

  // Operation#promise starts polling for the completion of the operation.
  const [result] = await operation.promise();

  // Do things with with the response.
  console.log(util.inspect(result, {depth: null}));


Cloud 애셋 인벤토리용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud 애셋 인벤토리 클라이언트 라이브러리를 참조하세요.

Cloud 애셋 인벤토리에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import asset_v1

# TODO project_id = 'Your Google Cloud Project ID'
# TODO dataset = 'Your BigQuery dataset path'
# TODO table = 'Your BigQuery table name'

client = asset_v1.AssetServiceClient()
parent = f"projects/{project_id}"

# Build analysis query
analysis_query = asset_v1.IamPolicyAnalysisQuery()
analysis_query.scope = parent
analysis_query.resource_selector.full_resource_name = (
analysis_query.options.expand_groups = True
analysis_query.options.output_group_edges = True

output_config = asset_v1.IamPolicyAnalysisOutputConfig()
output_config.bigquery_destination.dataset = dataset
output_config.bigquery_destination.table_prefix = table
output_config.bigquery_destination.write_disposition = "WRITE_TRUNCATE"
operation = client.analyze_iam_policy_longrunning(
    request={"analysis_query": analysis_query, "output_config": output_config}


다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.