列出资产。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
C#
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Asset.V1;
public class ListAssetsSample
{
public PagedEnumerable<ListAssetsResponse, Asset> ListAssets(string projectId)
{
// Create the client.
AssetServiceClient client = AssetServiceClient.Create();
// Build the request.
ListAssetsRequest request = new ListAssetsRequest
{
ParentAsResourceName = ProjectName.FromProject(projectId),
ContentType = ContentType.Resource,
};
// Call the API.
PagedEnumerable<ListAssetsResponse, Asset> response = client.ListAssets(request);
// Return the result.
return response;
}
}
Go
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
// Sample list-assets list assets.
package main
import (
"context"
"fmt"
"log"
"os"
"google.golang.org/api/iterator"
asset "cloud.google.com/go/asset/apiv1"
"cloud.google.com/go/asset/apiv1/assetpb"
)
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)
}
}
Java
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
// Imports the Google Cloud client library
public class ListAssetsExample {
public static void listAssets() throws IOException, IllegalArgumentException {
// 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.v1#contenttype
ContentType contentType = ContentType.CONTENT_TYPE_UNSPECIFIED;
listAssets(projectId, assetTypes, contentType);
}
public static void listAssets(String projectId, String[] assetTypes, ContentType contentType)
throws IOException, IllegalArgumentException {
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);
}
}
}
}
Node.js
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const assetTypes = 'storage.googleapis.com/Bucket,bigquery.googleapis.com/Table';
// const contentType = 'RESOURCE';
const util = require('util');
const {v1} = require('@google-cloud/asset');
const client = new v1.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: contentType,
// (Optional) Add readTime parameter to list assets at the given time instead of current time:
// readTime: { seconds: 1593988758 },
};
// Call cloud.assets.v1.ListAssets API.
const result = await client.listAssets(request);
// Handle the response.
console.log(util.inspect(result, {depth: null}));
}
listAssets();
PHP
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
use Google\Cloud\Asset\V1\Client\AssetServiceClient;
use Google\Cloud\Asset\V1\ListAssetsRequest;
/**
* @param string $projectId Tthe project Id for list assets.
* @param string[] $assetTypes (Optional) Asset types to list for.
* @param int $pageSize (Optional) Size of one result page.
*/
function list_assets(
string $projectId,
array $assetTypes = [],
int $pageSize = null
): void {
// Instantiate a client.
$client = new AssetServiceClient();
// Run request
$request = (new ListAssetsRequest())
->setParent("projects/$projectId")
->setAssetTypes($assetTypes)
->setPageSize($pageSize);
$response = $client->listAssets($request);
// Print the asset names in the result
foreach ($response->getPage() as $asset) {
print($asset->getName() . PHP_EOL);
}
}
Python
如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
from google.cloud import asset_v1
# 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)'
# TODO content_type ="Content type to list"
project_resource = f"projects/{project_id}"
client = asset_v1.AssetServiceClient()
# Call ListAssets v1 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)
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
content_type = :RESOURCE
response = asset_service.list_assets(
parent: formatted_parent,
content_type: content_type
)
# Do things with the result
response.page.each do |resource|
puts resource
end
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。