分析 IAM 政策

分析 IAM 政策

代码示例

C#


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


// 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"
	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.")
	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

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

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

from google.cloud import asset_v1

# TODO project_id = 'Your Google Cloud Project ID'

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

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

Ruby

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

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器