Analyser les stratégies IAM de manière asynchrone et transmettre les résultats dans BigQuery

Analyser les stratégies IAM de manière asynchrone, puis transmettre les résultats dans BigQuery

Exemple de code

C#

Pour vous authentifier auprès de l'inventaire des éléments cloud, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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

Go

Pour vous authentifier auprès de l'inventaire des éléments cloud, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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

import (
	"context"
	"flag"
	"fmt"
	"log"

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

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.")
	flag.Parse()
	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)
	}
	fmt.Print(op.Metadata())

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

Java

Pour vous authentifier auprès de l'inventaire des éléments cloud, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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 =
        ResourceSelector.newBuilder().setFullResourceName(fullResourceName).build();
    Options options = Options.newBuilder().setExpandGroups(true).setOutputGroupEdges(true).build();
    IamPolicyAnalysisQuery query =
        IamPolicyAnalysisQuery.newBuilder()
            .setScope(scope)
            .setResourceSelector(resourceSelector)
            .setOptions(options)
            .build();

    BigQueryDestination bigQueryDestination =
        BigQueryDestination.newBuilder().setDataset(dataset).setTablePrefix(tablePrefix).build();
    IamPolicyAnalysisOutputConfig outputConfig =
        IamPolicyAnalysisOutputConfig.newBuilder()
            .setBigqueryDestination(bigQueryDestination)
            .build();

    AnalyzeIamPolicyLongrunningRequest request =
        AnalyzeIamPolicyLongrunningRequest.newBuilder()
            .setAnalysisQuery(query)
            .setOutputConfig(outputConfig)
            .build();

    // 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()) {
      System.out.println(
          "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());
    }
  }
}

Node.js

Pour vous authentifier auprès de l'inventaire des éléments cloud, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Python

Pour vous authentifier auprès de l'inventaire des éléments cloud, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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 = (
    f"//cloudresourcemanager.googleapis.com/{parent}"
)
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}
)

operation.result(300)
print(operation.done())

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'exemple de navigateur Google Cloud.