列出资产

您可以列出 Cloud de Confiance by S3NS 项目、文件夹或组织中的资产。

准备工作

  1. 在您运行 Cloud Asset Inventory 命令的项目中启用 Cloud Asset Inventory API。

    启用 Cloud Asset Inventory API

  2. 确保您的账号拥有调用 Cloud Asset Inventory API 的正确角色。如需了解每种通话类型的各项权限,请参阅权限。

限制

  • 列出 BigQuery 表数据时,并非所有字段都受支持。

  • BigQuery 元数据中经常更改的资产字段(例如 numBytes、numLongTermBytes、numPhysicalBytes 和 numRows)会被分配 null 值。

列出您的资产

控制台

Cloud de Confiance 控制台使用 SearchAllResources API 请求数据,这意味着您只能查看具有 RESOURCE 内容类型的媒体资源。如需查看其他内容类型,或按更精确的条件进行过滤,请改用 gcloud CLI、REST 或客户端库。

如需列出项目、文件夹或组织的资源元数据,请完成以下步骤:

  1. 在 Cloud de Confiance 控制台中,前往资产库存页面。

    前往“Asset Inventory”

  2. 切换到您要列出资源的相应项目、文件夹或组织。
  3. 点击资源标签页。
  4. 在过滤结果面板中,选择要按资源类型、项目或位置过滤结果。
  5. 如需查看资源的元数据,请在结果面板中点击资源的显示名称。

gcloud

gcloud asset list \
    --SCOPE \
    --asset-types=ASSET_TYPE_1,ASSET_TYPE_2,... \
    --content-type=CONTENT_TYPE \
    --snapshot-time="SNAPSHOT_TIME"

请提供以下值:

  • SCOPE:请使用以下某个值:

    • project=PROJECT_ID,其中 PROJECT_ID 是包含您要检索的资产的项目的 ID。
    • folder=FOLDER_ID,其中 FOLDER_ID 是包含要检索的资产的文件夹的 ID。

      如何查找 Cloud de Confiance by S3NS 文件夹的 ID

      Cloud de Confiance 控制台

      如需查找 Cloud de Confiance by S3NS 文件夹的 ID,请完成以下步骤:

      1. 前往 Cloud de Confiance 控制台。

        前往 Cloud de Confiance 控制台

      2. 点击菜单栏中的切换器列表框。
      3. 从列表框中选择您的组织。
      4. 搜索文件夹名称。文件夹 ID 会显示在文件夹名称旁边。

      gcloud CLI

      您可以使用以下命令检索组织级层文件夹的 ID: Cloud de Confiance by S3NS

      gcloud resource-manager folders list \
          --organization=$(gcloud organizations describe ORGANIZATION_NAME \
            --format="value(name.segment(1))") \
          --filter='"DISPLAY_NAME":"TOP_LEVEL_FOLDER_NAME"' \
          --format="value(ID)"

      其中,TOP_LEVEL_FOLDER_NAME 是文件夹名称的部分或完整字符串匹配项。移除 --format 标志即可查看有关已找到文件夹的更多信息。

      上一个命令不会返回文件夹中子文件夹的 ID。为此,请使用顶级文件夹的 ID 运行以下命令:

      gcloud resource-manager folders list --folder=FOLDER_ID
    • organization=ORGANIZATION_ID,其中 ORGANIZATION_ID 是包含您要检索的资产的组织的 ID。

      如何查找 Cloud de Confiance by S3NS 组织的 ID

      Cloud de Confiance 控制台

      如需查找 Cloud de Confiance by S3NS 组织的 ID,请完成以下步骤:

      1. 前往 Cloud de Confiance 控制台。

        前往 Cloud de Confiance 控制台

      2. 点击菜单栏中的切换器列表框。
      3. 从列表框中选择您的组织。
      4. 点击全部标签页。组织 ID 显示在组织名称旁边。

      gcloud CLI

      您可以使用以下命令检索 Cloud de Confiance by S3NS 组织的 ID:

      gcloud organizations describe ORGANIZATION_NAME --format="value(name.segment(1))"
  • ASSET_TYPE_#:可选。以英文逗号分隔的 可搜索资产类型列表。 支持 RE2 兼容的正则表达式。如果正则表达式与任何支持的资源类型均不匹配,则会返回 INVALID_ARGUMENT 错误。如果未指定 --asset-types,则返回所有资源类型。
  • CONTENT_TYPE:可选。要检索的元数据的 内容类型。如果未指定 --content-type,则仅返回基本信息,例如资产名称、资产上次更新时间以及资产所属的项目、文件夹和组织。
  • SNAPSHOT_TIME:可选。您希望截取资源快照的时间,采用 gcloud topic datetime 格式。该值必须是过去不超过 35 天的时间。如果未指定 --snapshot-time,则在当前时间截取快照。

如需了解所有选项,请参阅 gcloud CLI 参考文档。

示例

以下命令会获取 my-project 项目中截至 2024 年 1 月 30 日 (2024-01-30) 的 Compute Engine 实例的 resource 元数据快照。

在运行此命令之前,请务必将快照时间更改为过去 35 天内的某个时间,并更改项目名称。

gcloud asset list \
    --project=my-project \
    --asset-types=compute.googleapis.com/Instance \
    --content-type=resource \
    --snapshot-time="2024-01-30"

示例响应

---
ancestors:
- projects/000000000000
- folders/000000000000
- organizations/000000000000
assetType: compute.googleapis.com/Instance
name: //compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/instance-name
resource:
  data:
    ASSET_METADATA
updateTime: '2024-01-30T00:00:00.000000Z'

REST

HTTP 方法和网址:

POST https://cloudasset.googleapis.com/v1/SCOPE_PATH/assets

请求 JSON 正文:

{
  "assetTypes": [
    "ASSET_TYPE_1",
    "ASSET_TYPE_2",
    "..."
  ],
  "contentType": "CONTENT_TYPE",
  "readTime": "SNAPSHOT_TIME",
  "pageSize": "PAGE_SIZE",
  "pageToken": "PAGE_TOKEN"
}

请提供以下值:

  • SCOPE_PATH:请使用以下某个值:

    允许使用的值包括:

    • projects/PROJECT_ID,其中 PROJECT_ID 是包含您要检索的资产的项目的 ID。
    • projects/PROJECT_NUMBER,其中 PROJECT_NUMBER 是包含您要检索的资产的项目的编号。

      如何查找 Cloud de Confiance by S3NS 项目编号

      Cloud de Confiance 控制台

      如需查找 Cloud de Confiance by S3NS 项目编号,请完成以下步骤:

      1. 前往 Cloud de Confiance 控制台中的欢迎页面。

        前往“欢迎”页面

      2. 点击菜单栏中的切换器列表框。
      3. 从列表框中选择您的组织,然后搜索您的项目名称。 项目名称、项目编号和项目 ID 会显示在欢迎标头附近。

        最多可显示 4,000 个资源。如果您没有看到要查找的项目,请前往管理资源页面,然后使用该项目的名称过滤列表。

      gcloud CLI

      您可以使用以下命令检索 Cloud de Confiance by S3NS 项目编号:

      gcloud projects describe PROJECT_ID --format="value(projectNumber)"
    • folders/FOLDER_ID,其中 FOLDER_ID 是包含要检索的资产的文件夹的 ID。

      如何查找 Cloud de Confiance by S3NS 文件夹的 ID

      Cloud de Confiance 控制台

      如需查找 Cloud de Confiance by S3NS 文件夹的 ID,请完成以下步骤:

      1. 前往 Cloud de Confiance 控制台。

        前往 Cloud de Confiance 控制台

      2. 点击菜单栏中的切换器列表框。
      3. 从列表框中选择您的组织。
      4. 搜索文件夹名称。文件夹 ID 会显示在文件夹名称旁边。

      gcloud CLI

      您可以使用以下命令检索组织级层文件夹的 ID: Cloud de Confiance by S3NS

      gcloud resource-manager folders list \
          --organization=$(gcloud organizations describe ORGANIZATION_NAME \
            --format="value(name.segment(1))") \
          --filter='"DISPLAY_NAME":"TOP_LEVEL_FOLDER_NAME"' \
          --format="value(ID)"

      其中,TOP_LEVEL_FOLDER_NAME 是文件夹名称的部分或完整字符串匹配项。移除 --format 标志即可查看有关已找到文件夹的更多信息。

      上一个命令不会返回文件夹中子文件夹的 ID。为此,请使用顶级文件夹的 ID 运行以下命令:

      gcloud resource-manager folders list --folder=FOLDER_ID
    • organizations/ORGANIZATION_ID,其中 ORGANIZATION_ID 是包含您要检索的资产的组织的 ID。

      如何查找 Cloud de Confiance by S3NS 组织的 ID

      Cloud de Confiance 控制台

      如需查找 Cloud de Confiance by S3NS 组织的 ID,请完成以下步骤:

      1. 前往 Cloud de Confiance 控制台。

        前往 Cloud de Confiance 控制台

      2. 点击菜单栏中的切换器列表框。
      3. 从列表框中选择您的组织。
      4. 点击全部标签页。组织 ID 显示在组织名称旁边。

      gcloud CLI

      您可以使用以下命令检索 Cloud de Confiance by S3NS 组织的 ID:

      gcloud organizations describe ORGANIZATION_NAME --format="value(name.segment(1))"
  • ASSET_TYPE_#:可选。 可搜索的资产类型数组。 支持 RE2 兼容的正则表达式。如果正则表达式与任何支持的资源类型均不匹配,则会返回 INVALID_ARGUMENT 错误。如果未指定 assetTypes,则返回所有资源类型。
  • CONTENT_TYPE:可选。要检索的元数据的 内容类型。如果未指定 contentType,则仅返回基本信息,例如资产名称、资产上次更新时间以及资产所属的项目、文件夹和组织。
  • SNAPSHOT_TIME:可选。您希望截取资源快照的时间,采用 RFC 3339 格式。该值必须是过去不超过 35 天的时间。如果未指定 readTime,则在当前时间截取快照。
  • PAGE_SIZE:可选。每页返回的结果数。最大值是 500。如果该值设为 0 或负值,系统会选择适当的默认值。系统会返回 nextPageToken 以检索后续结果。

  • PAGE_TOKEN:可选。较长的请求响应会分布在多个页面上。如果未指定 pageToken,则返回第一页。 后续页面可以通过使用上一个响应的 nextPageToken 作为 pageToken 值来调用。

如需了解所有选项,请参阅 REST 参考文档。

命令示例

以下命令会获取 my-project 项目中截至 2024 年 1 月 30 日 (2024-01-30T00:00:00Z) 的 Compute Engine 实例的 resource 元数据快照。

在运行这些命令之前,请务必将快照时间更改为过去 35 天内的时间,并更改项目名称。

curl(Linux、macOS 或 Cloud Shell)

curl -X POST \
     -H "X-HTTP-Method-Override: GET" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
            "assetTypes": ["compute.googleapis.com/Instance"],
            "contentType": "RESOURCE",
            "readTime": "2024-01-30T00:00:00Z"
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project/assets

PowerShell (Windows)

$cred = gcloud auth print-access-token

$headers = @{ 
  "X-HTTP-Method-Override" = "GET";
  "Authorization" = "Bearer $cred"
}


$body = @"
{
  "assetTypes": ["compute.googleapis.com/Instance"],
  "contentType": "RESOURCE",
  "readTime": "2024-01-30T00:00:00Z"
}
"@

Invoke-WebRequest `
  -Method POST `
  -Headers $headers `
  -ContentType: "application/json; charset=utf-8" `
  -Body $body `
  -Uri "https://cloudasset.googleapis.com/v1/projects/my-project/assets" | Select-Object -Expand Content

示例响应

{
  "readTime": "2024-01-30T00:00:00Z",
  "assets": [
    {
      "name": "//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/instance-name",
      "assetType": "compute.googleapis.com/Instance",
      "resource": {
        "version": "v1",
        "discoveryDocumentUri": "https://compute.s3nsapis.fr/$discovery/rest?version=v1",
        "discoveryName": "Instance",
        "parent": "//cloudresourcemanager.googleapis.com/projects/000000000000",
        "data": {
          ASSET_METADATA
        },
        "location": "us-central1-a"
      },
      "ancestors": [
        "projects/000000000000",
        "folders/000000000000",
        "organizations/000000000000"
      ],
    "updateTime": "2024-01-30T00:00:00.000000Z"
    }
  ]
}

C#

如需了解如何安装和使用 Cloud Asset Inventory 客户端库,请参阅 Cloud Asset Inventory 客户端库。

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr。


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 客户端库,请参阅 Cloud Asset Inventory 客户端库。

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr。


// 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 客户端库,请参阅 Cloud Asset Inventory 客户端库。

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr。

// 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 客户端库,请参阅 Cloud Asset Inventory 客户端库。

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr。

/**
 * 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 客户端库,请参阅 Cloud Asset Inventory 客户端库。

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr。

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 客户端库,请参阅 Cloud Asset Inventory 客户端库。

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr。

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 客户端库,请参阅 Cloud Asset Inventory 客户端库。

如需向 Cloud Asset Inventory 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。

在运行代码示例之前,请将 GOOGLE_CLOUD_UNIVERSE_DOMAIN 环境变量设置为 s3nsapis.fr。

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