Analisar políticas do IAM

Analisar políticas do IAM

Exemplo de código

C#

Para aprender a instalar e usar a biblioteca de cliente do Inventário de recursos do Cloud, consulte Bibliotecas de cliente do Cloud Asset Inventory.

Para autenticar no Inventário de recursos do Cloud, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


using Google.Cloud.Asset.V1;

public class AnalyzeIamPolicySample
{
    public AnalyzeIamPolicyResponse AnalyzeIamPolicy(string scope, string fullResourceName)
    {
        // Create the client.
        AssetServiceClient client = AssetServiceClient.Create();

        // Build the request.
        AnalyzeIamPolicyRequest request = new AnalyzeIamPolicyRequest
        {
            AnalysisQuery = new IamPolicyAnalysisQuery
            {
                Scope = scope,
                ResourceSelector = new IamPolicyAnalysisQuery.Types.ResourceSelector
                {
                    FullResourceName = fullResourceName,
                },
                Options = new IamPolicyAnalysisQuery.Types.Options
                {
                    ExpandGroups = true,
                    OutputGroupEdges = true,
                },
            },
        };

        // Call the API.
        AnalyzeIamPolicyResponse response = client.AnalyzeIamPolicy(request);

        // Return the result.
        return response;
    }
}

Go

Para saber como instalar e usar a biblioteca de cliente do Cloud Asset Inventory, consulte Bibliotecas de cliente do Cloud Asset Inventory.

Para autenticar no Inventário de recursos do Cloud, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.


// Sample analyze_iam_policy 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.")
	flag.Parse()
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatalf("asset.NewClient: %v", err)
	}
	defer client.Close()

	req := &assetpb.AnalyzeIamPolicyRequest{
		AnalysisQuery: &assetpb.IamPolicyAnalysisQuery{
			Scope: *scope,
			ResourceSelector: &assetpb.IamPolicyAnalysisQuery_ResourceSelector{
				FullResourceName: *fullResourceName,
			},
			Options: &assetpb.IamPolicyAnalysisQuery_Options{
				ExpandGroups:     true,
				OutputGroupEdges: true,
			},
		},
	}

	op, err := client.AnalyzeIamPolicy(ctx, req)
	if err != nil {
		log.Fatal(err)
	}
	for index, result := range op.MainAnalysis.AnalysisResults {
		fmt.Println(index, result)
	}
}

Java

Para aprender a instalar e usar a biblioteca de cliente do Inventário de recursos do Cloud, consulte Bibliotecas de cliente do Cloud Asset Inventory.

Para autenticar no Cloud Asset Inventory, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import com.google.api.gax.rpc.ApiException;
import com.google.cloud.asset.v1.AnalyzeIamPolicyRequest;
import com.google.cloud.asset.v1.AnalyzeIamPolicyResponse;
import com.google.cloud.asset.v1.AssetServiceClient;
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;

public class AnalyzeIamPolicyExample {

  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";
    analyzeIamPolicy(scope, fullResourceName);
  }

  // Analyzes accessible IAM policies that match a request.
  public static void analyzeIamPolicy(String scope, String fullResourceName) {
    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();
    AnalyzeIamPolicyRequest request =
        AnalyzeIamPolicyRequest.newBuilder().setAnalysisQuery(query).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()) {
      AnalyzeIamPolicyResponse response = client.analyzeIamPolicy(request);
      System.out.println("Analyze completed successfully:\n" + response);
    } catch (IOException e) {
      System.out.println("Failed to create client:\n" + e.toString());
    } catch (ApiException e) {
      System.out.println("Error during AnalyzeIamPolicy:\n" + e.toString());
    }
  }
}

Node.js

Para saber como instalar e usar a biblioteca de cliente do Cloud Asset Inventory, consulte Bibliotecas de cliente do Cloud Asset Inventory.

Para autenticar no Inventário de recursos do Cloud, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

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

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

async function analyzeIamPolicy() {
  const request = {
    analysisQuery: {
      scope: `projects/${projectId}`,
      resourceSelector: {
        fullResourceName: `//cloudresourcemanager.googleapis.com/projects/${projectId}`,
      },
      options: {
        expandGroups: true,
        outputGroupEdges: true,
      },
    },
  };

  // Handle the operation using the promise pattern.
  const result = await client.analyzeIamPolicy(request);
  // Do things with with the response.
  console.log(util.inspect(result, {depth: null}));
}

Python

Para aprender a instalar e usar a biblioteca de cliente do Inventário de recursos do Cloud, consulte Bibliotecas de cliente do Cloud Asset Inventory.

Para autenticar no Inventário de recursos do Cloud, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

from google.cloud import asset_v1

# TODO project_id = 'Your Google Cloud Project ID'

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

response = client.analyze_iam_policy(request={"analysis_query": analysis_query})
print(response)

Ruby

Para saber como instalar e usar a biblioteca de cliente do Cloud Asset Inventory, consulte Bibliotecas de cliente do Cloud Asset Inventory.

Para autenticar no Cloud Asset Inventory, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

require "google/cloud/asset"

# scope = 'SCOPE_OF_THE_QUERY'
# full_resource_name = 'QUERY_RESOURCE'
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
  }
}

response = asset_service.analyze_iam_policy analysis_query: query
# Do things with the response
puts response

A seguir

Para pesquisar e filtrar exemplos de código de outros produtos do Google Cloud, consulte a pesquisa de exemplos de código do Google Cloud.