取得資產記錄

您最多可以擷取 Google Cloud 專案或機構中資產的 35 天建立、更新和刪除記錄。如果素材資源在過去 35 天內沒有變更,系統會回報最新狀態。

事前準備

  1. 在您執行 Cloud Asset Inventory 指令的專案中,啟用 Cloud Asset Inventory API。

    啟用 Cloud Asset Inventory API

  2. 請確認您的帳戶具有呼叫 Cloud Asset Inventory API 的正確角色。 如要瞭解各通話類型的個別權限,請參閱「權限」。

限制

您只能在機構和專案層級擷取資產記錄。 不支援資料夾。

取得資產記錄

控制台

如要取得儲存在 Google Cloud中的資產記錄,請完成下列步驟。

  1. 前往 Google Cloud 控制台的「資產清單」頁面。

    前往 Asset Inventory

  2. 切換至要搜尋的專案、資料夾或機構。
  3. 按一下「資源」分頁標籤。
  4. 在「篩選結果」面板中,選取資源類型或位置,篩選結果。
  5. 在結果面板中按一下資源。
  6. 按一下「變更記錄」分頁標籤。
  7. 選取報表的「開始時間」和「結束時間」
  8. 使用「選取要比較的記錄」清單方塊,顯示所選日期記錄之間的差異。

執行搜尋後,與查詢相符的資源會列在「結果」表格中。按兩下查詢即可編輯,或使用「篩選結果」窗格,依特定條件限制搜尋結果。

如要以 Google Cloud CLI 指令查看查詢,請按一下「查看查詢」

如要匯出結果,請按一下「下載 CSV」

gcloud

gcloud asset get-history \
    --SCOPE \
    --asset-names=ASSET_NAME_1,ASSET_NAME_2,... \
    --content-type=CONTENT_TYPE \
    --relationship-types=RELATIONSHIP_TYPE_1,RELATIONSHIP_TYPE_2,... \
    --start-time="START_TIME" \
    --end-time="END_TIME"

提供以下這些值:

  • SCOPE:請使用下列其中一個值:

    • project=PROJECT_ID,其中 PROJECT_ID 是要擷取資產的專案 ID。
    • organization=ORGANIZATION_ID,其中 ORGANIZATION_ID 是擁有要擷取資產的機構 ID。

      如何查看機構的 ID Google Cloud

      Google Cloud 控制台

      如要找出 Google Cloud 機構的 ID,請完成下列步驟:

      1. 前往 Google Cloud 控制台。

        前往 Google Cloud 控制台

      2. 按一下選單列中的「切換器」清單方塊。
      3. 從清單方塊中選取機構。
      4. 按一下「全部」分頁標籤。機構 ID 會顯示在機構名稱旁邊。

      gcloud CLI

      您可以使用下列指令擷取機構的 ID: Google Cloud

      gcloud organizations describe ORGANIZATION_NAME --format="value(name.segment(1))"
  • ASSET_NAME_#:以逗號分隔的資產完整名稱清單。
  • CONTENT_TYPE:您要擷取的中繼資料 內容類型。如果未指定 --content-type,則只會傳回基本資訊,例如資產名稱、資產上次更新時間,以及資產所屬的專案、資料夾和機構。
  • RELATIONSHIP_TYPE_#:選用。您必須有 Security Command Center Premium 或 Enterprise 級別的存取權,或是 Gemini Cloud Assist 存取權,以半形逗號分隔的資產關係類型清單,列出您要擷取的類型。您必須將 CONTENT_TYPE 設為 RELATIONSHIP, 這項功能才能正常運作。
  • START_TIME:時間範圍的開頭,採用 gcloud topic datetime 格式。這個值不得超過 35 天前。
  • END_TIME:選用。時間範圍的結束點,格式為 gcloud topic datetime format。這個值不得超過 35 天前。如未指定 --end-time,系統會設為目前時間。

如要瞭解所有選項,請參閱 gcloud CLI 參考資料

範例

執行下列指令,取得 2024 年 1 月 30 日至 2024 年 2 月 5 日期間,my-project 專案中 Compute Engine 執行個體的 resource 歷史記錄中繼資料。my-instance執行個體具有下列屬性:

  • 執行個體名稱my-instance
  • 專案my-project
  • 位置us-central1-a
gcloud asset get-history \
    --project=my-project \
    --asset-names=//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance \
    --content-type=resource \
    --start-time="2024-01-30" \
    --end-time="2024-02-05"

回覆範例

---
asset:
  ancestors:
  - projects/000000000000
  - folders/000000000000
  - organizations/000000000000
  assetType: compute.googleapis.com/Instance
  name: //compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance
  resource:
    data:
      LATEST_ASSET_METADATA
    discoveryDocumentUri: https://www.googleapis.com/discovery/v1/apis/compute/v1/rest
    discoveryName: Instance
    location: us-central1-a
    parent: //cloudresourcemanager.googleapis.com/projects/000000000000
    version: v1
  updateTime: '2024-02-05T16:00:25.259186Z'
window:
  endTime: '2024-02-05T16:00:25.259186Z'
  startTime: '2024-02-03T16:00:28.854779Z'
---
asset:
  ancestors:
  - projects/000000000000
  - folders/000000000000
  - organizations/000000000000
  assetType: compute.googleapis.com/Instance
  name: //compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance
  resource:
    data:
      EARLIEST_ASSET_METADATA
    discoveryDocumentUri: https://www.googleapis.com/discovery/v1/apis/compute/v1/rest
    discoveryName: Instance
    location: us-central1-a
    parent: //cloudresourcemanager.googleapis.com/projects/000000000000
    version: v1
  updateTime: '2024-02-03T16:00:28.854779Z'
window:
  endTime: '2024-02-03T16:00:28.854779Z'
  startTime: '2024-01-30T08:00:22.930462Z'

REST

HTTP 方法和網址:

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

JSON 要求內文:

{
  "assetNames": [
    "ASSET_NAME_1",
    "ASSET_NAME_2",
    "..."
  ],
  "contentType": "CONTENT_TYPE",
  "relationshipTypes": [
    "RELATIONSHIP_TYPE_1",
    "RELATIONSHIP_TYPE_2",
    "..."
  ],
  "readTimeWindow": {
    "startTime": "START_TIME",
    "endTime": "END_TIME"
  }
}

提供以下這些值:

  • SCOPE_PATH:請使用下列其中一個值:

    允許的值如下:

    • projects/PROJECT_ID,其中 PROJECT_ID 是要擷取資產的專案 ID。
    • projects/PROJECT_NUMBER,其中 PROJECT_NUMBER 是含有要擷取資產的專案編號。

      如何找出 Google Cloud 專案編號

      Google Cloud 控制台

      如要找出專案編號,請完成下列步驟: Google Cloud

      1. 前往 Google Cloud 控制台的「Welcome」(歡迎) 頁面。

        前往「歡迎」

      2. 按一下選單列中的「切換器」清單方塊。
      3. 從清單方塊中選取機構,然後搜尋專案名稱。 專案名稱、專案編號和專案 ID 會顯示在「歡迎」標題附近。

        最多會顯示 4,000 個資源。如果找不到所需專案,請前往「管理資源」頁面,然後使用該專案的名稱篩選清單。

      gcloud CLI

      您可以使用下列指令擷取專案編號: Google Cloud

      gcloud projects describe PROJECT_ID --format="value(projectNumber)"
    • organizations/ORGANIZATION_ID,其中 ORGANIZATION_ID 是擁有要擷取資產的機構 ID。

      如何查看機構的 ID Google Cloud

      Google Cloud 控制台

      如要找出 Google Cloud 機構的 ID,請完成下列步驟:

      1. 前往 Google Cloud 控制台。

        前往 Google Cloud 控制台

      2. 按一下選單列中的「切換器」清單方塊。
      3. 從清單方塊中選取機構。
      4. 按一下「全部」分頁標籤。機構 ID 會顯示在機構名稱旁邊。

      gcloud CLI

      您可以使用下列指令擷取機構的 ID: Google Cloud

      gcloud organizations describe ORGANIZATION_NAME --format="value(name.segment(1))"
  • ASSET_NAME_#資產完整名稱的陣列。
  • CONTENT_TYPE:您要擷取的中繼資料 內容類型。如果未指定 contentType,則只會傳回基本資訊,例如資產名稱、資產上次更新時間,以及資產所屬的專案、資料夾和機構。
  • RELATIONSHIP_TYPE_#:選用。您必須有 Security Command Center Premium 或 Enterprise 級別的存取權,或是 Gemini Cloud Assist 存取權,以半形逗號分隔的資產關係類型清單,列出您要擷取的類型。您必須將 CONTENT_TYPE 設為 RELATIONSHIP, 這項功能才能正常運作。
  • START_TIME:時間範圍的開頭,採用 RFC 3339 格式。這個值不得超過 35 天前。
  • END_TIME:選用。時間範圍的結束時間,採用 RFC 3339 格式。這個值不得超過 35 天前。如未指定 endTime,系統會設為目前時間。

如要瞭解所有選項,請參閱 REST 參考資料

指令範例

執行下列任一指令,取得 2024 年 1 月 30 日至 2024 年 2 月 5 日期間,resource專案中my-instance Compute Engine 執行個體的my-project記錄。執行個體具有下列屬性:

  • 執行個體名稱my-instance
  • 專案my-project
  • 位置us-central1-a

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 '{
            "assetNames": ["//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance"],
            "contentType": "RESOURCE",
            "readTimeWindow": {
              "startTime": "2024-01-30T00:00:00Z",
              "endTime": "2024-02-05T00:00:00Z"
            }
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project:batchGetAssetsHistory

PowerShell (Windows)

$cred = gcloud auth print-access-token

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


$body = @"
{
  "assetNames": ["//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance"],
  "contentType": "RESOURCE",
  "readTimeWindow": {
    "startTime": "2024-01-30T00:00:00Z",
    "endTime": "2024-02-05T00: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:batchGetAssetsHistory" | Select-Object -Expand Content

回覆範例

{
  "assets": [
    {
      "window": {
        "startTime": "2024-02-03T16:00:28.854779Z",
        "endTime": "2024-02-05T16:00:25.259186Z"
      },
      "asset": {
        "name": "//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance",
        "assetType": "compute.googleapis.com/Instance",
        "resource": {
          "version": "v1",
          "discoveryDocumentUri": "https://www.googleapis.com/discovery/v1/apis/compute/v1/rest",
          "discoveryName": "Instance",
          "parent": "//cloudresourcemanager.googleapis.com/projects/000000000000",
          "data": {
            LATEST_ASSET_METADATA
          },
          "location": "us-central1-a"
        },
        "ancestors": [
          "projects/000000000000",
          "folders/000000000000",
          "organizations/000000000000"
        ],
        "updateTime": "2024-02-05T16:00:25.259186Z"
      }
    },
    {
      "window": {
        "startTime": "2024-01-30T08:00:22.930462Z",
        "endTime": "2024-02-03T16:00:28.854779Z"
      },
      "asset": {
        "name": "//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/my-instance",
        "assetType": "compute.googleapis.com/Instance",
        "resource": {
          "version": "v1",
          "discoveryDocumentUri": "https://www.googleapis.com/discovery/v1/apis/compute/v1/rest",
          "discoveryName": "Instance",
          "parent": "//cloudresourcemanager.googleapis.com/projects/000000000000",
          "data": {
            EARLIEST_ASSET_METADATA
          },
          "location": "us-central1-a"
        },
        "ancestors": [
          "projects/000000000000",
          "folders/000000000000",
          "organizations/000000000000"
        ],
        "updateTime": "2024-02-03T16:00:28.854779Z"
      }
    }
  ]
}

C#

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱這篇文章

如要驗證 Cloud Asset Inventory,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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

public class BatchGetAssetsHistorySample
{
    public BatchGetAssetsHistoryResponse BatchGetAssetsHistory(string[] assetNames, DateTimeOffset startTime, 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.FromDateTimeOffset(startTime)
            }
        };
        request.AssetNames.AddRange(assetNames);

        // Call the API.
        BatchGetAssetsHistoryResponse response = client.BatchGetAssetsHistory(request);

        // Return the result.
        return response;
    }
}

Go

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱這篇文章

如要驗證 Cloud Asset Inventory,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


// Sample asset-quickstart batch-gets assets history.
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"time"

	asset "cloud.google.com/go/asset/apiv1"
	"cloud.google.com/go/asset/apiv1/assetpb"
	"github.com/golang/protobuf/ptypes/timestamp"
)

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

Java

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱這篇文章

如要驗證 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.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);
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱這篇文章

如要驗證 Cloud Asset Inventory,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const assetNames = '//storage.googleapis.com/<BUCKET_NAME1>,//storage.googleapis.com/<BUCKET_NAME2>';
// const contentType = 'RESOURCE';

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

PHP

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱這篇文章

如要驗證 Cloud Asset Inventory,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Asset\V1\BatchGetAssetsHistoryRequest;
use Google\Cloud\Asset\V1\Client\AssetServiceClient;
use Google\Cloud\Asset\V1\ContentType;
use Google\Cloud\Asset\V1\TimeWindow;
use Google\Protobuf\Timestamp;

/**
 * @param string   $projectId  Tthe project Id for list assets.
 * @param string[] $assetNames (Optional) Asset types to list for.
 */
function batch_get_assets_history(string $projectId, array $assetNames): void
{
    $client = new AssetServiceClient();
    $formattedParent = $client->projectName($projectId);
    $contentType = ContentType::RESOURCE;
    $readTimeWindow = new TimeWindow(['start_time' => new Timestamp(['seconds' => time()])]);
    $request = (new BatchGetAssetsHistoryRequest())
        ->setParent($formattedParent)
        ->setContentType($contentType)
        ->setReadTimeWindow($readTimeWindow)
        ->setAssetNames($assetNames);

    $resp = $client->batchGetAssetsHistory($request);

    # Do things with response.
    print($resp->serializeToString());
}

Python

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱這篇文章

如要驗證 Cloud Asset Inventory,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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 = f"projects/{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(f"assets: {response.assets}")

Ruby

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱這篇文章

如要驗證 Cloud Asset Inventory,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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