Cloud 애셋 인벤토리 클라이언트 라이브러리

이 페이지에서는 Cloud Asset Inventory API의 Cloud 클라이언트 라이브러리를 시작하는 방법을 보여줍니다. 클라이언트 라이브러리를 사용하면 지원되는 언어로 Google Cloud API에 쉽게 액세스할 수 있습니다. 원시 요청을 서버에 보내 Google Cloud API를 직접 사용할 수 있지만 클라이언트 라이브러리는 작성해야 하는 코드 양을 크게 줄여 주는 간소화 기능을 제공합니다.

클라이언트 라이브러리 설명에서 Cloud 클라이언트 라이브러리 및 이전 Google API 클라이언트 라이브러리에 대해 자세히 알아보세요.

클라이언트 라이브러리 설치

C#

패키지 관리자

Install-Package Google.Cloud.Asset.V1

.NET CLI

dotnet add package Google.Cloud.Asset.V1

패킷 CLI

packet add Google.Cloud.Asset.V1

자세한 내용은 C# 개발 환경 설정을 참조하세요.

Go

go get cloud.google.com/go/asset/apiv1

자세한 내용은 Go 개발 환경 설정을 참조하세요.

Java

Maven을 사용하는 경우 pom.xml 파일에 다음을 추가합니다.

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-asset</artifactId>
    <version>DESIRED_VERSION_NUMBER</version>
</dependency>

Gradle을 사용하는 경우 종속 항목에 다음을 추가합니다.

compile group: 'com.google.cloud', name: 'google-cloud-asset', version: 'DESIRED_VERSION_NUMBER'

자세한 내용은 Java 개발 환경 설정을 참조하세요.

Node.js

npm install --save @google-cloud/asset

자세한 내용은 Node.js 개발 환경 설정을 참조하세요.

PHP

composer require google/cloud-asset

자세한 내용은 Google Cloud에서 PHP 사용을 참조하세요.

Python

pip install --upgrade google-cloud-asset

자세한 내용은 Python 개발 환경 설정을 참조하세요.

Ruby

gem install google-cloud-asset

자세한 내용은 Ruby 개발 환경 설정을 참조하세요.

인증 설정

Google Cloud API 호출을 인증하기 위해 클라이언트 라이브러리는 애플리케이션 기본 사용자 인증 정보(ADC)를 지원합니다. 라이브러리가 정의된 위치 집합에서 사용자 인증 정보를 찾고 이러한 사용자 인증 정보를 사용하여 API에 대한 요청을 인증합니다. ADC를 사용하면 애플리케이션 코드를 수정할 필요 없이 로컬 개발 또는 프로덕션과 같은 다양한 환경에서 애플리케이션에 사용자 인증 정보를 제공할 수 있습니다.

프로덕션 환경에서 ADC를 설정하는 방법은 서비스와 컨텍스트에 따라 다릅니다. 자세한 내용은 애플리케이션 기본 사용자 인증 정보 설정을 참조하세요.

로컬 개발 환경의 경우 Google 계정과 연결된 사용자 인증 정보를 사용하여 ADC를 설정할 수 있습니다.

  1. gcloud CLI를 설치하고 초기화합니다.

    gcloud CLI를 초기화할 때 애플리케이션에 필요한 리소스에 액세스할 수 있는 권한이 있는 Google Cloud 프로젝트를 지정해야 합니다.

  2. 사용자 인증 정보 파일을 만듭니다.

    gcloud auth application-default login

    로그인 화면이 표시됩니다. 로그인 후 사용자 인증 정보는 ADC에 사용하는 로컬 사용자 인증 정보 파일에 저장됩니다.

클라이언트 라이브러리 사용

다음 예시에서는 클라이언트 라이브러리를 사용하는 방법을 보여줍니다.

C#

ExportAssets


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Asset.V1;

public class ExportAssetsSample
{
    public ExportAssetsResponse ExportAssets(string bucketName, string projectId)
    {
        string assetDumpFile = $"gs://{bucketName}/my-assets.txt";
        // Create the client
        AssetServiceClient client = AssetServiceClient.Create();
        // Build the request
        ExportAssetsRequest request = new ExportAssetsRequest
        {
            ParentAsResourceName = ProjectName.FromProject(projectId),
            OutputConfig = new OutputConfig
            {
                GcsDestination = new GcsDestination { Uri = assetDumpFile }
            }
        };
        // Start the long-running export operation
        var operation = client.ExportAssets(request);
        // Wait for it to complete (or fail)
        operation = operation.PollUntilCompleted();
        // Return the result
        return operation.Result;
    }
}

BatchGetAssetsHistory


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Asset.V1;
using Google.Protobuf.WellKnownTypes;
using System;

public class BatchGetAssetsHistorySample
{
    public BatchGetAssetsHistoryResponse BatchGetAssetsHistory(string[] assetNames, DateTimeOffset startTime, string projectId)
    {
        // Create the client.
        AssetServiceClient client = AssetServiceClient.Create();

        // Build the request.
        BatchGetAssetsHistoryRequest request = new BatchGetAssetsHistoryRequest
        {
            ParentAsResourceName = ProjectName.FromProject(projectId),
            ContentType = ContentType.Resource,
            ReadTimeWindow = new TimeWindow
            {
                StartTime = Timestamp.FromDateTimeOffset(startTime)
            }
        };
        request.AssetNames.AddRange(assetNames);

        // Call the API.
        BatchGetAssetsHistoryResponse response = client.BatchGetAssetsHistory(request);

        // Return the result.
        return response;
    }
}

ListAssets


using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Asset.V1;

public class ListAssetsSample
{
    public  PagedEnumerable<ListAssetsResponse, Asset> ListAssets(string projectId)
    {
        // Create the client.
        AssetServiceClient client = AssetServiceClient.Create();

        // Build the request.
        ListAssetsRequest request = new ListAssetsRequest
        {
            ParentAsResourceName = ProjectName.FromProject(projectId),
            ContentType = ContentType.Resource,
        };

        // Call the API.
         PagedEnumerable<ListAssetsResponse, Asset> response = client.ListAssets(request);

        // Return the result.
        return response;
    }
}

SearchAllIamPolicies


using Google.Api.Gax;
using Google.Cloud.Asset.V1;
using System.Collections.Generic;
using System.Linq;

public class SearchAllIamPoliciesSample
{
    public SearchAllIamPoliciesResponse SearchAllIamPolicies(string scope, string query)
    {
        // Create the client.
        AssetServiceClient client = AssetServiceClient.Create();

        // Build the request.
        SearchAllIamPoliciesRequest request = new SearchAllIamPoliciesRequest
        {
            Scope = scope,
            Query = query,
        };

        // Call the API.
        PagedEnumerable<SearchAllIamPoliciesResponse, IamPolicySearchResult> response = client.SearchAllIamPolicies(request);

        // Return the first page.
        IEnumerable<SearchAllIamPoliciesResponse> byPages = response.AsRawResponses();
        return byPages.First();
    }
}

SearchAllResources


using Google.Api.Gax;
using Google.Cloud.Asset.V1;
using System.Collections.Generic;
using System.Linq;

public class SearchAllResourcesSample
{
    public SearchAllResourcesResponse SearchAllResources(string scope, string query)
    {
        // Create the client.
        AssetServiceClient client = AssetServiceClient.Create();

        // Build the request.
        SearchAllResourcesRequest request = new SearchAllResourcesRequest
        {
            Scope = scope,
            Query = query,
        };

        // Call the API.
        PagedEnumerable<SearchAllResourcesResponse, ResourceSearchResult> response = client.SearchAllResources(request);

        // Return the first page.
        IEnumerable<SearchAllResourcesResponse> byPages = response.AsRawResponses();
        return byPages.First();
    }
}

Go

ExportAssetsGcs


// Sample asset-quickstart exports assets to given path.
package main

import (
	"context"
	"fmt"
	"log"
	"os"

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

func main() {
	ctx := context.Background()
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()
	bucketName := fmt.Sprintf("%s-for-assets", projectID)
	assetDumpFile := fmt.Sprintf("gs://%s/my-assets.txt", bucketName)
	req := &assetpb.ExportAssetsRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		OutputConfig: &assetpb.OutputConfig{
			Destination: &assetpb.OutputConfig_GcsDestination{
				GcsDestination: &assetpb.GcsDestination{
					ObjectUri: &assetpb.GcsDestination_Uri{
						Uri: string(assetDumpFile),
					},
				},
			},
		},
	}
	operation, err := client.ExportAssets(ctx, req)
	if err != nil {
		log.Fatal(err)
	}
	response, err := operation.Wait(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(response)
}

ExportAssetsBigQuery


// Sample asset-quickstart exports assets to given bigquery table.
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"

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

func main() {
	ctx := context.Background()
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatalf("asset.NewClient: %v", err)
	}
	defer client.Close()
	datasetID := strings.Replace(fmt.Sprintf("%s-for-assets", projectID), "-", "_", -1)
	dataset := fmt.Sprintf("projects/%s/datasets/%s", projectID, datasetID)
	req := &assetpb.ExportAssetsRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		OutputConfig: &assetpb.OutputConfig{
			Destination: &assetpb.OutputConfig_BigqueryDestination{
				BigqueryDestination: &assetpb.BigQueryDestination{
					Dataset: dataset,
					Table:   "test",
					Force:   true,
				},
			},
		},
	}
	op, err := client.ExportAssets(ctx, req)
	if err != nil {
		log.Fatalf("ExportAssets: %v", err)
	}
	resp, err := op.Wait(ctx)
	if err != nil {
		log.Fatalf("Wait: %v", err)
	}
	fmt.Print(resp)
}

BatchGetAssetsHistory


// Sample asset-quickstart batch-gets assets history.
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	asset "cloud.google.com/go/asset/apiv1"
	"cloud.google.com/go/asset/apiv1/assetpb"
	"github.com/golang/protobuf/ptypes/timestamp"
)

func main() {
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	bucketResourceName := fmt.Sprintf("//storage.googleapis.com/%s-for-assets", projectID)
	req := &assetpb.BatchGetAssetsHistoryRequest{
		Parent:      fmt.Sprintf("projects/%s", projectID),
		AssetNames:  []string{bucketResourceName},
		ContentType: assetpb.ContentType_RESOURCE,
		ReadTimeWindow: &assetpb.TimeWindow{
			StartTime: &timestamp.Timestamp{
				Seconds: time.Now().Unix(),
			},
		},
	}
	response, err := client.BatchGetAssetsHistory(ctx, req)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Print(response)
}

ListAssets


// Sample list-assets list assets.
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"google.golang.org/api/iterator"

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

func main() {
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	assetType := "storage.googleapis.com/Bucket"
	req := &assetpb.ListAssetsRequest{
		Parent:      fmt.Sprintf("projects/%s", projectID),
		AssetTypes:  []string{assetType},
		ContentType: assetpb.ContentType_RESOURCE,
	}

	// Call ListAssets API to get an asset iterator.
	it := client.ListAssets(ctx, req)

	// Traverse and print the first 10 listed assets in response.
	for i := 0; i < 10; i++ {
		response, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(response)
	}
}

SearchAllIamPolicies


// Sample search-all-iam-policies searches all IAM policies within the given scope.
package main

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

	asset "cloud.google.com/go/asset/apiv1"
	"cloud.google.com/go/asset/apiv1/assetpb"
	"google.golang.org/api/iterator"
)

func main() {
	scope := flag.String("scope", "", "Scope of the search.")
	query := flag.String("query", "", "Query statement.")
	flag.Parse()
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatalf("asset.NewClient: %v", err)
	}
	defer client.Close()

	req := &assetpb.SearchAllIamPoliciesRequest{
		Scope: *scope,
		Query: *query,
	}
	it := client.SearchAllIamPolicies(ctx, req)
	for {
		policy, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(policy)
	}
}

SearchAllResources


// Sample search-all-resources searches all resources within the given scope.
package main

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

	asset "cloud.google.com/go/asset/apiv1"
	"cloud.google.com/go/asset/apiv1/assetpb"
	"google.golang.org/api/iterator"
)

func main() {
	scope := flag.String("scope", "", "Scope of the search.")
	query := flag.String("query", "", "Query statement.")
	flag.Parse()
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatalf("asset.NewClient: %v", err)
	}
	defer client.Close()

	req := &assetpb.SearchAllResourcesRequest{
		Scope: *scope,
		Query: *query,
	}
	it := client.SearchAllResources(ctx, req)
	for {
		resource, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(resource)
	}
}

Java

ExportAssetsGcs

// Imports the Google Cloud client library

import com.google.cloud.ServiceOptions;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.ContentType;
import com.google.cloud.asset.v1.ExportAssetsRequest;
import com.google.cloud.asset.v1.ExportAssetsRequest.Builder;
import com.google.cloud.asset.v1.ExportAssetsResponse;
import com.google.cloud.asset.v1.GcsDestination;
import com.google.cloud.asset.v1.OutputConfig;
import com.google.cloud.asset.v1.ProjectName;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ExportAssetsExample {

  // Use the default project Id.
  private static final String projectId = ServiceOptions.getDefaultProjectId();

  /**
   * Export assets for a project.
   *
   * @param exportPath where the results will be exported to
   * @param contentType determines the schema for the table
   * @param assetTypes a list of asset types to export. if empty, export all.
   */
  public static void exportAssets(String exportPath, ContentType contentType, String[] assetTypes)
      throws IOException,
          IllegalArgumentException,
          InterruptedException,
          ExecutionException,
          TimeoutException {
    try (AssetServiceClient client = AssetServiceClient.create()) {
      ProjectName parent = ProjectName.of(projectId);
      OutputConfig outputConfig =
          OutputConfig.newBuilder()
              .setGcsDestination(GcsDestination.newBuilder().setUri(exportPath).build())
              .build();
      Builder exportAssetsRequestBuilder =
          ExportAssetsRequest.newBuilder()
              .setParent(parent.toString())
              .setContentType(contentType)
              .setOutputConfig(outputConfig);
      if (assetTypes.length > 0) {
        exportAssetsRequestBuilder.addAllAssetTypes(Arrays.asList(assetTypes));
      }
      ExportAssetsRequest request = exportAssetsRequestBuilder.build();
      ExportAssetsResponse response = client.exportAssetsAsync(request).get(5, TimeUnit.MINUTES);
      System.out.println(response);
    }
  }
}

ExportAssetsBigQuery

// Imports the Google Cloud client library

import com.google.cloud.ServiceOptions;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.BigQueryDestination;
import com.google.cloud.asset.v1.ContentType;
import com.google.cloud.asset.v1.ExportAssetsRequest;
import com.google.cloud.asset.v1.ExportAssetsRequest.Builder;
import com.google.cloud.asset.v1.ExportAssetsResponse;
import com.google.cloud.asset.v1.OutputConfig;
import com.google.cloud.asset.v1.PartitionSpec;
import com.google.cloud.asset.v1.ProjectName;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;

public class ExportAssetsBigqueryExample {

  // Use the default project Id.
  private static final String projectId = ServiceOptions.getDefaultProjectId();

  /**
   * Export assets to BigQuery for a project.

   * @param bigqueryDataset which dataset the results will be exported to
   * @param bigqueryTable which table the results will be exported to
   * @param contentType determines the schema for the table
   * @param assetTypes a list of asset types to export. if empty, export all.
   * @param isPerType separate BigQuery tables for each resource type
   */
  public static void exportBigQuery(String bigqueryDataset, String bigqueryTable,
      ContentType contentType, String[] assetTypes, boolean isPerType)
      throws IOException, IllegalArgumentException, InterruptedException, ExecutionException {
    try (AssetServiceClient client = AssetServiceClient.create()) {
      ProjectName parent = ProjectName.of(projectId);
      OutputConfig outputConfig;
      // Outputs to per-type BigQuery table.
      if (isPerType) {
        outputConfig =
            OutputConfig.newBuilder()
                .setBigqueryDestination(
                    BigQueryDestination.newBuilder()
                        .setDataset(bigqueryDataset)
                        .setTable(bigqueryTable)
                        .setForce(true)
                        .setSeparateTablesPerAssetType(true)
                        .setPartitionSpec(
                            PartitionSpec.newBuilder()
                                .setPartitionKey(PartitionSpec.PartitionKey.READ_TIME)
                                .build())
                        .build())
                .build();
      } else {
        outputConfig =
            OutputConfig.newBuilder()
                .setBigqueryDestination(
                    BigQueryDestination.newBuilder()
                        .setDataset(bigqueryDataset)
                        .setTable(bigqueryTable)
                        .setForce(true)
                        .build())
                .build();
      }
      Builder exportAssetsRequestBuilder = ExportAssetsRequest.newBuilder()
          .setParent(parent.toString()).setContentType(contentType).setOutputConfig(outputConfig);
      if (assetTypes.length > 0) {
        exportAssetsRequestBuilder.addAllAssetTypes(Arrays.asList(assetTypes));
      }
      ExportAssetsRequest request = exportAssetsRequestBuilder.build();
      ExportAssetsResponse response = client.exportAssetsAsync(request).get();
      System.out.println(response);
    }
  }
}

BatchGetAssetsHistory

// Imports the Google Cloud client library

import com.google.cloud.ServiceOptions;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.BatchGetAssetsHistoryRequest;
import com.google.cloud.asset.v1.BatchGetAssetsHistoryResponse;
import com.google.cloud.asset.v1.ContentType;
import com.google.cloud.asset.v1.ProjectName;
import com.google.cloud.asset.v1.TimeWindow;
import java.util.Arrays;

public class BatchGetAssetsHistoryExample {

  // Use the default project Id.
  private static final String projectId = ServiceOptions.getDefaultProjectId();

  // Export assets for a project.
  // @param args path where the results will be exported to.
  public static void main(String... args) throws Exception {
    // Asset names, e.g.: "//storage.googleapis.com/[BUCKET_NAME]"
    String[] assetNames = args[0].split(",");
    try (AssetServiceClient client = AssetServiceClient.create()) {
      ProjectName parent = ProjectName.of(projectId);
      ContentType contentType = ContentType.CONTENT_TYPE_UNSPECIFIED;
      TimeWindow readTimeWindow = TimeWindow.newBuilder().build();
      BatchGetAssetsHistoryRequest request =
          BatchGetAssetsHistoryRequest.newBuilder()
              .setParent(parent.toString())
              .addAllAssetNames(Arrays.asList(assetNames))
              .setContentType(contentType)
              .setReadTimeWindow(readTimeWindow)
              .build();
      BatchGetAssetsHistoryResponse response = client.batchGetAssetsHistory(request);
      System.out.println(response);
    }
  }
}

ListAssets

// Imports the Google Cloud client library

public class ListAssetsExample {

  public static void listAssets() throws IOException, IllegalArgumentException {
    // The project id of the asset parent to list.
    String projectId = "YOUR_PROJECT_ID";
    // The asset types to list. E.g.,
    // ["storage.googleapis.com/Bucket", "bigquery.googleapis.com/Table"].
    // See full list of supported asset types at
    // https://cloud.google.com/asset-inventory/docs/supported-asset-types.
    String[] assetTypes = {"YOUR_ASSET_TYPES_TO_LIST"};
    // The asset content type to list. E.g., ContentType.CONTENT_TYPE_UNSPECIFIED.
    // See full list of content types at
    // https://cloud.google.com/asset-inventory/docs/reference/rpc/google.cloud.asset.v1#contenttype
    ContentType contentType = ContentType.CONTENT_TYPE_UNSPECIFIED;
    listAssets(projectId, assetTypes, contentType);
  }

  public static void listAssets(String projectId, String[] assetTypes, ContentType contentType)
      throws IOException, IllegalArgumentException {
    try (AssetServiceClient client = AssetServiceClient.create()) {
      ProjectName parent = ProjectName.of(projectId);

      // Build initial ListAssetsRequest without setting page token.
      ListAssetsRequest request =
          ListAssetsRequest.newBuilder()
              .setParent(parent.toString())
              .addAllAssetTypes(Arrays.asList(assetTypes))
              .setContentType(contentType)
              .build();

      // Repeatedly call ListAssets until page token is empty.
      ListAssetsPagedResponse response = client.listAssets(request);
      System.out.println(response);
      while (!response.getNextPageToken().isEmpty()) {
        request = request.toBuilder().setPageToken(response.getNextPageToken()).build();
        response = client.listAssets(request);
        System.out.println(response);
      }
    }
  }
}

CreateFeed

import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.ContentType;
import com.google.cloud.asset.v1.CreateFeedRequest;
import com.google.cloud.asset.v1.Feed;
import com.google.cloud.asset.v1.FeedOutputConfig;
import com.google.cloud.asset.v1.ProjectName;
import com.google.cloud.asset.v1.PubsubDestination;
import java.io.IOException;
import java.util.Arrays;

public class CreateFeedExample {
  // Create a feed
  public static void createFeed(
      String[] assetNames, String feedId, String topic, String projectId, ContentType contentType)
      throws IOException, IllegalArgumentException {
    // String[] assetNames = {"MY_ASSET_NAME"}
    // ContentType contentType = contentType
    // String FeedId = "MY_FEED_ID"
    // String topic = "projects/[PROJECT_ID]/topics/[TOPIC_NAME]"
    // String projectID = "MY_PROJECT_ID"
    Feed feed =
        Feed.newBuilder()
            .addAllAssetNames(Arrays.asList(assetNames))
            .setContentType(contentType)
            .setFeedOutputConfig(
                FeedOutputConfig.newBuilder()
                    .setPubsubDestination(PubsubDestination.newBuilder().setTopic(topic).build())
                    .build())
            .build();
    CreateFeedRequest request =
        CreateFeedRequest.newBuilder()
            .setParent(String.format(ProjectName.of(projectId).toString()))
            .setFeedId(feedId)
            .setFeed(feed)
            .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()) {
      Feed response = client.createFeed(request);
      System.out.println("Feed created successfully: " + response.getName());
    } catch (IOException | IllegalArgumentException e) {
      System.out.println("Error during CreateFeed: \n" + e.toString());
    }
  }
}

SearchAllIamPolicies

import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.AssetServiceClient.SearchAllIamPoliciesPagedResponse;
import com.google.cloud.asset.v1.SearchAllIamPoliciesRequest;
import java.io.IOException;

public class SearchAllIamPoliciesExample {

  // Searches for all the iam policies within the given scope.
  public static void searchAllIamPolicies(String scope, String query) {
    // TODO(developer): Replace these variables before running the sample.
    int pageSize = 0;
    String pageToken = "";

    SearchAllIamPoliciesRequest request =
        SearchAllIamPoliciesRequest.newBuilder()
            .setScope(scope)
            .setQuery(query)
            .setPageSize(pageSize)
            .setPageToken(pageToken)
            .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()) {
      SearchAllIamPoliciesPagedResponse response = client.searchAllIamPolicies(request);
      System.out.println("Search completed successfully:\n" + response.getPage().getValues());
    } catch (IOException e) {
      System.out.println(String.format("Failed to create client:%n%s", e.toString()));
    } catch (InvalidArgumentException e) {
      System.out.println(String.format("Invalid request:%n%s", e.toString()));
    } catch (ApiException e) {
      System.out.println(String.format("Error during SearchAllIamPolicies:%n%s", e.toString()));
    }
  }
}

SearchAllResources

import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.AssetServiceClient.SearchAllResourcesPagedResponse;
import com.google.cloud.asset.v1.SearchAllResourcesRequest;
import java.io.IOException;
import java.util.Arrays;

public class SearchAllResourcesExample {

  // Searches for all the resources within the given scope.
  public static void searchAllResources(String scope, String query) {
    // TODO(developer): Replace these variables before running the sample.
    String[] assetTypes = {};
    int pageSize = 0;
    String pageToken = "";
    String orderBy = "";

    SearchAllResourcesRequest request =
        SearchAllResourcesRequest.newBuilder()
            .setScope(scope)
            .setQuery(query)
            .addAllAssetTypes(Arrays.asList(assetTypes))
            .setPageSize(pageSize)
            .setPageToken(pageToken)
            .setOrderBy(orderBy)
            .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()) {
      SearchAllResourcesPagedResponse response = client.searchAllResources(request);
      System.out.println("Search completed successfully:\n" + response.getPage().getValues());
    } catch (IOException e) {
      System.out.println(String.format("Failed to create client:%n%s", e.toString()));
    } catch (InvalidArgumentException e) {
      System.out.println(String.format("Invalid request:%n%s", e.toString()));
    } catch (ApiException e) {
      System.out.println(String.format("Error during SearchAllResources:%n%s", e.toString()));
    }
  }
}

Node.js

ExportAssets

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const dumpFilePath = 'gs://my-bucket/my-assets.txt';
// const contentType = 'RESOURCE';

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

async function exportAssets() {
  const projectId = await client.getProjectId();
  const projectResource = `projects/${projectId}`;

  // TODO(developer): choose the dump file path
  // const dumpFilePath = 'Dump file path, e.g.: gs://<my_bucket>/<my_asset_file>'
  const request = {
    parent: projectResource,
    contentType: contentType,
    outputConfig: {
      gcsDestination: {
        uri: dumpFilePath,
      },
    },
  };

  // Handle the operation using the promise pattern.
  const [operation] = await client.exportAssets(request);

  // Operation#promise starts polling for the completion of the operation.
  const [result] = await operation.promise();

  // Do things with with the response.
  console.log(result);
}
exportAssets().catch(err => {
  throw err;
});

BatchGetAssetsHistory

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const assetNames = '//storage.googleapis.com/<BUCKET_NAME1>,//storage.googleapis.com/<BUCKET_NAME2>';
// const contentType = 'RESOURCE';

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

const client = new AssetServiceClient();

async function batchGetAssetsHistory() {
  const projectId = await client.getProjectId();
  const projectResource = `projects/${projectId}`;
  // TODO(developer): Choose asset names, such as //storage.googleapis.com/[YOUR_BUCKET_NAME].
  // const assetNames = ['ASSET_NAME1', 'ASSET_NAME2', ...];

  const request = {
    parent: projectResource,
    assetNames: assetNames.split(','),
    contentType: contentType,
    readTimeWindow: {
      startTime: {
        seconds: Math.floor(new Date().getTime() / 1000),
      },
    },
  };

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

ListAssets

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const assetTypes = 'storage.googleapis.com/Bucket,bigquery.googleapis.com/Table';
// const contentType = 'RESOURCE';

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

const projectId = await client.getProjectId();
const projectResource = `projects/${projectId}`;
// TODO(developer): Choose types of assets to list, such as 'storage.googleapis.com/Bucket':
//   const assetTypes = 'storage.googleapis.com/Bucket,bigquery.googleapis.com/Table';
// Or simply use empty string to list all types of assets:
//   const assetTypes = '';
const assetTypesList = assetTypes ? assetTypes.split(',') : [];

async function listAssets() {
  const request = {
    parent: projectResource,
    assetTypes: assetTypesList,
    contentType: contentType,
    // (Optional) Add readTime parameter to list assets at the given time instead of current time:
    //   readTime: { seconds: 1593988758 },
  };

  // Call cloud.assets.v1.ListAssets API.
  const result = await client.listAssets(request);
  // Handle the response.
  console.log(util.inspect(result, {depth: null}));
}
listAssets();

CreateFeed

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const feedId = 'my feed';
// const assetNames = '//storage.googleapis.com/<BUCKET_NAME1>,//storage.googleapis.com/<BUCKET_NAME2>';
// const topicName = 'projects/<PROJECT_ID>/topics/<TOPIC_ID>'
// const contentType = 'RESOURCE';

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

const client = new AssetServiceClient();

async function createFeed() {
  const projectId = await client.getProjectId();
  // TODO(developer): Choose asset names, such as //storage.googleapis.com/[YOUR_BUCKET_NAME].
  // const assetNames = ['ASSET_NAME1', 'ASSET_NAME2', ...];

  const request = {
    parent: `projects/${projectId}`,
    feedId: feedId,
    feed: {
      assetNames: assetNames.split(','),
      contentType: contentType,
      feedOutputConfig: {
        pubsubDestination: {
          topic: topicName,
        },
      },
    },
  };

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

SearchAllIamPolicies

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const scope = '';
// const query = '';
// const pageSize = 0;
// const pageToken = '';

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

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

async function searchAllIamPolicies() {
  const request = {
    scope: `projects/${projectId}`,
    query: query,
    pageSize: pageSize,
    pageToken: pageToken,
  };
  const options = {
    autoPaginate: false,
  };

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

SearchAllResources

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const scope = '';
// const query = '';
// const assetTypes = [];
// const pageSize = 0;
// const pageToken = '';
// const orderBy = '';

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

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

async function searchAllResources() {
  const request = {
    scope: `projects/${projectId}`,
    query: query,
    assetTypes: assetTypes,
    pageSize: pageSize,
    pageToken: pageToken,
    orderBy: orderBy,
  };
  const options = {
    autoPaginate: false,
  };

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

PHP

ExportAssets

use Google\Cloud\Asset\V1\Client\AssetServiceClient;
use Google\Cloud\Asset\V1\ExportAssetsRequest;
use Google\Cloud\Asset\V1\GcsDestination;
use Google\Cloud\Asset\V1\OutputConfig;

/**
 * Export assets for given project to specified dump file path.
 *
 * @param string $projectId the project Id for export assets.
 * @param string $dumpFilePath the file path where the assets will be dumped to.
 *        e.g.: gs://[bucket-name]/[asset-file-name].
 */
function export_assets(string $projectId, string $dumpFilePath)
{
    $client = new AssetServiceClient();

    $gcsDestination = new GcsDestination(['uri' => $dumpFilePath]);
    $outputConfig = new OutputConfig(['gcs_destination' => $gcsDestination]);
    $request = (new ExportAssetsRequest())
        ->setParent("projects/$projectId")
        ->setOutputConfig($outputConfig);

    $resp = $client->exportAssets($request);

    $resp->pollUntilComplete();

    if ($resp->operationSucceeded()) {
        print('The result is dumped to $dumpFilePath successfully.' . PHP_EOL);
    } else {
        $error = $resp->getError();
        printf('There was an error: "%s".' . PHP_EOL, $error?->getMessage());
        // handleError($error)
    }
}

BatchGetAssetsHistory

use Google\Cloud\Asset\V1\BatchGetAssetsHistoryRequest;
use Google\Cloud\Asset\V1\Client\AssetServiceClient;
use Google\Cloud\Asset\V1\ContentType;
use Google\Cloud\Asset\V1\TimeWindow;
use Google\Protobuf\Timestamp;

/**
 * @param string   $projectId  Tthe project Id for list assets.
 * @param string[] $assetNames (Optional) Asset types to list for.
 */
function batch_get_assets_history(string $projectId, array $assetNames): void
{
    $client = new AssetServiceClient();
    $formattedParent = $client->projectName($projectId);
    $contentType = ContentType::RESOURCE;
    $readTimeWindow = new TimeWindow(['start_time' => new Timestamp(['seconds' => time()])]);
    $request = (new BatchGetAssetsHistoryRequest())
        ->setParent($formattedParent)
        ->setContentType($contentType)
        ->setReadTimeWindow($readTimeWindow)
        ->setAssetNames($assetNames);

    $resp = $client->batchGetAssetsHistory($request);

    # Do things with response.
    print($resp->serializeToString());
}

ListAssets

use Google\Cloud\Asset\V1\Client\AssetServiceClient;
use Google\Cloud\Asset\V1\ListAssetsRequest;

/**
 * @param string   $projectId  Tthe project Id for list assets.
 * @param string[] $assetTypes (Optional) Asset types to list for.
 * @param int      $pageSize   (Optional) Size of one result page.
 */
function list_assets(
    string $projectId,
    array $assetTypes = [],
    int $pageSize = null
): void {
    // Instantiate a client.
    $client = new AssetServiceClient();

    // Run request
    $request = (new ListAssetsRequest())
        ->setParent("projects/$projectId")
        ->setAssetTypes($assetTypes)
        ->setPageSize($pageSize);
    $response = $client->listAssets($request);

    // Print the asset names in the result
    foreach ($response->getPage() as $asset) {
        print($asset->getName() . PHP_EOL);
    }
}

SearchAllIamPolicies

use Google\Cloud\Asset\V1\Client\AssetServiceClient;
use Google\Cloud\Asset\V1\SearchAllIamPoliciesRequest;

/**
 * @param string $scope      Scope of the search
 * @param string $query      (Optional) Query statement
 * @param int    $pageSize   (Optional) Size of each result page
 * @param string $pageToken  (Optional) Token produced by the preceding call
 */
function search_all_iam_policies(
    string $scope,
    string $query = '',
    int $pageSize = 0,
    string $pageToken = ''
) {
    // Instantiate a client.
    $asset = new AssetServiceClient();

    // Run request
    $request = (new SearchAllIamPoliciesRequest())
        ->setScope($scope)
        ->setQuery($query)
        ->setPageSize($pageSize)
        ->setPageToken($pageToken);
    $response = $asset->searchAllIamPolicies($request);

    // Print the resources that the policies are set on
    foreach ($response->getPage() as $policy) {
        print($policy->getResource() . PHP_EOL);
    }
}

SearchAllResources

use Google\Cloud\Asset\V1\Client\AssetServiceClient;
use Google\Cloud\Asset\V1\SearchAllResourcesRequest;

/**
 * @param string   $scope      Scope of the search
 * @param string   $query      (Optional) Query statement
 * @param string[] $assetTypes (Optional) Asset types to search for
 * @param int      $pageSize   (Optional) Size of each result page
 * @param string   $pageToken  (Optional) Token produced by the preceding call
 * @param string   $orderBy    (Optional) Fields to sort the results
 */
function search_all_resources(
    string $scope,
    string $query = '',
    array $assetTypes = [],
    int $pageSize = 0,
    string $pageToken = '',
    string $orderBy = ''
): void {
    // Instantiate a client.
    $asset = new AssetServiceClient();

    // Run request
    $request = (new SearchAllResourcesRequest())
        ->setScope($scope)
        ->setQuery($query)
        ->setAssetTypes($assetTypes)
        ->setPageSize($pageSize)
        ->setPageToken($pageToken)
        ->setOrderBy($orderBy);
    $response = $asset->searchAllResources($request);

    // Print the resource names in the first page of the result
    foreach ($response->getPage() as $resource) {
        print($resource->getName() . PHP_EOL);
    }
}

Python

ExportAssetsGcs

from google.cloud import asset_v1

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

client = asset_v1.AssetServiceClient()
parent = f"projects/{project_id}"
output_config = asset_v1.OutputConfig()
output_config.gcs_destination.uri = dump_file_path
request_options = {"parent": parent, "output_config": output_config}

if content_type is not None:
    request_options["content_type"] = content_type

response = client.export_assets(request=request_options)
print(response.result())

ExportAssetsBigQuery

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'
# TODO content_type ="Content type to export"

client = asset_v1.AssetServiceClient()
parent = f"projects/{project_id}"
output_config = asset_v1.OutputConfig()
output_config.bigquery_destination.dataset = dataset
output_config.bigquery_destination.table = table
output_config.bigquery_destination.force = True
response = client.export_assets(
    request={
        "parent": parent,
        "content_type": content_type,
        "output_config": output_config,
    }
)
print(response.result())

BatchGetAssetsHistory

from google.cloud import asset_v1

# TODO project_id = 'Your Google Cloud Project ID'
# TODO asset_names = 'Your asset names list, e.g.:
# ["//storage.googleapis.com/[BUCKET_NAME]",]'

client = asset_v1.AssetServiceClient()
parent = f"projects/{project_id}"
content_type = asset_v1.ContentType.RESOURCE
read_time_window = asset_v1.TimeWindow()
response = client.batch_get_assets_history(
    request={
        "parent": parent,
        "asset_names": asset_names,
        "content_type": content_type,
        "read_time_window": read_time_window,
    }
)
print(f"assets: {response.assets}")

ListAssets

from google.cloud import asset_v1

# TODO project_id = 'Your Google Cloud Project ID'
# TODO asset_types = 'Your asset type list, e.g.,
# ["storage.googleapis.com/Bucket","bigquery.googleapis.com/Table"]'
# TODO page_size = 'Num of assets in one page, which must be between 1 and
# 1000 (both inclusively)'
# TODO content_type ="Content type to list"

project_resource = f"projects/{project_id}"
client = asset_v1.AssetServiceClient()

# Call ListAssets v1 to list assets.
response = client.list_assets(
    request={
        "parent": project_resource,
        "read_time": None,
        "asset_types": asset_types,
        "content_type": content_type,
        "page_size": page_size,
    }
)

for asset in response:
    print(asset)

CreateFeed

from google.cloud import asset_v1

# TODO project_id = 'Your Google Cloud Project ID'
# TODO feed_id = 'Feed ID you want to create'
# TODO asset_names = 'List of asset names the feed listen to'
# TODO topic = "Topic name of the feed"
# TODO content_type ="Content type of the feed"

client = asset_v1.AssetServiceClient()
parent = f"projects/{project_id}"
feed = asset_v1.Feed()
feed.asset_names.extend(asset_names)
feed.feed_output_config.pubsub_destination.topic = topic
feed.content_type = content_type
response = client.create_feed(
    request={"parent": parent, "feed_id": feed_id, "feed": feed}
)
print(f"feed: {response}")

SearchAllIamPolicies

from google.cloud import asset_v1

# TODO scope = 'Scope of the search'
# TODO query = 'Query statement'
# TODO page_size = Size of each result page

client = asset_v1.AssetServiceClient()
response = client.search_all_iam_policies(
    request={"scope": scope, "query": query, "page_size": page_size}
)
for policy in response:
    print(policy)
    break

SearchAllResources

from google.cloud import asset_v1

# TODO scope = 'Scope of the search'
# TODO query = 'Query statement'
# TODO asset_types = 'List of asset types to search for'
# TODO page_size = Size of each result page
# TODO order_by = 'Fields to sort the results'

client = asset_v1.AssetServiceClient()
response = client.search_all_resources(
    request={
        "scope": scope,
        "query": query,
        "asset_types": asset_types,
        "page_size": page_size,
        "order_by": order_by,
    }
)
for resource in response:
    print(resource)

Ruby

ExportAssets

require "google/cloud/asset"

asset_service = Google::Cloud::Asset.asset_service
# project_id = 'YOUR_PROJECT_ID'
formatted_parent = asset_service.project_path project: project_id
# Assets dump file path, e.g.: gs://[YOUR_BUCKET]/[YOUR_ASSETS_FILE]
# dump_file_path = 'YOUR_ASSET_DUMP_FILE_PATH'
output_config = {
  gcs_destination: {
    uri: dump_file_path
  }
}

operation = asset_service.export_assets(
  parent: formatted_parent, output_config: output_config
) do |op|
  # Handle the error.
  raise op.results.message if op.error?
end

operation.wait_until_done!
response = operation.response
puts "Exported assets to: #{response.output_config.gcs_destination.uri}"
# Do things with the result

BatchGetAssetsHistory

require "google/cloud/asset"

# project_id = 'YOUR_PROJECT_ID'
# asset names, e.g.: //storage.googleapis.com/[YOUR_BUCKET_NAME]
# asset_names = [ASSET_NAMES, COMMMA_DELIMTTED]
asset_service = Google::Cloud::Asset.asset_service

formatted_parent = asset_service.project_path project: project_id

content_type = :RESOURCE
read_time_window = {
  start_time: {
    seconds: Time.now.getutc.to_i
  }
}

response = asset_service.batch_get_assets_history(
  parent:           formatted_parent,
  content_type:     content_type,
  read_time_window: read_time_window,
  asset_names:      asset_names
)
# Do things with the response
puts response.assets

ListAssets

require "google/cloud/asset"

asset_service = Google::Cloud::Asset.asset_service
# project_id = 'YOUR_PROJECT_ID'
formatted_parent = asset_service.project_path project: project_id

content_type = :RESOURCE
response = asset_service.list_assets(
  parent:           formatted_parent,
  content_type:     content_type
)

# Do things with the result
response.page.each do |resource|
  puts resource
end

CreateFeed

require "google/cloud/asset"

# project_id = 'YOUR_PROJECT_ID'
# feed_id = 'NAME_OF_FEED'
# pubsub_topic = 'YOUR_PUBSUB_TOPIC'
# asset names, e.g.: //storage.googleapis.com/[YOUR_BUCKET_NAME]
# asset_names = [ASSET_NAMES, COMMMA_DELIMTTED]
asset_service = Google::Cloud::Asset.asset_service

formatted_parent = asset_service.project_path project: project_id

feed = {
  asset_names:        asset_names,
  feed_output_config: {
    pubsub_destination: {
      topic: pubsub_topic
    }
  }
}
response = asset_service.create_feed(
  parent:  formatted_parent,
  feed_id: feed_id,
  feed:    feed
)
puts "Created feed: #{response.name}"

SearchAllIamPolicies

require "google/cloud/asset"

# scope = 'SCOPE_OF_THE_QUERY'
# query = 'QUERY_STATEMENT'
# page_size = 'SIZE_OF_EACH_RESULT_PAGE'
# page_token = 'TOKEN_PRODUCED_BY_THE_PRECEDING_CALL'
asset_service = Google::Cloud::Asset.asset_service

response = asset_service.search_all_iam_policies(
  scope:      scope,
  query:      query,
  page_size:  page_size,
  page_token: page_token
)
# Do things with the response
response.page.each do |policy|
  puts policy
end

SearchAllResources

require "google/cloud/asset"

# scope = 'SCOPE_OF_THE_QUERY'
# query = 'QUERY_STATEMENT'
# asset_types = 'AN_ARRAY_OF_ASSET_TYPES_TO_SEARCH_FOR'
# page_size = 'SIZE_OF_EACH_RESULT_PAGE'
# page_token = 'TOKEN_PRODUCED_BY_THE_PRECEDING_CALL'
# order_by = 'FIELDS_TO_SORT_THE RESULTS'
asset_service = Google::Cloud::Asset.asset_service

response = asset_service.search_all_resources(
  scope:       scope,
  query:       query,
  asset_types: asset_types,
  page_size:   page_size,
  page_token:  page_token,
  order_by:    order_by
)
# Do things with the response
response.page.each do |resource|
  puts resource
end

추가 리소스

C#

다음 목록에는 C#용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Go

다음 목록에는 Go용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Java

다음 목록에는 자바용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Node.js

다음 목록에는 Node.js용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

PHP

다음 목록에는 PHP용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Python

다음 목록에는 Python용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Ruby

다음 목록에는 Ruby용 클라이언트 라이브러리와 관련된 추가 리소스의 링크가 포함되어 있습니다.