Recuperare batch di una cronologia degli asset

Esegui un recupero collettivo della cronologia di una risorsa.

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:

Esempio di codice

C#

Per eseguire l'autenticazione in Cloud Asset Inventory, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in Cloud Asset Inventory, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Per eseguire l'autenticazione in Cloud Asset Inventory, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Cloud Asset Inventory, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

/**
 * 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

Per eseguire l'autenticazione in Cloud Asset Inventory, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Cloud Asset Inventory, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Per eseguire l'autenticazione in Cloud Asset Inventory, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.