Export assets to Cloud Storage

Export an asset inventory to Cloud Storage.

Explore further

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

Code sample

C#

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;

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

Go

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

Java

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

Node.js

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

PHP

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

Python

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

Ruby

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"

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

What's next

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