使用 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

      您可以使用下列指令,擷取位於機構組織層級的 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))"
  • 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,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


// 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,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * 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,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


// 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,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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);
  // Do things with with the response.
  console.log(util.inspect(result, {depth: null}));
}
getFeed();

Python

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

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

from google.cloud import asset_v1

# TODO feed_name = 'Feed Name you want to get'

client = asset_v1.AssetServiceClient()
response = client.get_feed(request={"name": feed_name})
print(f"gotten_feed: {response}")

列出動態饋給

如要列出專案、資料夾或機構的所有動態消息,請提出下列其中一個要求。

gcloud

gcloud asset feeds list \
    --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 主題的權限。 進一步瞭解如何設定帳單專案

如要瞭解所有選項,請參閱 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

標頭:

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 資料集和資料表的權限。 進一步瞭解如何設定帳單專案

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

指令範例

執行下列任一指令,列出 my-project 專案中的所有動態消息。

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

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" | Select-Object -Expand Content

回覆範例

{
  "feeds": [
    {
      "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,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


// Sample list-feeds list feeds.
package main

import (
	"context"
	"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"
)

func main() {
	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)
	parent := fmt.Sprintf("projects/%s", projectNumber)
	req := &assetpb.ListFeedsRequest{
		Parent: parent}
	response, err := client.ListFeeds(ctx, req)
	if err != nil {
		log.Fatalf("client.ListFeeds: %v", err)
	}
	fmt.Print(response)
}

Java

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

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

import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.ListFeedsResponse;
import com.google.cloud.asset.v1.ProjectName;

public class ListFeedsExample {
  // List feeds in a project.
  public static void listFeeds(String projectId) throws Exception {
    // String projectId = "MY_PROJECT_ID"
    // String topic = "projects/[PROJECT_ID]/topics/[TOPIC_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()) {
      ListFeedsResponse response = client.listFeeds(ProjectName.of(projectId).toString());
      System.out.println("Listed feeds under: " + projectId);
    } catch (Exception e) {
      System.out.println("Error during ListFeeds: \n" + e.toString());
    }
  }
}

Node.js

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

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

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

const client = new AssetServiceClient();

async function listFeeds() {
  const projectId = await client.getProjectId();

  const request = {
    parent: `projects/${projectId}`,
  };

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

Python

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

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

from google.cloud import asset_v1

# TODO parent_resource = 'Parent resource you want to list all feeds'

client = asset_v1.AssetServiceClient()
response = client.list_feeds(request={"parent": parent_resource})
print(f"feeds: {response.feeds}")

更新動態饋給

如要更新現有動態饋給的屬性,請採取下列任一做法:

  • 在動態饋給中新增及移除特定資產名稱,或清除所有資產名稱。

  • 在動態饋給中新增及移除特定類型的素材資源,或清除所有素材資源。

  • 覆寫條件或從動態饋給中清除條件。

gcloud

gcloud asset feeds update FEED_ID \
    --SCOPE \
    --billing-project=BILLING_PROJECT_ID \
    --pubsub-topic=projects/TOPIC_PROJECT_ID/topics/TOPIC_ID \
    --clear-asset-names \
    --add-asset-names=ASSET_NAME_1,ASSET_NAME_2,... \
    --remove-asset-names=ASSET_NAME_3,ASSET_NAME_4,... \
    --clear-asset-types \
    --add-asset-types=ASSET_TYPE_1,ASSET_TYPE_2,... \
    --remove-asset-types=ASSET_TYPE_3,ASSET_TYPE_4,... \
    --clear-content-type \
    --content-type=CONTENT_TYPE \
    --clear-relationship-types \
    --remove-relationship-types=RELATIONSHIP_TYPE_1,RELATIONSHIP_TYPE_2,... \
    --add-relationship-types=RELATIONSHIP_TYPE_1,RELATIONSHIP_TYPE_2,... \
    --clear-condition-title \
    --condition-title="CONDITION_TITLE" \
    --clear-condition-description \
    --condition-description="CONDITION_DESCRIPTION" \
    --clear-condition-expression
    --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

      您可以使用下列指令,擷取位於機構組織層級的 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))"
  • 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-project 專案中的 my-topic Pub/Sub 主題。這項要求會從監控中移除所有資產名稱,並新增資產類型 gkemulticloud.googleapis.com/AttachedCluster

gcloud asset feeds update my-feed \
    --project=my-project \
    --pubsub-topic=projects/my-project/topics/my-topic \
    --clear-asset-names \
    --add-asset-types=gkemulticloud.googleapis.com/AttachedCluster

回覆範例

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

如要更新動態饋給的屬性,請在 update_mask 中指定屬性路徑,以及該屬性的值。

REST

HTTP 方法和網址:

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

標頭:

X-Goog-User-Project: BILLING_PROJECT_ID

JSON 要求內文:

{
  "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"
  },
  "update_mask": {
    "paths": [
      "feed_output_config.pubsub_destination.topic",
      ATTRIBUTE_PATH_1,
      ATTRIBUTE_PATH_2,
      ...
    ]
  }
}

提供以下這些值:

  • 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-project 專案中的 my-topic Pub/Sub 主題。這項要求會從監控中移除所有資產名稱,並新增資產類型 gkemulticloud.googleapis.com/AttachedCluster

curl (Linux、macOS 或 Cloud Shell)

curl -X PATCH \
     -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 '{
            "feed": {
              "assetNames": [],
              "assetTypes": [
                "gkemulticloud.googleapis.com/AttachedCluster"
              ],
              "feedOutputConfig": {
                "pubsubDestination": {
                  "topic": "projects/my-project/topics/my-topic"
                }
              }
            },
            "update_mask": {
              "paths": ["feed_output_config.pubsub_destination.topic", "asset_names", "asset_types"]
            }
          }' \
     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"
}


$body = @"
{
  "feed": {
    "assetNames": [],
    "assetTypes": [
      "gkemulticloud.googleapis.com/AttachedCluster"
    ],
    "feedOutputConfig": {
      "pubsubDestination": {
        "topic": "projects/my-project/topics/my-topic"
      }
    }
  },
  "update_mask": {
    "paths": ["feed_output_config.pubsub_destination.topic", "asset_names", "asset_types"]
  }
}
"@

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

回覆範例

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

Go

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

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


// Sample update-feed update 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"
	field_mask "google.golang.org/genproto/protobuf/field_mask"
)

// 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)
	topic := fmt.Sprintf("projects/%s/topics/%s", projectID, "TOPIC_TO_UPDATE")

	req := &assetpb.UpdateFeedRequest{
		Feed: &assetpb.Feed{
			Name: feedName,
			FeedOutputConfig: &assetpb.FeedOutputConfig{
				Destination: &assetpb.FeedOutputConfig_PubsubDestination{
					PubsubDestination: &assetpb.PubsubDestination{
						Topic: topic,
					},
				},
			},
		},
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"feed_output_config.pubsub_destination.topic"},
		},
	}
	response, err := client.UpdateFeed(ctx, req)
	if err != nil {
		log.Fatalf("client.UpdateFeed: %v", err)
	}
	fmt.Print(response)
}

Java

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

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

import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.Feed;
import com.google.cloud.asset.v1.FeedOutputConfig;
import com.google.cloud.asset.v1.PubsubDestination;
import com.google.cloud.asset.v1.UpdateFeedRequest;
import com.google.protobuf.FieldMask;

public class UpdateFeedExample {

  // Update a feed
  public static void updateFeed(String feedName, String topic) throws Exception {
    // String feedName = "MY_FEED_NAME"
    // String topic = "projects/[PROJECT_ID]/topics/[TOPIC_NAME]"
    Feed feed =
        Feed.newBuilder()
            .setName(feedName)
            .setFeedOutputConfig(
                FeedOutputConfig.newBuilder()
                    .setPubsubDestination(PubsubDestination.newBuilder().setTopic(topic).build())
                    .build())
            .build();
    UpdateFeedRequest request =
        UpdateFeedRequest.newBuilder()
            .setFeed(feed)
            .setUpdateMask(
                FieldMask.newBuilder()
                    .addPaths("feed_output_config.pubsub_destination.topic")
                    .build())
            .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.updateFeed(request);
      System.out.println("Feed updated successfully: " + response.getName());
    } catch (Exception e) {
      System.out.println("Error during UpdateFeed: \n" + e.toString());
    }
  }
}

Node.js

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

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

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

const client = new AssetServiceClient();
// example inputs:
// const fullQueryName = 'folders/<FOLDER_NUMBER>/savedQueries/<QUERY_ID>';
// const description = 'a new description';
async function updateSavedQuery() {
  const request = {
    savedQuery: {
      name: fullQueryName,
      description: description,
    },
    updateMask: {
      paths: ['description'],
    },
  };

  // Handle the operation using the promise pattern.
  const [query] = await client.updateSavedQuery(request);
  // Do things with with the response.
  console.log('Query name:', query.name);
  console.log('Query description:', query.description);
  console.log('Created time:', query.createTime);
  console.log('Updated time:', query.lastUpdateTime);
  console.log('Query type:', query.content.queryContent);
  console.log('Query content:', JSON.stringify(query.content, null, 4));

Python

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

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

from google.cloud import asset_v1
from google.protobuf import field_mask_pb2

# TODO feed_name = 'Feed Name you want to update'
# TODO topic = "Topic name you want to update with"

client = asset_v1.AssetServiceClient()
feed = asset_v1.Feed()
feed.name = feed_name
feed.feed_output_config.pubsub_destination.topic = topic
update_mask = field_mask_pb2.FieldMask()
# In this example, we update topic of the feed
update_mask.paths.append("feed_output_config.pubsub_destination.topic")
response = client.update_feed(request={"feed": feed, "update_mask": update_mask})
print(f"updated_feed: {response}")

刪除動態消息

如要停止接收資產變更通知,請提出下列其中一項要求來刪除動態消息。

gcloud

gcloud asset feeds delete 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 主題的權限。 進一步瞭解如何設定帳單專案

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

回覆範例

成功刪除後不會傳回任何回應。

REST

HTTP 方法和網址:

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

標頭:

X-Goog-User-Project: BILLING_PROJECT_ID

提供以下這些值:

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

    允許的值如下:

    • 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 主題的權限。 進一步瞭解如何設定帳單專案

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

指令範例

執行下列任一指令,刪除特定動態消息。

curl (Linux、macOS 或 Cloud Shell)

curl -X DELETE \
     -H "X-Goog-User-Project: BILLING_PROJECT_ID" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     https://cloudasset.googleapis.com/v1/projects/000000000000/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 DELETE `
  -Headers $headers `
  -Uri "https://cloudasset.googleapis.com/v1/projects/000000000000/feeds/my-feed" | Select-Object -Expand Content

回覆範例

{}

Go

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

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


// Sample delete-feed delete 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.DeleteFeedRequest{
		Name: feedName,
	}
	if err = client.DeleteFeed(ctx, req); err != nil {
		log.Fatalf("client.DeleteFeed: %v", err)
	}
	fmt.Print("Deleted Feed")
}

Java

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

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

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

public class DeleteFeedExample {

  // Delete a feed with full feed name
  public static void deleteFeed(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()) {
      client.deleteFeed(feedName);
      System.out.println("Feed deleted");
    } catch (Exception e) {
      System.out.println("Error during DeleteFeed: \n" + e.toString());
    }
  }
}

Node.js

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

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

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

const client = new AssetServiceClient();

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

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

Python

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

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

from google.cloud import asset_v1

# TODO feed_name = 'Feed name you want to delete'

client = asset_v1.AssetServiceClient()
client.delete_feed(request={"name": feed_name})
print("deleted_feed")

動態饋給條件

如要只查看特定素材資源的特定類型變更,可以在動態饋給中新增條件。條件是以一般運算語言 (CEL) 編寫。

條件支援功能有限。在某些情況下,建立或更新附帶條件的動態饋給可能會導致延遲。

限制

  • 條件運算式的長度上限為 3,000 個半形字元。

  • 條件運算式中的大多數變數名稱都以小寫表示,每個字之間以底線分隔。例如 example_variable

    例外狀況是 data 的子欄位變數名稱位於「Resource」物件中。這類名稱沒有字詞分隔符,且第一個字詞之後的每個字詞首字母都會大寫。例如:exampleVariable

  • 系統會在建立或更新動態饋給時,對條件運算式執行部分驗證。不過,這類驗證並不完整,尤其是針對 temporal_asset.asset.resource.data 欄位設定的條件,因為該欄位具有動態型別。請盡可能改用適當的 gcloud CLI 或 REST API 參數來篩選動態饋給。

  • 如果評估期間發生錯誤,系統不會傳送通知,但會記錄錯誤

  • 如果是 temporal_asset.asset.resource.data 中的動態類型,在缺少的欄位上指定的條件會觸發執行階段錯誤,且不會發布通知。舉例來說,如果更新中缺少 name 欄位,系統會評估條件 temporal_asset.asset.resource.data.name != "my_name" 是否成立,如果條件不成立,您就不會收到通知。如果條件只能在特定欄位存在時運作,請在條件中新增存在性檢查,確保系統正確評估條件。

  • 靜態列舉型別可以表示為完整路徑名稱或原始整數。舉例來說,下列運算式適用於 prior_asset_state

    temporal_asset.prior_asset_state == google.cloud.asset.v1.TemporalAsset.PriorAssetState.DOES_NOT_EXIST
    

    temporal_asset.prior_asset_state == 3
    

    temporal_asset.asset.resource.data 中的動態列舉類型會以原始字串表示。舉例來說,下列運算式適用於資產類型 cloudresourcemanager.googleapis.com/Project

    temporal_asset.asset.resource.data.lifecycleState == "ACTIVE"
    

使用 CEL 建立條件運算式

在動態饋給條件中,一般運算語言 (CEL) 可根據屬性資料做出布林決策。條件運算式由一或多個陳述式組成,並使用邏輯運算子聯結。每項陳述式都會表示以屬性為依據的控制規則,適用於 TemporalAsset,用來判斷是否要傳送通知。

以下是動態消息條件最重要的 CEL 功能:

  • 變數:條件會使用變數來表示特定屬性,例如 temporal_asset.deleted (Boolean) 或 temporal_asset.asset.name (String)。這些變數會根據執行階段的環境填入值。

  • 運算子:每個資料類型 (例如 String) 都支援一組運算子,可用於建立邏輯運算式。最常見的用法是使用運算子比較變數中包含的值與常值,例如 temporal_asset.asset.name == "//cloudresourcemanager.googleapis.com/projects/12345"。在這個範例中,如果 temporal_asset.asset.name 的輸入值為 //cloudresourcemanager.googleapis.com/projects/12345,則運算式會評估為 true

  • 函式:函式是資料類型的複合運算子,支援更複雜的運算。在條件運算式中,您可以搭配特定資料類型使用預先定義的函式。舉例來說,temporal_asset.asset.name.contains("keyword") 會使用名為 contains 的函式,檢查 temporal_asset.asset.name 的值是否包含 "keyword"。如果是,則評估結果為 true

  • 邏輯運算子:條件支援邏輯運算子,可用於從基本運算式陳述式建構複雜的邏輯運算式:&& (AND) 和 || (OR)。這些邏輯運算子可讓您在條件運算式中使用多個輸入變數。舉例來說: temporal_asset.deleted && temporal_asset.window.start_time.getFullYear() > 2020 會彙整兩個基本陳述式,且必須滿足這兩個陳述式,才能產生 true 評估結果。

如要進一步瞭解 CEL 功能,請參閱語言定義

使用條件變數

條件變數可讓您根據不同屬性建立條件。支援的條件變數包括:

  • temporal_asset:採用 TemporalAsset 格式的最新資產變更。如果條件評估結果為 true,系統會將 TemporalAsset 傳送至設定的目的地。

條件運算式範例

下列條件運算式會在建立事件時傳送通知:

temporal_asset.deleted == false &&
temporal_asset.prior_asset_state == google.cloud.asset.v1.TemporalAsset.PriorAssetState.DOES_NOT_EXIST

下列條件運算式會針對位於資料夾 1234523456 中的資源傳送通知:

"folders/12345" in temporal_asset.asset.ancestors ||
"folders/23456" in temporal_asset.asset.ancestors

假設資產類型已在動態饋給中設為 compute.googleapis.com/Firewall,下列條件運算式會在防火牆新增允許的規則時傳送通知:

size(temporal_asset.asset.resource.data.allowed) >
size(temporal_asset.prior_asset.resource.data.allowed)

假設動態饋給中的資產類型已設為 compute.googleapis.com/Instance,下列條件運算式會針對具有 n1-standard-1 機器類型的 VM 執行個體傳送通知:

temporal_asset.asset.resource.data.machineType.endsWith('/machineTypes/n1-standard-1')

假設資產類型在動態饋給中設為 storage.googleapis.com/Bucket,內容類型設為 IAM_POLICY,則下列條件運算式會針對具有任何 IAM 政策的儲存空間值區傳送通知:allUsers

temporal_asset.asset.iam_policy.bindings.exists(b, b.members.exists(m, m == "allUsers"))

如果儲存空間 bucket 的標籤中含有 test 鍵,且該 bucket 已遭刪除,下列條件運算式就會傳送通知:

temporal_asset.deleted == true && temporal_asset.prior_asset_state == google.cloud.asset.v1.TemporalAsset.PriorAssetState.PRESENT && "test" in temporal_asset.prior_asset.resource.data.labels

疑難排解

如果沒有收到資源或 IAM 政策更新通知,請按照下列步驟排解問題:

  • 確認資產的中繼資料已變更。只有在支援的資源類型中繼資料變更時,即時動態消息才會傳送更新。 將新檔案上傳至 Cloud Storage bucket 等作業不會觸發中繼資料變更。

  • 請確認資產符合你在動態饋給中指定的其中一個資產名稱或類型。

  • 刪除專案時,請注意關閉專案後,您有 30 天的時間可以復原。因此,在永久刪除專案前,資產中繼資料中的 deleted 欄位不會設定。如要監控待刪除的專案,請改為在專案的 lifecycleState 欄位中設定條件。例如: temporal_asset.asset.resource.data.lifecycleState == "DELETE_REQUESTED"

  • 檢查記錄,確認發布主題更新時是否發生錯誤。

Cloud Logging

如果即時動態饋給無法透過 Pub/Sub 傳送資源或 IAM 政策更新,Cloud Asset Inventory 會在 Logging 中記錄錯誤狀態和訊息。系統預設會啟用記錄功能,並歸類為 Google Cloud Observability。瞭解 Google Cloud Observability 定價

查看即時動態饋給記錄

即時動態消息記錄會依 Pub/Sub 主題建立索引。如要查看所有記錄:

  1. 前往 Google Cloud 控制台的「Logs Explorer」頁面。

    前往「Logs Explorer」頁面

  2. 按一下「搜尋所有欄位」方塊附近的「資源」清單。

  3. 搜尋 Cloud Pub/Sub Topic,然後按一下「Cloud Pub/Sub Topic」資源類型。

  4. 按一下要查看的主題 ID。

  5. 按一下 [套用]

系統會對記錄檔欄位強制採用 UTF-8 編碼。非 UTF-8 字元都會替換為問號。

記錄資訊

即時動態饋給記錄項目包含下列類型的資訊:

  • 多數 Google Cloud 記錄檔所示的一般資訊,如嚴重性、專案 ID、專案編號或時間戳記。

  • jsonPayload 中的動態饋給即時記錄欄位,包含資產名稱、動態饋給輸出設定,以及發布資源或 IAM 政策更新時的錯誤狀態。

下表說明每個欄位包含的資訊類型。

欄位 類型和說明
name

string

動態饋給的全名。格式如下:

  • projects/PROJECT_ID/feeds/FEED_ID
  • folders/FOLDER_ID/feeds/FEED_ID
  • organizations/ORGANIZATION_ID/feeds/FEED_ID
asset_name

string

要接收更新的資產全名。例如:

//compute.googleapis.com/projects/my_project_123/zones/zone1/instances/instance1

詳情請參閱「 資源名稱 」。

condition

Expr

動態饋給條件,用於判斷是否應發布資產更新。

error_status

Status

無法將資產更新發布至動態饋給時的狀態。

feed_output_config

FeedOutputConfig

動態饋給輸出設定,定義資產更新的發布位置。