Bibliotecas cliente de Cloud Asset Inventory

En esta página se muestra cómo comenzar a usar las bibliotecas cliente de Cloud para la API de Cloud Asset Inventory. Obtén más información sobre las bibliotecas cliente para las API de Cloud, incluidas aquellas de las API de Google anteriores, en Explicación de bibliotecas cliente.

Instala la biblioteca cliente

C#

Para obtener más información, consulta Configura un entorno de desarrollo de C#.

Administrador de paquetes

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

Comienza a usarlo

Para obtener más información, consulta Configura un entorno de desarrollo de Go.

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

Java

Para obtener más información, consulta Configura un entorno de desarrollo de Java.

Si usas Maven, agrega esto a tu archivo pom.xml:

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

Si usas Gradle, agrega lo siguiente a tus dependencias:

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

Node.js

Para obtener más información, consulta Configura un entorno de desarrollo de Node.js.

npm install --save @google-cloud/asset

PHP

Para obtener más información, consulta PHP en Google Cloud.

composer require google/cloud-asset

Python

Para obtener más información, consulta Configura un entorno de desarrollo de Python.

pip install --upgrade google-cloud-asset

Ruby

Para obtener más información, consulta Cómo configurar un entorno de desarrollo en Ruby.

gem install google-cloud-asset

Cómo configurar la autenticación

Si quieres ejecutar la biblioteca cliente, primero debes configurar la autenticación. Para ello, crea una cuenta de servicio y configura una variable de entorno. Sigue los pasos que se indican a continuación a fin de configurar la autenticación. Para obtener más información sobre otras maneras de autentificar, consulta la documentación de autenticación de GCP.

Cloud Console

Crea una cuenta de servicio:

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

    Ir a Crear cuenta de servicio
  2. Selecciona un proyecto
  3. Ingresa un nombre en el campo Nombre de cuenta de servicio. Cloud Console completa el campo ID de cuenta de servicio con este nombre.

    En el campo Descripción de la cuenta de servicio, ingresa una descripción. Por ejemplo, Service account for quickstart.

  4. Haga clic en Crear.
  5. Haz clic en el campo Seleccionar una función.

    En Acceso rápido, haz clic en Básica y, luego, en Propietario.

  6. Haga clic en Continuar.
  7. Haz clic en Listo para terminar de crear la cuenta de servicio.

    No cierres la ventana del navegador. La usarás en la próxima tarea.

Para crear una clave de cuenta de servicio, haz lo siguiente:

  1. En Cloud Console, haz clic en la dirección de correo electrónico de la cuenta de servicio que creaste.
  2. Haz clic en Claves.
  3. Haz clic en Agregar clave y, luego, en Crear clave nueva.
  4. Haga clic en Crear. Se descargará un archivo de claves JSON a tu computadora.
  5. Haga clic en Cerrar.

Línea de comandos

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

  1. Crea la cuenta de servicio. Reemplaza NAME por un nombre para la cuenta de servicio.

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

    gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:NAME@PROJECT_ID.iam.gserviceaccount.com" --role="roles/owner"
  3. Genera el archivo de claves. Reemplaza FILE_NAME por un nombre para el archivo de claves.

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

Configura la variable de entorno GOOGLE_APPLICATION_CREDENTIALS para proporcionar credenciales de autenticación al código de la aplicación. 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="KEY_PATH"

Reemplaza KEY_PATH por la ruta de acceso del archivo JSON que contiene la clave de tu cuenta de servicio.

Por ejemplo:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Windows

Para PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="KEY_PATH"

Reemplaza KEY_PATH por la ruta de acceso del archivo JSON que contiene la clave de tu cuenta de servicio.

Por ejemplo:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\service-account-file.json"

Para el símbolo del sistema:

set GOOGLE_APPLICATION_CREDENTIALS=KEY_PATH

Reemplaza KEY_PATH por la ruta de acceso del archivo JSON que contiene la clave de tu cuenta de servicio.

Usa la biblioteca cliente

El siguiente ejemplo muestra cómo usar la biblioteca cliente.

C#

ExportAssets


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

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, 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.FromDateTime(DateTime.UtcNow)
            }
        };
        request.AssetNames.AddRange(assetNames);

        // Call the API.
        BatchGetAssetsHistoryResponse response = client.BatchGetAssetsHistory(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();
    }
}

Comienza a usarlo

ExportAssetsGcs


// 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)
	}
	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"
	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.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",
				},
			},
		},
	}
	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"
	"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)
	}
	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/apiv1p5beta1"
	assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1p5beta1"
)

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"
	"google.golang.org/api/iterator"
	assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1"
)

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"
	"google.golang.org/api/iterator"
	assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1"
)

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

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.ExportAssetsRequest;
import com.google.cloud.asset.v1.ExportAssetsResponse;
import com.google.cloud.asset.v1.OutputConfig;
import com.google.cloud.asset.v1.ProjectName;

public class ExportAssetsBigqueryExample {

  // 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 exportBigQuery(String bigqueryDataset, String bigqueryTable) throws Exception {
    try (AssetServiceClient client = AssetServiceClient.create()) {
      ProjectName parent = ProjectName.of(projectId);
      OutputConfig outputConfig =
          OutputConfig.newBuilder()
              .setBigqueryDestination(
                  BigQueryDestination.newBuilder()
                      .setDataset(bigqueryDataset)
                      .setTable(bigqueryTable)
                      .setForce(true)
                      .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);
    }
  }
}

ListAssets

// Imports the Google Cloud client library

import com.google.cloud.asset.v1.ProjectName;
import com.google.cloud.asset.v1p5beta1.AssetServiceClient;
import com.google.cloud.asset.v1p5beta1.AssetServiceClient.ListAssetsPagedResponse;
import com.google.cloud.asset.v1p5beta1.ContentType;
import com.google.cloud.asset.v1p5beta1.ListAssetsRequest;
import java.util.Arrays;

public class ListAssetsExample {

  public static void listAssets() throws Exception {
    // 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.v1p5beta1#contenttype
    ContentType contentType = ContentType.CONTENT_TYPE_UNSPECIFIED;
    listAssets(projectId, assetTypes, contentType);
  }

  public static void listAssets(String projectId, String[] assetTypes, ContentType contentType)
      throws Exception {
    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.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.util.Arrays;

public class CreateFeedExample {
  // Create a feed
  public static void createFeed(
      String[] assetNames, String feedId, String topic, String projectId) throws Exception {
    // String[] assetNames = {"MY_ASSET_NAME"}
    // 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))
        .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 (Exception 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

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

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: '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}));

ListAssets

const util = require('util');
const {v1p5beta1} = require('@google-cloud/asset');
const client = new v1p5beta1.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: 'RESOURCE',
    // (Optional) Add readTime parameter to list assets at the given time instead of current time:
    //   readTime: { seconds: 1593988758 },
  };

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

CreateFeed

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(','),
      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\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(string $projectId, string $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(string $projectId, string $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());
}

SearchAllIamPolicies

use Google\Cloud\Asset\V1\AssetServiceClient;

/**
 * @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
    $response = $asset->searchAllIamPolicies($scope, [
        'query' => $query,
        'pageSize' => $pageSize,
        'pageToken' => $pageToken
    ]);

    // 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\AssetServiceClient;

/**
 * @param string       $scope      Scope of the search
 * @param string       $query      (Optional) Query statement
 * @param string|array $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 = ''
) {
    // Instantiate a client.
    $asset = new AssetServiceClient();

    // Run request
    $response = $asset->searchAllResources($scope, [
        'query' => $query,
        'assetTypes' => $assetTypes,
        'pageSize' => $pageSize,
        'pageToken' => $pageToken,
        'orderBy' => $orderBy
    ]);

    // 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 = "projects/{}".format(project_id)
output_config = asset_v1.OutputConfig()
output_config.gcs_destination.uri = dump_file_path
response = client.export_assets(
    request={"parent": parent, "output_config": output_config}
)
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'

client = asset_v1.AssetServiceClient()
parent = "projects/{}".format(project_id)
content_type = asset_v1.ContentType.RESOURCE
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 = "projects/{}".format(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("assets: {}".format(response.assets))

ListAssets

from google.cloud import asset_v1p5beta1

# 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)'

project_resource = "projects/{}".format(project_id)
content_type = asset_v1p5beta1.ContentType.RESOURCE
client = asset_v1p5beta1.AssetServiceClient()

# Call ListAssets v1p5beta1 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"

client = asset_v1.AssetServiceClient()
parent = "projects/{}".format(project_id)
feed = asset_v1.Feed()
feed.asset_names.extend(asset_names)
feed.feed_output_config.pubsub_destination.topic = topic
response = client.create_feed(
    request={"parent": parent, "feed_id": feed_id, "feed": feed}
)
print("feed: {}".format(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)
    break

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

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

Recursos adicionales