搜尋資源

您可以在專案、資料夾或機構中搜尋資源,並使用查詢條件篩選傳回的結果。

事前準備

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

    啟用 Cloud Asset Inventory API

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

建構查詢

建構查詢前,建議先從指定查詢的搜尋要求開始。使用完整回應中的欄位和值,透過搜尋查詢語法建立查詢,並加以修正,直到傳回您想要的結果為止。

如要瞭解可在查詢中使用的欄位,請參閱搜尋所有資源參考文件

系統僅支援搜尋部分資源,如要查看資源名稱,以及確認資源名稱是否適用於搜尋 API,請參閱「資源類型」。

搜尋資源

控制台

如要搜尋資源中繼資料,請完成下列步驟。

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

    前往 Asset Inventory

  2. 切換至要搜尋的專案、資料夾或機構。
  3. 按一下「資源」分頁標籤。
  4. 如要搜尋資源,請在「篩選條件」欄位中輸入查詢。如要瞭解如何編寫搜尋查詢,請參閱「 搜尋查詢語法」。

    如要簡化查詢建構作業,可以按一下「篩選器」欄位,顯示並將可搜尋的欄位新增至查詢。

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

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

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

gcloud

gcloud asset search-all-resources \
    --scope=SCOPE_PATH \
    --query="QUERY" \
    --asset-types=ASSET_TYPE_1,ASSET_TYPE_2,... \
    --order-by="ORDER_BY" \
    --read-mask="READ_MASK"

提供以下這些值:

  • 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))"
  • QUERY:選用。查詢運算式。如果未指定或留空,系統會在指定範圍內搜尋所有資源。如要瞭解如何編寫搜尋查詢,請參閱「搜尋查詢語法」。
  • ASSET_TYPE_#:選用。以半形逗號分隔的 可搜尋素材資源類型清單。 支援與 RE2 相容的規則運算式。如果規則運算式與任何支援的資產類型都不相符,系統會傳回 INVALID_ARGUMENT 錯誤。如未指定 --asset-types,系統會傳回所有資產類型。
  • ORDER_BY:選用。以半形逗號分隔的欄位清單,指定結果的排序順序。預設為遞增排序。在欄位名稱後方新增 DESC,表示遞減順序。如要瞭解可排序的欄位,請參閱 參考說明文件
  • READ_MASK:選用。以半形逗號分隔的欄位清單,指定要在結果中傳回哪些欄位。如要瞭解預設傳回的欄位,以及指定讀取遮罩時應注意的其他條件,請參閱。

您可以使用 --format--flatten 標記,設定 gcloud CLI 輸出內容的格式。

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

範例

執行下列指令,取得 my-project 專案中所有 Compute Engine 執行個體的清單,這些執行個體的instance 完整資源名稱中包含 1。結果會依名稱遞減排序,且由於讀取遮罩的關係,只會傳回 namelocation 欄位。

gcloud asset search-all-resources \
    --scope=projects/my-project \
    --query="name:instance 1" \
    --asset-types=compute.googleapis.com/Instance \
    --order-by="name DESC" \
    --read-mask="name,location"

回覆範例

---
location: us-central1-a
name: //compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/instance-2-1
---
location: us-central1-a
name: //compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/instance-1

REST

HTTP 方法和網址:

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

JSON 要求內文:

{
  "query": "QUERY",
  "assetTypes": [
    "ASSET_TYPE_1",
    "ASSET_TYPE_2",
    "..."
  ],
  "orderBy": "ORDER_BY",
  "pageSize": "PAGE_SIZE",
  "pageToken": "PAGE_TOKEN",
  "readMask": "READ_MASK"
}

提供以下這些值:

  • 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))"
  • QUERY:選用。查詢運算式。如果未指定或留空,系統會在指定範圍內搜尋所有資源。如要瞭解如何編寫搜尋查詢,請參閱「搜尋查詢語法」。
  • ASSET_TYPE_#:選用。可搜尋的素材資源類型陣列。 支援與 RE2 相容的規則運算式。如果規則運算式與任何支援的資產類型都不相符,系統會傳回 INVALID_ARGUMENT 錯誤。如未指定 assetTypes,系統會傳回所有資產類型。
  • ORDER_BY:選用。以半形逗號分隔的欄位清單,指定結果的排序順序。預設為遞增排序。在欄位名稱後方新增 DESC,表示遞減順序。如要瞭解可排序的欄位,請參閱 參考說明文件
  • PAGE_SIZE:選用。每頁要傳回的結果數。上限為 500 個。如果值設為 0 或負值,系統將會選取適當的預設值。系統會傳回 nextPageToken,以擷取後續結果。

  • PAGE_TOKEN:選用。如果要求的回應內容很長,系統會將其分開顯示在多個頁面。如未指定 pageToken,系統會傳回第一頁。 如要呼叫後續頁面,請使用先前回應的 nextPageToken 做為 pageToken 值。
  • READ_MASK:選用。以半形逗號分隔的欄位清單,指定要在結果中傳回哪些欄位。如要瞭解預設傳回的欄位,以及指定讀取遮罩時應注意的其他條件,請參閱。

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

指令範例

執行下列任一指令,即可取得 my-project 專案中所有 Compute Engine 執行個體的清單,其中包含 instance 字詞,後面接著1,位於完整資源名稱中。結果會依名稱遞減排序,且只會傳回 namelocation 欄位。

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 '{
            "query": "name:instance 1",
            "assetTypes": ["compute.googleapis.com/Instance"],
            "orderBy": "name DESC",
            "readMask": "name,location"
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

PowerShell (Windows)

$cred = gcloud auth print-access-token

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


$body = @"
{
  "query": "name:instance 1",
  "assetTypes": ["compute.googleapis.com/Instance"],
  "orderBy": "name DESC",
  "readMask": "name,location"
}
"@

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

回覆範例

{
  "results": [
    {
      "name": "//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/instance-2-1",
      "location": "us-central1-a"
    },
    {
      "name": "//compute.googleapis.com/projects/my-project/zones/us-central1-a/instances/instance-1",
      "location": "us-central1-a"
    }
  ]
}

C#

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

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


using Google.Api.Gax;
using Google.Cloud.Asset.V1;
using System.Collections.Generic;
using System.Linq;

public class SearchAllResourcesSample
{
    public SearchAllResourcesResponse SearchAllResources(string scope, string query)
    {
        // Create the client.
        AssetServiceClient client = AssetServiceClient.Create();

        // Build the request.
        SearchAllResourcesRequest request = new SearchAllResourcesRequest
        {
            Scope = scope,
            Query = query,
        };

        // Call the API.
        PagedEnumerable<SearchAllResourcesResponse, ResourceSearchResult> response = client.SearchAllResources(request);

        // Return the first page.
        IEnumerable<SearchAllResourcesResponse> byPages = response.AsRawResponses();
        return byPages.First();
    }
}

Go

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

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


// Sample search-all-resources searches all resources within the given scope.
package main

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

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

func main() {
	scope := flag.String("scope", "", "Scope of the search.")
	query := flag.String("query", "", "Query statement.")
	flag.Parse()
	ctx := context.Background()
	client, err := asset.NewClient(ctx)
	if err != nil {
		log.Fatalf("asset.NewClient: %v", err)
	}
	defer client.Close()

	req := &assetpb.SearchAllResourcesRequest{
		Scope: *scope,
		Query: *query,
	}
	it := client.SearchAllResources(ctx, req)
	for {
		resource, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(resource)
	}
}

Java

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

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

import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.InvalidArgumentException;
import com.google.cloud.asset.v1.AssetServiceClient;
import com.google.cloud.asset.v1.AssetServiceClient.SearchAllResourcesPagedResponse;
import com.google.cloud.asset.v1.SearchAllResourcesRequest;
import java.io.IOException;
import java.util.Arrays;

public class SearchAllResourcesExample {

  // Searches for all the resources within the given scope.
  public static void searchAllResources(String scope, String query) {
    // TODO(developer): Replace these variables before running the sample.
    String[] assetTypes = {};
    int pageSize = 0;
    String pageToken = "";
    String orderBy = "";

    SearchAllResourcesRequest request =
        SearchAllResourcesRequest.newBuilder()
            .setScope(scope)
            .setQuery(query)
            .addAllAssetTypes(Arrays.asList(assetTypes))
            .setPageSize(pageSize)
            .setPageToken(pageToken)
            .setOrderBy(orderBy)
            .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()) {
      SearchAllResourcesPagedResponse response = client.searchAllResources(request);
      System.out.println("Search completed successfully:\n" + response.getPage().getValues());
    } catch (IOException e) {
      System.out.println(String.format("Failed to create client:%n%s", e.toString()));
    } catch (InvalidArgumentException e) {
      System.out.println(String.format("Invalid request:%n%s", e.toString()));
    } catch (ApiException e) {
      System.out.println(String.format("Error during SearchAllResources:%n%s", e.toString()));
    }
  }
}

Node.js

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

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const scope = '';
// const query = '';
// const assetTypes = [];
// const pageSize = 0;
// const pageToken = '';
// const orderBy = '';

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

const client = new AssetServiceClient();
const projectId = await client.getProjectId();

async function searchAllResources() {
  const request = {
    scope: `projects/${projectId}`,
    query: query,
    assetTypes: assetTypes,
    pageSize: pageSize,
    pageToken: pageToken,
    orderBy: orderBy,
  };
  const options = {
    autoPaginate: false,
  };

  // Handle the operation using the promise pattern.
  const result = await client.searchAllResources(request, options);
  // 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\Client\AssetServiceClient;
use Google\Cloud\Asset\V1\SearchAllResourcesRequest;

/**
 * @param string   $scope      Scope of the search
 * @param string   $query      (Optional) Query statement
 * @param string[] $assetTypes (Optional) Asset types to search for
 * @param int      $pageSize   (Optional) Size of each result page
 * @param string   $pageToken  (Optional) Token produced by the preceding call
 * @param string   $orderBy    (Optional) Fields to sort the results
 */
function search_all_resources(
    string $scope,
    string $query = '',
    array $assetTypes = [],
    int $pageSize = 0,
    string $pageToken = '',
    string $orderBy = ''
): void {
    // Instantiate a client.
    $asset = new AssetServiceClient();

    // Run request
    $request = (new SearchAllResourcesRequest())
        ->setScope($scope)
        ->setQuery($query)
        ->setAssetTypes($assetTypes)
        ->setPageSize($pageSize)
        ->setPageToken($pageToken)
        ->setOrderBy($orderBy);
    $response = $asset->searchAllResources($request);

    // Print the resource names in the first page of the result
    foreach ($response->getPage() as $resource) {
        print($resource->getName() . PHP_EOL);
    }
}

Python

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

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

from google.cloud import asset_v1

# TODO scope = 'Scope of the search'
# TODO query = 'Query statement'
# TODO asset_types = 'List of asset types to search for'
# TODO page_size = Size of each result page
# TODO order_by = 'Fields to sort the results'

client = asset_v1.AssetServiceClient()
response = client.search_all_resources(
    request={
        "scope": scope,
        "query": query,
        "asset_types": asset_types,
        "page_size": page_size,
        "order_by": order_by,
    }
)
for resource in response:
    print(resource)

Ruby

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

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

require "google/cloud/asset"

# scope = 'SCOPE_OF_THE_QUERY'
# query = 'QUERY_STATEMENT'
# asset_types = 'AN_ARRAY_OF_ASSET_TYPES_TO_SEARCH_FOR'
# page_size = 'SIZE_OF_EACH_RESULT_PAGE'
# page_token = 'TOKEN_PRODUCED_BY_THE_PRECEDING_CALL'
# order_by = 'FIELDS_TO_SORT_THE RESULTS'
asset_service = Google::Cloud::Asset.asset_service

response = asset_service.search_all_resources(
  scope:       scope,
  query:       query,
  asset_types: asset_types,
  page_size:   page_size,
  page_token:  page_token,
  order_by:    order_by
)
# Do things with the response
response.page.each do |resource|
  puts resource
end

其他搜尋範例

下列程式碼範例顯示 gcloud 和 REST 的特定搜尋查詢,協助您建構自己的搜尋。

專案中的所有資源

以下範例顯示如何搜尋 my-project 專案中的所有資源。

gcloud

gcloud asset search-all-resources \
    --scope=projects/my-project \
    --format="table(assetType.basename(), name.basename(), name.scope(projects).segment(0):label=PROJECT_ID, labels)"

REST

HTTP 方法和網址:

GET https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

指令範例

curl (Linux、macOS 或 Cloud Shell)

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

PowerShell (Windows)

$cred = gcloud auth print-access-token

$headers = @{ 
  "Authorization" = "Bearer $cred"
}


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

依說明分類的 Compute Engine 執行個體

以下範例說明如何在 my-project 專案中,搜尋名稱完全符合 instance-prod 的 Compute Engine 執行個體。

gcloud

gcloud asset search-all-resources \
    --scope=projects/my-project \
    --query="description=instance-prod" \
    --asset-types=compute.googleapis.com/Instance \
    --format="table(name, assetType, location)"

REST

HTTP 方法和網址:

POST https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

JSON 要求內文:

{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "description=instance-prod",
  "readMask": "name,assetType,location"
}

指令範例

curl (Linux、macOS 或 Cloud Shell)

curl -X POST \
     -H "X-HTTP-Method-Override: GET" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
            "assetTypes": "compute.googleapis.com/Instance",
            "pageSize": 1,
            "query": "description=instance-prod",
            "readMask": "name,assetType,location"
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

PowerShell (Windows)

$cred = gcloud auth print-access-token

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


$body = @"
{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "description=instance-prod",
  "readMask": "name,assetType,location"
}
"@

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

如要搜尋名稱中含有 instance-prod 的執行個體 (例如 instance-prod-1instance-prod-2),而非完全相符的執行個體,請將 =instance-prod 換成 :instance-prod

依標籤分類的 Compute Engine 執行個體

以下範例說明如何在 my-project 專案中,搜尋標籤名稱為 env 的 Compute Engine 執行個體。

gcloud

gcloud asset search-all-resources \
    --scope=projects/my-project \
    --query="labels.env:*" \
    --asset-types=compute.googleapis.com/Instance \
    --format="table(name, assetType, labels)"

REST

HTTP 方法和網址:

POST https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

JSON 要求內文:

{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "labels.env:*",
  "readMask": "name,assetType,labels"
}

指令範例

curl (Linux、macOS 或 Cloud Shell)

curl -X POST \
     -H "X-HTTP-Method-Override: GET" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
            "assetTypes": "compute.googleapis.com/Instance",
            "pageSize": 1,
            "query": "labels.env:*",
            "readMask": "name,assetType,labels"
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

PowerShell (Windows)

$cred = gcloud auth print-access-token

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


$body = @"
{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "labels.env:*",
  "readMask": "name,assetType,labels"
}
"@

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

依 TagKey 分組的 Compute Engine 執行個體

以下範例說明如何在 my-project 專案中搜尋直接附加 TagKey 的 Compute Engine 執行個體。namespacedName 包含 env

如要改用有效的 TagKey 搜尋,請將 tagKeys 替換成 effectiveTagKeys

gcloud

gcloud asset search-all-resources \
    --scope=projects/my-project \
    --query="tagKeys:env" \
    --asset-types=compute.googleapis.com/Instance \
    --format="table(name, assetType, tags)"

REST

HTTP 方法和網址:

POST https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

JSON 要求內文:

{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "tagKeys:env",
  "readMask": "name,assetType,tags"
}

指令範例

curl (Linux、macOS 或 Cloud Shell)

curl -X POST \
     -H "X-HTTP-Method-Override: GET" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
            "assetTypes": "compute.googleapis.com/Instance",
            "pageSize": 1,
            "query": "tagKeys:env",
            "readMask": "name,assetType,tags"
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

PowerShell (Windows)

$cred = gcloud auth print-access-token

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


$body = @"
{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "tagKeys:env",
  "readMask": "name,assetType,tags"
}
"@

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

依 TagValue 分組的 Compute Engine 執行個體

以下範例說明如何在 my-project 專案中搜尋直接附加標記的 Compute Engine 執行個體,其中 TagValuenamespacedName 包含 prodsea,且執行個體名稱不包含 instance1

如要改用有效 TagValues 搜尋,請將 tagValues 替換成 effectiveTagValues

gcloud

gcloud asset search-all-resources \
    --scope=projects/my-project \
    --query="tagValues:(prod OR sea) (NOT name:instance1)" \
    --asset-types=compute.googleapis.com/Instance \
    --format="table(name, assetType, tags)"

REST

HTTP 方法和網址:

POST https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

JSON 要求內文:

{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "tagValues:(prod OR sea) (NOT name:instance1)",
  "readMask": "name,assetType,tags"
}

指令範例

curl (Linux、macOS 或 Cloud Shell)

curl -X POST \
     -H "X-HTTP-Method-Override: GET" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
            "assetTypes": "compute.googleapis.com/Instance",
            "pageSize": 1,
            "query": "tagValues:(prod OR sea) (NOT name:instance1)",
            "readMask": "name,assetType,tags"
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

PowerShell (Windows)

$cred = gcloud auth print-access-token

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


$body = @"
{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "tagValues:(prod OR sea) (NOT name:instance1)",
  "readMask": "name,assetType,tags"
}
"@

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

在特定時間後建立的 Compute Engine 執行個體

下列範例說明如何搜尋 my-project 專案中在 2023 年 12 月 31 日後建立的 Compute Engine 執行個體。

如要進一步瞭解日期時間比較,請參閱「數值和時間戳記比較」。

gcloud

gcloud asset search-all-resources \
    --scope=projects/my-project \
    --query="createTime>2023-31-12" \
    --asset-types=compute.googleapis.com/Instance \
    --format="table(name, assetType, location)"

REST

HTTP 方法和網址:

POST https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

JSON 要求內文:

{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "createTime>2023-31-12",
  "readMask": "name,assetType,location"
}

指令範例

curl (Linux、macOS 或 Cloud Shell)

curl -X POST \
     -H "X-HTTP-Method-Override: GET" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
            "assetTypes": "compute.googleapis.com/Instance",
            "pageSize": 1,
            "query": "createTime>2023-31-12",
            "readMask": "name,assetType,location"
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

PowerShell (Windows)

$cred = gcloud auth print-access-token

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


$body = @"
{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "createTime>2023-31-12",
  "readMask": "name,assetType,location"
}
"@

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

位於美國的 Compute Engine 執行個體

以下範例顯示如何搜尋位於美國的 my-project 專案中的 Compute Engine 執行個體。

gcloud

gcloud asset search-all-resources \
    --scope=projects/my-project \
    --query="location:us-*" \
    --asset-types=compute.googleapis.com/Instance \
    --format="table(name, assetType, location)"

REST

HTTP 方法和網址:

POST https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

JSON 要求內文:

{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "location:us-*",
  "readMask": "name,assetType,location"
}

指令範例

curl (Linux、macOS 或 Cloud Shell)

curl -X POST \
     -H "X-HTTP-Method-Override: GET" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
            "assetTypes": "compute.googleapis.com/Instance",
            "pageSize": 1,
            "query": "location:us-*",
            "readMask": "name,assetType,location"
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

PowerShell (Windows)

$cred = gcloud auth print-access-token

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


$body = @"
{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "location:us-*",
  "readMask": "name,assetType,location"
}
"@

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

正在執行的 Compute Engine 執行個體

以下範例顯示如何搜尋在 my-project 專案中執行的 Compute Engine 執行個體。

gcloud

gcloud asset search-all-resources \
    --scope=projects/my-project \
    --query="state=RUNNING" \
    --asset-types=compute.googleapis.com/Instance \
    --read-mask="name,assetType,location,versionedResources" \
    --format="table(name, assetType, location, versionedResources)"

REST

HTTP 方法和網址:

POST https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

JSON 要求內文:

{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "state=RUNNING",
  "readMask": "name,assetType,location,versionedResources"
}

指令範例

curl (Linux、macOS 或 Cloud Shell)

curl -X POST \
     -H "X-HTTP-Method-Override: GET" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
            "assetTypes": "compute.googleapis.com/Instance",
            "pageSize": 1,
            "query": "state=RUNNING",
            "readMask": "name,assetType,location,versionedResources"
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

PowerShell (Windows)

$cred = gcloud auth print-access-token

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


$body = @"
{
  "assetTypes": "compute.googleapis.com/Instance",
  "pageSize": 1,
  "query": "state=RUNNING",
  "readMask": "name,assetType,location,versionedResources"
}
"@

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

IAM 拒絕政策

以下範例說明如何在 my-project 專案中搜尋 IAM 拒絕政策

gcloud

gcloud asset search-all-resources \
    --scope=projects/my-project \
    --asset-types=iam.googleapis.com/PolicyV2 \
    --query="name:denypolicies"

REST

HTTP 方法和網址:

POST https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

JSON 要求內文:

{
  "assetTypes": "iam.googleapis.com/PolicyV2",
  "pageSize": 1,
  "query": "name:denypolicies"
}

指令範例

curl (Linux、macOS 或 Cloud Shell)

curl -X POST \
     -H "X-HTTP-Method-Override: GET" \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     -d '{
            "assetTypes": "iam.googleapis.com/PolicyV2",
            "pageSize": 1,
            "query": "name:denypolicies"
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

PowerShell (Windows)

$cred = gcloud auth print-access-token

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


$body = @"
{
  "assetTypes": "iam.googleapis.com/PolicyV2",
  "pageSize": 1,
  "query": "name:denypolicies"
}
"@

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

如要搜尋未執行的 Compute Engine 執行個體,請將 state=RUNNING 替換為 NOT state:running

相關 Google Cloud 資源

如要查詢關係,您必須具備Security Command Center 進階或 Enterprise 級別,或 Gemini Cloud Assist

下列範例說明如何在 my-project 專案中搜尋相關資源,適用於支援的關係類型。舉例來說,您可以搜尋完整資源名稱中含有 instance-group執行個體群組,找出所有隸屬於這些群組的 Compute Engine 執行個體。

gcloud

gcloud asset search-all-resources \
    --scope=projects/my-project \
    --query="relationships:instance-group" \
    --format="table(name, assetType, relationships)"

REST

HTTP 方法和網址:

POST https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

JSON 要求內文:

{
  "pageSize": 1,
  "query": "relationships:instance-group",
  "readMask": "name,assetType,relationships"
}

指令範例

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 '{
            "pageSize": 1,
            "query": "relationships:instance-group",
            "readMask": "name,assetType,relationships"
          }' \
     https://cloudasset.googleapis.com/v1/projects/my-project:searchAllResources

PowerShell (Windows)

$cred = gcloud auth print-access-token

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


$body = @"
{
  "pageSize": 1,
  "query": "relationships:instance-group",
  "readMask": "name,assetType,relationships"
}
"@

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

您也可以指定要搜尋的關係類型。舉例來說,如要搜尋 INSTANCE_TO_INSTANCEGROUP 關係類型,請使用 relationships.INSTANCE_TO_INSTANCEGROUP 查詢。如要使用包含 instance-group 的完整資源名稱搜尋該關係類型,請使用查詢 relationships.INSTANCE_TO_INSTANCEGROUP:instance-group