Cloud Asset Inventory Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Cloud Asset API. Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

Installing the client library

C#

For more information, see Setting Up a C# Development Environment.

Package Manager

Install-Package Google.Cloud.Asset.V1
.NET CLI
dotnet add package Google.Cloud.Asset.V1
Paket CLI
packet add Google.Cloud.Asset.V1

Go

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

Java

For more information, see Setting Up a Java Development Environment. If you are using Maven, add this to your pom.xml file:

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

If you are using Gradle, add this to your dependencies:

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

Node.js

For more information, see Setting Up a Node.js Development Environment.
npm install --save @google-cloud/asset

PHP

composer require google/cloud-asset

Python

For more information, see Setting Up a Python Development Environment.
pip install --upgrade google-cloud-asset

Ruby

For more information, see Setting Up a Ruby Development Environment.
gem install google-cloud-asset

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For more information, see the GCP authentication documentation .

GCP Console

  1. En GCP Console, ve a la página Crear clave de la cuenta de servicio.

    Ir a la página Crear clave de la cuenta de servicio
  2. Desde la lista desplegable de la Cuenta de servicio, selecciona Nueva cuenta de servicio.
  3. En el campo Nombre de cuenta de servicio, ingresa un nombre.
  4. En la lista desplegable Función, selecciona Proyecto > Propietario.

    Nota: El campo Función autoriza tu cuenta de servicio para acceder a los recursos. Puedes ver y cambiar este campo luego con GCP Console. Si desarrollas una aplicación de producción, especifica permisos más detallados que Proyecto > Propietario. Para obtener más información, consulta Cómo otorgar funciones a las cuentas de servicio.
  5. Haz clic en Crear. Se descargará un archivo JSON a tu computadora que contiene tus descargas de claves.

Línea de comandos

Puedes ejecutar los siguientes comandos con el SDK de Cloud en tu máquina local o dentro de Cloud Shell.

  1. Crea la cuenta de servicio. Reemplaza [NAME] con el nombre que le quieres poner a la cuenta de servicio.

    gcloud iam service-accounts create [NAME]
  2. Otorga permisos a la cuenta de servicio. Reemplaza [PROJECT_ID] con el ID del proyecto.

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    Nota: El campo Función autoriza a tu cuenta de servicio para acceder a los recursos. Puedes ver y cambiar este campo luego con GCP Console. Si desarrollas una aplicación de producción, especifica permisos más detallados que Proyecto > Propietario. Para obtener más información, consulta Cómo otorgar funciones a las cuentas de servicio.
  3. Genera el archivo de claves. Reemplaza [FILE_NAME] con un nombre para el archivo de claves.

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

Proporciónale las credenciales de autenticación a tu código de la aplicación mediante la configuración de la variable de entorno GOOGLE_APPLICATION_CREDENTIALS. Reemplaza [PATH] con la ruta de acceso al archivo JSON que contiene la clave de tu cuenta de servicio y [FILE_NAME] con el nombre del archivo. Esta variable solo se aplica a la sesión actual de shell. Por lo tanto, si abres una sesión nueva, deberás volver a configurar la variable.

Linux o macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Por ejemplo:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

Con PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Por ejemplo:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

Con el símbolo del sistema:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C#

ExportAssets


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


public class ExportAssets
{
    public static void Main(string[] args)
    {
        string bucketName = "YOUR-BUCKET-NAME";
        string projectId = "YOUR-GOOGLE-PROJECT-ID";
        string assetDumpFile = String.Format("gs://{0}/my-assets.txt", bucketName);
        AssetServiceClient client = AssetServiceClient.Create();
        ExportAssetsRequest request = new ExportAssetsRequest
        {
            ParentAsProjectName = new ProjectName(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();
        // Extract the result
        ExportAssetsResponse response = operation.Result;
        Console.WriteLine(response);
    }
}

BatchGetAssetsHistory


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


public class BatchGetAssetsHistory
{
    public static void Main(string[] args)
    {
        // Asset names, e.g.: //storage.googleapis.com/[YOUR_BUCKET_NAME]
        string[] assetNames = { "ASSET-NAME" };
        string projectId = "YOUR-GOOGLE-PROJECT-ID";

        BatchGetAssetsHistoryRequest request = new BatchGetAssetsHistoryRequest
        {
            ParentAsProjectName = new ProjectName(projectId),
            ContentType = ContentType.Resource,
            ReadTimeWindow = new TimeWindow
            {
                StartTime = Timestamp.FromDateTime(System.DateTime.UtcNow)
            }
        };
        request.AssetNames.AddRange(assetNames);
        AssetServiceClient client = AssetServiceClient.Create();
        BatchGetAssetsHistoryResponse response = client.BatchGetAssetsHistory(request);
        Console.WriteLine(response);
    }
}

Go

ExportAssets


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

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

	asset "cloud.google.com/go/asset/apiv1"
	assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1"
)

func main() {
	ctx := context.Background()
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatal(err)
	}
	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)
}

BatchGetAssetsHistory


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

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

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

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

	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

ExportAssets

// Imports the Google Cloud client library

import com.google.cloud.ServiceOptions;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.ExportAssetsRequest;
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;

public class ExportAssetsExample {

  // 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 {
    // Gcs path, e.g.: "gs://<my_asset_bucket>/<my_asset_dump_file>"
    String exportPath = args[0];
    try (AssetServiceClient client = AssetServiceClient.create()) {
      ProjectName parent = ProjectName.of(projectId);
      OutputConfig outputConfig =
          OutputConfig.newBuilder()
              .setGcsDestination(GcsDestination.newBuilder().setUri(exportPath).build())
              .build();
      ExportAssetsRequest request =
          ExportAssetsRequest.newBuilder()
              .setParent(parent.toString())
              .setOutputConfig(outputConfig)
              .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);
    }
  }
}

Node.js

ExportAssets

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

async function exportAssets() {
  const projectId = await client.getProjectId();
  const projectResource = client.projectPath(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,
    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();

BatchGetAssetsHistory

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

const client = new AssetServiceClient();

async function batchGetAssetsHistory() {
  const projectId = await client.getProjectId();
  const projectResource = client.projectPath(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: 'RESOURCE',
    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

ExportAssets

use Google\Cloud\Asset\V1\AssetServiceClient;
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($projectId, $dumpFilePath)
{
    $client = new AssetServiceClient();

    $gcsDestination = new GcsDestination(['uri' => $dumpFilePath]);
    $outputConfig = new OutputConfig(['gcs_destination' => $gcsDestination]);

    $resp = $client->exportAssets("projects/$projectId", $outputConfig);

    $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\AssetServiceClient;
use Google\Cloud\Asset\V1\ContentType;
use Google\Cloud\Asset\V1\TimeWindow;
use Google\Protobuf\Timestamp;

function batch_get_assets_history($projectId, $assetNames)
{
    $client = new AssetServiceClient();
    $formattedParent = $client->projectName($projectId);
    $contentType = ContentType::RESOURCE;
    $readTimeWindow = new TimeWindow(['start_time' => new Timestamp(['seconds' => time()])]);

    $resp = $client->batchGetAssetsHistory($formattedParent, $contentType, $readTimeWindow, ['assetNames' => $assetNames]);

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

Python

ExportAssets

from google.cloud import asset_v1
from google.cloud.asset_v1.proto import asset_service_pb2

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

client = asset_v1.AssetServiceClient()
parent = client.project_path(project_id)
output_config = asset_service_pb2.OutputConfig()
output_config.gcs_destination.uri = dump_file_path
response = client.export_assets(parent, output_config)
print(response.result())

BatchGetAssetsHistory

from google.cloud import asset_v1
from google.cloud.asset_v1.proto import assets_pb2
from google.cloud.asset_v1 import enums

# 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 = client.project_path(project_id)
content_type = enums.ContentType.RESOURCE
read_time_window = assets_pb2.TimeWindow()
response = client.batch_get_assets_history(
    parent, content_type, read_time_window, asset_names)
print('assets: {}'.format(response.assets))

Ruby

ExportAssets

require "google/cloud/asset"

asset_service_client = Google::Cloud::Asset.new version: :v1
# project_id = 'YOUR_PROJECT_ID'
# Assets dump file path, e.g.: gs://[YOUR_BUCKET]/[YOUR_ASSETS_FILE]
# dump_file_path = 'YOUR_ASSET_DUMP_FILE_PATH'
formatted_parent =
  Google::Cloud::Asset::V1::AssetServiceClient.project_path(
    project_id
  )
output_config = Google::Cloud::Asset::V1::OutputConfig.new(
  gcs_destination: Google::Cloud::Asset::V1::GcsDestination.new(
    uri: dump_file_path
  )
)

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

operation.wait_until_done!
# 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]
formatted_parent =
  Google::Cloud::Asset::V1::AssetServiceClient.project_path project_id

content_type = :RESOURCE
read_time_window = Google::Cloud::Asset::V1::TimeWindow.new(
  start_time: Google::Protobuf::Timestamp.new(seconds: Time.now.getutc.to_i)
)

asset_service_client = Google::Cloud::Asset.new version: :v1
response = asset_service_client.batch_get_assets_history(
  formatted_parent, content_type, read_time_window, asset_names: asset_names
)
# Do things with the response
puts response

Additional resources

¿Te ha resultado útil esta página? Enviar comentarios:

Enviar comentarios sobre...