将资产清单导出到 Cloud Storage。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
C#
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
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
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
// 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
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
// 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
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
/**
* 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
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
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
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
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
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
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
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。