Analizar políticas de IAM de forma asíncrona y enviar los resultados a Cloud Storage

Analizar políticas de IAM de forma asíncrona y, luego, enviar los resultados a Cloud Storage

Muestra de código

C#


using Google.Cloud.Asset.V1;

public class AnalyzeIamPolicyLongrunningGcsSample
{
    public AnalyzeIamPolicyLongrunningResponse AnalyzeIamPolicyLongrunning(
      string scope, string fullResourceName, string uri)
    {
        // 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
            {
                GcsDestination = new IamPolicyAnalysisOutputConfig.Types.GcsDestination
                {
                    Uri = uri,
                },
            },
        };

        // 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


// 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"
	assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1"
)

func main() {
	scope := flag.String("scope", "", "Scope of the analysis.")
	fullResourceName := flag.String("fullResourceName", "", "Query resource.")
	uri := flag.String("uri", "", "Output GCS uri.")
	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_GcsDestination_{
				GcsDestination: &assetpb.IamPolicyAnalysisOutputConfig_GcsDestination{
					Uri: *uri,
				},
			},
		},
	}

	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

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.GcsDestination;
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 AnalyzeIamPolicyLongrunningGcsExample {

  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 uri = "gs://BUCKET_NAME/OBJECT_NAME";
    analyzeIamPolicyLongrunning(scope, fullResourceName, uri);
  }

  // Analyzes accessible IAM policies that match a request.
  public static void analyzeIamPolicyLongrunning(
      String scope, String fullResourceName, String uri) {
    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();

    GcsDestination gcsDestination = GcsDestination.newBuilder().setUri(uri).build();
    IamPolicyAnalysisOutputConfig outputConfig =
        IamPolicyAnalysisOutputConfig.newBuilder()
            .setGcsDestination(GcsDestination.newBuilder().setUri(uri).build())
            .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

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

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

async function analyzeIamPolicyLongrunningGcs() {
  // TODO(developer): choose the gcs path uri
  // const gcsUri = 'Gcs path uri, e.g.: gs://<my_bucket>/<my_analysis_file>'

  const request = {
    analysisQuery: {
      scope: `projects/${projectId}`,
      resourceSelector: {
        fullResourceName: `//cloudresourcemanager.googleapis.com/projects/${projectId}`,
      },
      options: {
        expandGroups: true,
        outputGroupEdges: true,
      },
    },
    outputConfig: {
      gcsDestination: {
        uri: gcsUri,
      },
    },
  };

  // 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

from google.cloud import asset_v1

# TODO project_id = 'Your Google Cloud Project ID'
# TODO dump_file_path = 'Your analysis dump file path'

client = asset_v1.AssetServiceClient()
parent = "projects/{}".format(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.gcs_destination.uri = dump_file_path
operation = client.analyze_iam_policy_longrunning(
    request={"analysis_query": analysis_query, "output_config": output_config}
)

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

Ruby

require "google/cloud/asset"

# scope = 'SCOPE_OF_THE_QUERY'
# full_resource_name = 'QUERY_RESOURCE'
# uri = 'OUTPUT_GCS_URI'
asset_service = Google::Cloud::Asset.asset_service

query = {
  scope:             scope,
  resource_selector: {
    full_resource_name: full_resource_name
  },
  options:           {
    expand_groups:      true,
    output_group_edges: true
  }
}
output_config = {
  gcs_destination: {
    uri: uri
  }
}

operation = asset_service.analyze_iam_policy_longrunning(
  analysis_query: query,
  output_config:  output_config
)

operation.wait_until_done!
puts "Wrote analysis results to: #{uri}"
# Do things with the result

¿Qué sigue?

Para buscar y filtrar muestras de código de otros productos de Google Cloud, consulta el navegador de muestras de Google Cloud.