使用 Pub/Sub 監控資產變更

您可以建立及訂閱動態消息,接收資源和政策變更的即時通知。

建立資訊提供時,您可以指定要監控機構、資料夾、專案中支援的資源類型、IAM 政策、存取權政策和機構政策的變更。此外,你也可以在動態饋給中新增條件,只接收特定類型素材資源變更的通知。

建立動態饋給後,每當指定資產有變更,您就會透過 Pub/Sub 收到通知。發布至 Pub/Sub 主題的第一則訊息是字串格式的歡迎訊息,後續所有訊息都是 TemporalAsset 格式。

以下是 RESOURCE 內容類型的 Pub/Sub 訊息範例。

{
  "asset":{
    "ancestors":[
      "projects/000000000000",
      "folders/000000000000",
      "organizations/000000000000"
    ],
    "assetType":"storage.googleapis.com/Bucket",
    "name":"//storage.googleapis.com/my-bucket",
    "resource":{
      "data":{
        LATEST_ASSET_METADATA
      },
      "discoveryDocumentUri":"https://www.googleapis.com/discovery/v1/apis/storage/v1/rest",
      "discoveryName":"Bucket",
      "location":"us",
      "parent":"//cloudresourcemanager.googleapis.com/projects/000000000000",
      "version":"v1"
    },
    "updateTime":"2024-01-30T00:00:00.000000Z"
  },
  "priorAsset":{
    "ancestors":[
      "projects/000000000000",
      "folders/000000000000",
      "organizations/000000000000"
    ],
    "assetType":"storage.googleapis.com/Bucket",
    "name":"//storage.googleapis.com/my-bucket",
    "resource":{
      "data":{
        PREVIOUS_ASSET_METADATA
      },
      "discoveryDocumentUri":"https://www.googleapis.com/discovery/v1/apis/storage/v1/rest",
      "discoveryName":"Bucket",
      "location":"us",
      "parent":"//cloudresourcemanager.googleapis.com/projects/000000000000",
      "version":"v1"
    },
    "updateTime":"2024-01-29T00:00:00.000000Z"
  },
  "priorAssetState":"PRESENT",
  "window":{
    "startTime":"2024-01-30T00:00:00.000000Z"
  }
}

如要進一步瞭解 Pub/Sub 或如何設定訂閱項目,請參閱 Pub/Sub 說明文件

事前準備

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

    啟用 Cloud Asset Inventory API

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

  3. 如果沒有 Pub/Sub 主題,請建立一個

限制

  • 建立、更新或刪除動態消息最多可能需要 10 分鐘才會生效。

  • 建立動態消息的專案必須比動態消息更長壽。這是因為用於發布至目的地 Pub/Sub 主題的服務帳戶位於該專案中。動態消息不再運作,且會在專案永久刪除後隨即刪除。

  • 上層最多可建立 200 個動態饋給。這項限制僅適用於直接追蹤上層帳戶的動態消息,不包括子帳戶的動態消息。舉例來說,如果機構中有 10 個專案,每個專案最多可有 200 個動態消息,機構最多也可有 200 個動態消息。

建立動態饋給

gcloud

gcloud asset feeds create FEED_ID \
    --SCOPE \
    --billing-project=BILLING_PROJECT_ID \
    --pubsub-topic=projects/TOPIC_PROJECT_ID/topics/TOPIC_ID \
    --asset-names=ASSET_NAME_1,ASSET_NAME_2,... \
    --asset-types=ASSET_TYPE_1,ASSET_TYPE_2,... \
    --content-type=CONTENT_TYPE \
    --relationship-types=RELATIONSHIP_TYPE_1,RELATIONSHIP_TYPE_2,... \
    --condition-title="CONDITION_TITLE" \
    --condition-description="CONDITION_DESCRIPTION" \
    --condition-expression="CONDITION_EXPRESSION"

提供以下這些值:

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

    • project=PROJECT_ID,其中 PROJECT_ID 是要在其中建立動態消息的專案 ID。
    • folder=FOLDER_ID,其中 FOLDER_ID 是要建立動態消息的資料夾 ID。

      如何找出 Google Cloud 資料夾的 ID

      Google Cloud 控制台

      如要找出 Google Cloud 資料夾的 ID,請完成下列步驟:

      1. 前往 Google Cloud 控制台。

        前往 Google Cloud 控制台

      2. 按一下選單列中的「切換器」清單方塊。
      3. 從清單方塊中選取機構。
      4. 搜尋資料夾名稱。資料夾 ID 會顯示在資料夾名稱旁邊。

      gcloud CLI

      如要擷取機構層級資料夾的 ID,請執行下列指令: Google Cloud

      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。

      如何查看機構的 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))"
  • FEED_ID:專屬素材資源動態饋給 ID。
  • BILLING_PROJECT_ID:選用。預設 Cloud Asset Inventory 服務代理所在的專案 ID,該專案具有管理 Pub/Sub 主題的權限。 進一步瞭解如何設定帳單專案

  • TOPIC_PROJECT_ID:Pub/Sub 主題所在的專案 ID。
  • TOPIC_ID:要發布通知的 Pub/Sub 主題 ID。
  • 至少下列其中一個資產定義:
  • CONTENT_TYPE:選用。要擷取的中繼資料 內容類型。如果未指定 --content-type,則只會傳回基本資訊,例如資產名稱、資產上次更新時間,以及資產所屬的專案、資料夾和機構。
  • RELATIONSHIP_TYPE_#:選用。您必須具備 Security Command Center Premium 或 Enterprise 級別的存取權,或是 Gemini Cloud Assist 的存取權,以半形逗號分隔的資產關係類型清單,列出要擷取的類型。您必須將 CONTENT_TYPE 設為 RELATIONSHIP, 這項功能才能正常運作。
  • 如要新增選用的動態饋給條件,請在指令中加入下列詳細資料:
    • CONDITION_TITLE:指派給動態饋給條件的標題。
    • CONDITION_DESCRIPTION:要指派給動態饋給條件的說明。
    • CONDITION_EXPRESSION:要套用至動態饋給的條件運算式。

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

範例

執行下列指令,在 my-topic Pub/Sub 主題中建立動態消息,以便在 my-project 專案中對下列資源進行變更時收到通知。

  • my-bucket Cloud Storage bucket
  • 任何 BigQuery 資料表
gcloud asset feeds create my-feed \
    --project=my-project \
    --pubsub-topic=projects/my-project/topics/my-topic \
    --asset-names=//storage.googleapis.com/my-bucket \
    --asset-types=bigquery.googleapis.com/Table \
    --content-type=resource

回覆範例

assetNames:
- //storage.googleapis.com/my-bucket
assetTypes:
- bigquery.googleapis.com/Table
condition: {}
contentType: RESOURCE
feedOutputConfig:
  pubsubDestination:
    topic: projects/my-project/topics/my-topic
name: projects/000000000000/feeds/my-feed

REST

HTTP 方法和網址:

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

標頭:

X-Goog-User-Project: BILLING_PROJECT_ID

JSON 要求主體:

{
  "feedId": "FEED_ID",
  "feed": {
    "assetNames": [
      "ASSET_NAME_1",
      "ASSET_NAME_2",
      "..."
    ],
    "assetTypes": [
      "ASSET_TYPE_1",
      "ASSET_TYPE_2",
      "..."
    ],
    "contentType": "CONTENT_TYPE",
    "relationshipTypes": [
      "RELATIONSHIP_TYPE_1",
      "RELATIONSHIP_TYPE_2",
      "..."
    ],
    "feedOutputConfig": {
      "pubsubDestination": {
        "topic": "projects/TOPIC_PROJECT_ID/topics/TOPIC_ID"
      }
    },
    "condition": {
      "title": "CONDITION_TITLE",
      "description": "CONDITION_DESCRIPTION",
      "expression": "CONDITION_EXPRESSION"
    }
  }
}

提供以下這些值:

  • 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)"
    • folders/FOLDER_ID,其中 FOLDER_ID 是要建立動態消息的資料夾 ID。

      如何找出 Google Cloud 資料夾的 ID

      Google Cloud 控制台

      如要找出 Google Cloud 資料夾的 ID,請完成下列步驟:

      1. 前往 Google Cloud 控制台。

        前往 Google Cloud 控制台

      2. 按一下選單列中的「切換器」清單方塊。
      3. 從清單方塊中選取機構。
      4. 搜尋資料夾名稱。資料夾 ID 會顯示在資料夾名稱旁邊。

      gcloud CLI

      您可以使用下列指令,擷取位於機構組織層級的 Google Cloud 資料夾 ID:

      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。

      如何查看機構的 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))"
  • BILLING_PROJECT_ID:預設 Cloud Asset Inventory 服務代理所在的專案 ID,該專案具有管理 Pub/Sub 主題的權限。 進一步瞭解如何設定帳單專案

  • FEED_ID:專屬素材資源動態饋給 ID。
  • 至少下列其中一個資產定義:
    • ASSET_NAME_#:選用。資產完整名稱陣列。
    • ASSET_TYPE_#:選用。可搜尋的素材資源類型陣列。 支援與 RE2 相容的規則運算式。如果規則運算式與任何支援的資產類型都不相符,系統會傳回 INVALID_ARGUMENT 錯誤。如未指定 assetTypes,系統會傳回所有資產類型。
  • CONTENT_TYPE:選用。要擷取的中繼資料 內容類型。如果未指定 contentType,系統只會傳回基本資訊,例如資產名稱、資產上次更新時間,以及資產所屬的專案、資料夾和機構。
  • RELATIONSHIP_TYPE_#:選用。您必須具備 Security Command Center Premium 或 Enterprise 級別的存取權,或是 Gemini Cloud Assist 的存取權,以半形逗號分隔的資產關係類型清單,列出要擷取的類型。您必須將 CONTENT_TYPE 設為 RELATIONSHIP, 這項功能才能正常運作。
  • TOPIC_PROJECT_ID:Pub/Sub 主題所在的專案 ID。
  • TOPIC_ID:要發布通知的 Pub/Sub 主題 ID。
  • 如要新增選用的動態饋給條件,請在指令中加入下列詳細資料:
    • CONDITION_TITLE:指派給動態饋給條件的標題。
    • CONDITION_DESCRIPTION:要指派給動態饋給條件的說明。
    • CONDITION_EXPRESSION:要套用至動態饋給的條件運算式。

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

指令範例

執行下列任一指令,在 my-topic Pub/Sub 主題中建立動態消息,以便在 my-project 專案中對下列資源進行變更時收到通知。

  • my-bucket Cloud Storage bucket
  • 任何 BigQuery 資料表

curl (Linux、macOS 或 Cloud Shell)

curl -X POST \
     -H "X-Goog-User-Project: BILLING_PROJECT_ID" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
            "feedId": "my-feed",
            "feed": {
              "assetNames": [
                "//storage.googleapis.com/my-bucket"
              ],
              "assetTypes": [
                "bigquery.googleapis.com/Table"
              ],
              "contentType": "RESOURCE",
              "feedOutputConfig": {
                "pubsubDestination": {
                  "topic": "projects/my-project/topics/my-topic"
                }
              }
            }
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project/feeds

PowerShell (Windows)

$cred = gcloud auth print-access-token

$headers = @{ 
  "X-Goog-User-Project" = "BILLING_PROJECT_ID";
  "Authorization" = "Bearer $cred"
}


$body = @"
{
  "feedId": "my-feed",
  "feed": {
    "assetNames": [
      "//storage.googleapis.com/my-bucket"
    ],
    "assetTypes": [
      "bigquery.googleapis.com/Table"
    ],
    "contentType": "RESOURCE",
    "feedOutputConfig": {
      "pubsubDestination": {
        "topic": "projects/my-project/topics/my-topic"
      }
    }
  }
}
"@

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

回覆範例

{
  "name": "projects/000000000000/feeds/my-feed",
  "assetNames": [
    "//storage.googleapis.com/my-bucket"
  ],
  "assetTypes": [
    "bigquery.googleapis.com/Table"
  ],
  "contentType": "RESOURCE",
  "feedOutputConfig": {
    "pubsubDestination": {
      "topic": "projects/my-project/topics/my-topic"
    }
  }
}

Go

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱「Cloud Asset Inventory 用戶端程式庫」。

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


// Sample create-feed create feed.
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"os"

	asset "cloud.google.com/go/asset/apiv1"
	"cloud.google.com/go/asset/apiv1/assetpb"
)

// Command-line flags.
var (
	feedID = flag.String("feed_id", "YOUR_FEED_ID", "Identifier of Feed.")
)

func main() {
	flag.Parse()
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatalf("asset.NewClient: %v", err)
	}
	defer client.Close()

	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	feedParent := fmt.Sprintf("projects/%s", projectID)
	assetNames := []string{"YOUR_ASSET_NAME"}
	topic := fmt.Sprintf("projects/%s/topics/%s", projectID, "YOUR_TOPIC_NAME")

	req := &assetpb.CreateFeedRequest{
		Parent: feedParent,
		FeedId: *feedID,
		Feed: &assetpb.Feed{
			AssetNames: assetNames,
			FeedOutputConfig: &assetpb.FeedOutputConfig{
				Destination: &assetpb.FeedOutputConfig_PubsubDestination{
					PubsubDestination: &assetpb.PubsubDestination{
						Topic: topic,
					},
				},
			},
		}}
	response, err := client.CreateFeed(ctx, req)
	if err != nil {
		log.Fatalf("client.CreateFeed: %v", err)
	}
	fmt.Print(response)
}

Java

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱「Cloud Asset Inventory 用戶端程式庫」。

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

import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.ContentType;
import com.google.cloud.asset.v1.CreateFeedRequest;
import com.google.cloud.asset.v1.Feed;
import com.google.cloud.asset.v1.FeedOutputConfig;
import com.google.cloud.asset.v1.ProjectName;
import com.google.cloud.asset.v1.PubsubDestination;
import java.io.IOException;
import java.util.Arrays;

public class CreateFeedExample {
  // Create a feed
  public static void createFeed(
      String[] assetNames, String feedId, String topic, String projectId, ContentType contentType)
      throws IOException, IllegalArgumentException {
    // String[] assetNames = {"MY_ASSET_NAME"}
    // ContentType contentType = contentType
    // String FeedId = "MY_FEED_ID"
    // String topic = "projects/[PROJECT_ID]/topics/[TOPIC_NAME]"
    // String projectID = "MY_PROJECT_ID"
    Feed feed =
        Feed.newBuilder()
            .addAllAssetNames(Arrays.asList(assetNames))
            .setContentType(contentType)
            .setFeedOutputConfig(
                FeedOutputConfig.newBuilder()
                    .setPubsubDestination(PubsubDestination.newBuilder().setTopic(topic).build())
                    .build())
            .build();
    CreateFeedRequest request =
        CreateFeedRequest.newBuilder()
            .setParent(String.format(ProjectName.of(projectId).toString()))
            .setFeedId(feedId)
            .setFeed(feed)
            .build();
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AssetServiceClient client = AssetServiceClient.create()) {
      Feed response = client.createFeed(request);
      System.out.println("Feed created successfully: " + response.getName());
    } catch (IOException | IllegalArgumentException e) {
      System.out.println("Error during CreateFeed: \n" + e.toString());
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱「Cloud Asset Inventory 用戶端程式庫」。

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const feedId = 'my feed';
// const assetNames = '//storage.googleapis.com/<BUCKET_NAME1>,//storage.googleapis.com/<BUCKET_NAME2>';
// const topicName = 'projects/<PROJECT_ID>/topics/<TOPIC_ID>'
// const contentType = 'RESOURCE';

const util = require('util');
const {AssetServiceClient} = require('@google-cloud/asset');

const client = new AssetServiceClient();

async function createFeed() {
  const projectId = await client.getProjectId();
  // TODO(developer): Choose asset names, such as //storage.googleapis.com/[YOUR_BUCKET_NAME].
  // const assetNames = ['ASSET_NAME1', 'ASSET_NAME2', ...];

  const request = {
    parent: `projects/${projectId}`,
    feedId: feedId,
    feed: {
      assetNames: assetNames.split(','),
      contentType: contentType,
      feedOutputConfig: {
        pubsubDestination: {
          topic: topicName,
        },
      },
    },
  };

  // Handle the operation using the promise pattern.
  const result = await client.createFeed(request);
  // Do things with with the response.
  console.log(util.inspect(result, {depth: null}));

Python

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱「Cloud Asset Inventory 用戶端程式庫」。

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

from google.cloud import asset_v1

# TODO project_id = 'Your Google Cloud Project ID'
# TODO feed_id = 'Feed ID you want to create'
# TODO asset_names = 'List of asset names the feed listen to'
# TODO topic = "Topic name of the feed"
# TODO content_type ="Content type of the feed"

client = asset_v1.AssetServiceClient()
parent = f"projects/{project_id}"
feed = asset_v1.Feed()
feed.asset_names.extend(asset_names)
feed.feed_output_config.pubsub_destination.topic = topic
feed.content_type = content_type
response = client.create_feed(
    request={"parent": parent, "feed_id": feed_id, "feed": feed}
)
print(f"feed: {response}")

Ruby

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱「Cloud Asset Inventory 用戶端程式庫」。

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

require "google/cloud/asset"

# project_id = 'YOUR_PROJECT_ID'
# feed_id = 'NAME_OF_FEED'
# pubsub_topic = 'YOUR_PUBSUB_TOPIC'
# 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

feed = {
  asset_names:        asset_names,
  feed_output_config: {
    pubsub_destination: {
      topic: pubsub_topic
    }
  }
}
response = asset_service.create_feed(
  parent:  formatted_parent,
  feed_id: feed_id,
  feed:    feed
)
puts "Created feed: #{response.name}"

取得動態消息

gcloud

gcloud asset feeds describe FEED_ID \
    --SCOPE \
    --billing-project=BILLING_PROJECT_ID

提供以下這些值:

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

    • project=PROJECT_ID,其中 PROJECT_ID 是動態饋給所在的專案 ID。
    • folder=FOLDER_ID,其中 FOLDER_ID 是動態饋給所在資料夾的 ID。

      如何找出 Google Cloud 資料夾的 ID

      Google Cloud 控制台

      如要找出 Google Cloud 資料夾的 ID,請完成下列步驟:

      1. 前往 Google Cloud 控制台。

        前往 Google Cloud 控制台

      2. 按一下選單列中的「切換器」清單方塊。
      3. 從清單方塊中選取機構。
      4. 搜尋資料夾名稱。資料夾 ID 會顯示在資料夾名稱旁邊。

      gcloud CLI

      您可以使用下列指令,擷取位於機構組織層級的 Google Cloud 資料夾 ID:

      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。

      如何查看機構的 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))"
  • BILLING_PROJECT_ID:預設 Cloud Asset Inventory 服務代理所在的專案 ID,該專案具有管理 Pub/Sub 主題的權限。 進一步瞭解如何設定帳單專案

  • FEED_ID:專屬素材資源動態饋給 ID。

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

回覆範例

assetNames:
- //storage.googleapis.com/my-bucket
assetTypes:
- bigquery.googleapis.com/Table
condition: {}
contentType: RESOURCE
feedOutputConfig:
  pubsubDestination:
    topic: projects/my-project/topics/my-topic
name: projects/000000000000/feeds/my-feed

REST

HTTP 方法和網址:

GET https://cloudasset.googleapis.com/v1/SCOPE_PATH/feeds/FEED_ID

標頭:

X-Goog-User-Project: BILLING_PROJECT_ID

提供以下這些值:

  • 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)"
    • folders/FOLDER_ID,其中 FOLDER_ID 是動態饋給所在資料夾的 ID。

      如何找出 Google Cloud 資料夾的 ID

      Google Cloud 控制台

      如要找出 Google Cloud 資料夾的 ID,請完成下列步驟:

      1. 前往 Google Cloud 控制台。

        前往 Google Cloud 控制台

      2. 按一下選單列中的「切換器」清單方塊。
      3. 從清單方塊中選取機構。
      4. 搜尋資料夾名稱。資料夾 ID 會顯示在資料夾名稱旁邊。

      gcloud CLI

      您可以使用下列指令,擷取位於機構組織層級的 Google Cloud 資料夾 ID:

      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。

      如何查看機構的 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))"
  • BILLING_PROJECT_ID:預設 Cloud Asset Inventory 服務代理程式所在的專案 ID,該專案具有管理 BigQuery 資料集和資料表的權限。 進一步瞭解如何設定帳單專案

  • FEED_ID:專屬素材資源動態饋給 ID。

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

指令範例

執行下列任一指令,即可取得特定動態消息。

curl (Linux、macOS 或 Cloud Shell)

curl -X GET \
     -H "X-Goog-User-Project: BILLING_PROJECT_ID" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     https://cloudasset.googleapis.com/v1/projects/my-project/feeds/my-feed

PowerShell (Windows)

$cred = gcloud auth print-access-token

$headers = @{ 
  "X-Goog-User-Project" = "BILLING_PROJECT_ID";
  "Authorization" = "Bearer $cred"
}


Invoke-WebRequest `
  -Method GET `
  -Headers $headers `
  -Uri "https://cloudasset.googleapis.com/v1/projects/my-project/feeds/my-feed" | Select-Object -Expand Content

回覆範例

{
  "name": "projects/000000000000/feeds/my-feed",
  "assetNames": [
    "//storage.googleapis.com/my-bucket"
  ],
  "assetTypes": [
    "bigquery.googleapis.com/Table"
  ],
  "contentType": "RESOURCE",
  "feedOutputConfig": {
    "pubsubDestination": {
      "topic": "projects/my-project/topics/my-topic"
    }
  }
}

Go

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱「Cloud Asset Inventory 用戶端程式庫」。

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


// Sample get-feed get feed.
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"os"
	"strconv"

	asset "cloud.google.com/go/asset/apiv1"
	"cloud.google.com/go/asset/apiv1/assetpb"
	cloudresourcemanager "google.golang.org/api/cloudresourcemanager/v1"
)

// Command-line flags.
var (
	feedID = flag.String("feed_id", "YOUR_FEED_ID", "Identifier of Feed.")
)

func main() {
	flag.Parse()
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatalf("asset.NewClient: %v", err)
	}
	defer client.Close()

	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	cloudresourcemanagerClient, err := cloudresourcemanager.NewService(ctx)
	if err != nil {
		log.Fatalf("cloudresourcemanager.NewService: %v", err)
	}

	project, err := cloudresourcemanagerClient.Projects.Get(projectID).Do()
	if err != nil {
		log.Fatalf("cloudresourcemanagerClient.Projects.Get.Do: %v", err)
	}
	projectNumber := strconv.FormatInt(project.ProjectNumber, 10)
	feedName := fmt.Sprintf("projects/%s/feeds/%s", projectNumber, *feedID)
	req := &assetpb.GetFeedRequest{
		Name: feedName}
	response, err := client.GetFeed(ctx, req)
	if err != nil {
		log.Fatalf("client.GetFeed: %v", err)
	}
	fmt.Print(response)
}

Java

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱「Cloud Asset Inventory 用戶端程式庫」。

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

import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.Feed;

public class GetFeedExample {

  // Get a feed with full feed name
  public static void getFeed(String feedName) throws Exception {
    // String feedName = "MY_FEED_NAME"

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (AssetServiceClient client = AssetServiceClient.create()) {
      Feed feed = client.getFeed(feedName);
      System.out.println("Get a feed: " + feedName);
    } catch (Exception e) {
      System.out.println("Error during GetFeed: \n" + e.toString());
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Cloud Asset Inventory 的用戶端程式庫,請參閱「Cloud Asset Inventory 用戶端程式庫」。

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

const util = require('util');
const {AssetServiceClient} = require('@google-cloud/asset');

const client = new AssetServiceClient();

async function getFeed() {
  const request = {
    name: feedName,
  };

  // Handle the operation using the promise pattern.
  const result = await client.getFeed(request);