IAM 정책을 비동기적으로 분석한 후 Cloud Storage에 결과 출력
코드 샘플
C#
Cloud 애셋 인벤토리에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
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
Cloud 애셋 인벤토리에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
// 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.")
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
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.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
Cloud 애셋 인벤토리에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
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
Cloud 애셋 인벤토리에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
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 = 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.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
Cloud 애셋 인벤토리에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
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
다음 단계
다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.