Cloud Asset Inventory クライアント ライブラリ

このページでは、Cloud Asset Inventory API の Cloud クライアント ライブラリの使用を開始する方法について説明します。クライアント ライブラリを使用すると、サポートされている言語から Google Cloud APIs に簡単にアクセスできるようになります。サーバーにリクエストを送信して Google Cloud APIs を直接利用することもできますが、クライアント ライブラリを使用すると、記述するコードの量を大幅に削減できます。

Cloud クライアント ライブラリと以前の Google API クライアント ライブラリの詳細については、クライアント ライブラリの説明をご覧ください。

クライアント ライブラリをインストールする

C#

パッケージ マネージャー

Install-Package Google.Cloud.Asset.V1

.NET CLI

dotnet add package Google.Cloud.Asset.V1

Paket 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 APIs の呼び出しを認証するために、クライアント ライブラリではアプリケーションのデフォルト認証情報(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

次のリストは、Java のクライアント ライブラリに関連するその他のリソースへのリンクを示します。

Node.js

次のリストは、Node.js のクライアント ライブラリに関連するその他のリソースへのリンクを示します。

PHP

次のリストは、PHP のクライアント ライブラリに関連するその他のリソースへのリンクを示します。

Python

次のリストは、Python のクライアント ライブラリに関連するその他のリソースへのリンクを示します。

Ruby

次のリストは、Ruby のクライアント ライブラリに関連するその他のリソースへのリンクを示します。