Batch get an asset history

Do a batch get of an asset history.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

C#

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


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;
    }
}

Go

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.


// 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)
}

Java

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

// 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);
    }
  }
}

Node.js

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

/**
 * 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}));

PHP

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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());
}

Python

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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}")

Ruby

To learn how to install and use the client library for Cloud Asset Inventory, see Cloud Asset Inventory client libraries.

To authenticate to Cloud Asset Inventory, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.