篩選區域性密鑰和密鑰版本

本頁說明如何在 Secret Manager 中篩選密鑰和密鑰版本。在有大量密鑰的環境中,篩選功能可協助您快速找出特定密鑰或版本,不必手動捲動整個清單。您可以根據標籤、建立日期或密鑰名稱中的特定模式等條件進行篩選,集中管理特定密鑰群組。

在 Secret Manager 中,您可以使用 Google Cloud 控制台的「篩選」選項,或在 API 呼叫中指定篩選條件,篩選密鑰和密鑰版本。在 Google Cloud CLI 中,您可以在列出密鑰時加入 filter 字串,篩選密鑰和密鑰版本。

篩選密鑰

如要篩選密鑰,請使用下列其中一種方法:

控制台

  1. 前往 Google Cloud 控制台的「Secret Manager」頁面。

    前往 Secret Manager

  2. 在「Secret Manager」頁面中,按一下「區域性密鑰」分頁標籤。

  3. 在「區域密鑰」表格中,按一下「篩選器」欄位。

  4. 選擇篩選器屬性和相應值,例如 Location:asia-east1

    系統會根據輸入的值自動篩選表格。結果會依名稱遞增排序。

gcloud

使用下方的任何指令資料之前,請先替換以下項目:

  • LOCATION:密鑰的 Google Cloud 位置
  • FILTER:篩選器字串,例如 name:asecret OR name:bsecret。 gcloud CLI 也支援規則運算式,例如 name ~ "secret_ab.*"

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud secrets list --location=LOCATION --filter="FILTER"

Windows (PowerShell)

gcloud secrets list --location=LOCATION --filter="FILTER"

Windows (cmd.exe)

gcloud secrets list --location=LOCATION --filter="FILTER"

REST

使用任何要求資料之前,請先替換以下項目:

  • LOCATION:密鑰的 Google Cloud 位置
  • PROJECT_ID:專案 ID Google Cloud
  • FILTER:篩選器字串。篩選條件會指定為 filter 查詢字串參數,且必須經過網址編碼。舉例來說,篩選條件 name:asecret OR name:bsecret 經過網址編碼後會變成 name%3Aasecret+OR+name%3Absecret。API 不支援規則運算式。

HTTP 方法和網址:

GET https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?filter=FILTER

JSON 要求主體:

{}

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?filter=FILTER"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?filter=FILTER" | Select-Object -Expand Content

您應該會收到如下的 JSON 回應:

{
  "secrets": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
      "createTime": "2024-09-02T07:14:00.281541Z",
      "etag": "\"16211dd90b37e7\""
    }
  ]
}

Go

如要執行這段程式碼,請先設定 Go 開發環境,並安裝 Secret Manager Go SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
	"google.golang.org/api/iterator"
	"google.golang.org/api/option"
)

// listSecretsWithFilter lists all filter-matching secrets in the given project.
func ListRegionalSecretsWithFilter(w io.Writer, projectId, locationId string, filter string) error {
	// parent := "projects/my-project/locations/my-location"
	// Follow https://cloud.google.com/secret-manager/docs/filtering
	// for filter syntax and examples.
	// filter := "name:name-substring"

	// Create the client.
	ctx := context.Background()
	//Endpoint to send the request to regional server
	endpoint := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", locationId)
	client, err := secretmanager.NewClient(ctx, option.WithEndpoint(endpoint))

	if err != nil {
		return fmt.Errorf("failed to create regional secretmanager client: %w", err)
	}
	defer client.Close()

	parent := fmt.Sprintf("projects/%s/locations/%s", projectId, locationId)
	// Build the request.
	req := &secretmanagerpb.ListSecretsRequest{
		Parent: parent,
		Filter: filter,
	}

	// Call the API.
	it := client.ListSecrets(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}

		if err != nil {
			return fmt.Errorf("failed to list regional secrets: %w", err)
		}

		fmt.Fprintf(w, "Found regional secret %s\n", resp.Name)
	}

	return nil
}

Java

如要執行這段程式碼,請先設定 Java 開發環境,並安裝 Secret Manager Java SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

import com.google.cloud.secretmanager.v1.ListSecretsRequest;
import com.google.cloud.secretmanager.v1.LocationName;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient.ListSecretsPage;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient.ListSecretsPagedResponse;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import java.io.IOException;

public class ListRegionalSecretsWithFilter {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Your GCP project ID.
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // Filter to be applied. 
    // See https://cloud.google.com/secret-manager/docs/filtering
    // for filter syntax and examples.
    String filter = "name:your-secret-substring AND expire_time<2022-01-01T00:00:00Z";
    listRegionalSecretsWithFilter(projectId, locationId, filter);
  }

  // List all secrets for a project
  public static ListSecretsPage listRegionalSecretsWithFilter(
      String projectId, String locationId, String filter) throws IOException {

    // Endpoint to call the regional secret manager sever
    String apiEndpoint = String.format("secretmanager.%s.rep.googleapis.com:443", locationId);
    SecretManagerServiceSettings secretManagerServiceSettings =
        SecretManagerServiceSettings.newBuilder().setEndpoint(apiEndpoint).build();

    // Initialize the client that will be used to send requests. This client only needs to be
    // created once, and can be reused for multiple requests.
    try (SecretManagerServiceClient client = 
        SecretManagerServiceClient.create(secretManagerServiceSettings)) {
      // Build the parent name.
      LocationName parent = LocationName.of(projectId, locationId);

      // Get filtered secrets.
      ListSecretsRequest request =
          ListSecretsRequest.newBuilder()
              .setParent(parent.toString())
              .setFilter(filter)
              .build();

      ListSecretsPagedResponse pagedResponse = client.listSecrets(request);

      // List all secrets.
      pagedResponse
          .iterateAll()
          .forEach(
              secret -> {
                System.out.printf("Regional secret %s\n", secret.getName());
              });

      return pagedResponse.getPage();
    }
  }
}

Python

如要執行這段程式碼,請先設定 Python 開發環境,然後安裝 Secret Manager Python SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

# Import the Secret Manager client library.
from google.cloud import secretmanager_v1


def list_regional_secrets_with_filter(
    project_id: str, location_id: str, filter_str: str
) -> None:
    """
    Lists all regional secrets in the given project.
    """

    # Endpoint to call the regional secret manager sever.
    api_endpoint = f"secretmanager.{location_id}.rep.googleapis.com"

    # Create the Secret Manager client.
    client = secretmanager_v1.SecretManagerServiceClient(
        client_options={"api_endpoint": api_endpoint},
    )

    # Build the resource name of the parent project.
    parent = f"projects/{project_id}/locations/{location_id}"

    # List all secrets.
    for secret in client.list_secrets(request={"parent": parent, "filter": filter_str}):
        print(f"Found secret: {secret.name}")

篩選密鑰版本

如要篩選密鑰版本,請按照下列步驟操作:

  • 在 Google Cloud 控制台中選取密鑰,存取密鑰版本,然後使用「版本」表格中的「篩選器」選項。

  • 如果您使用 Google Cloud CLI 或 Secret Manager API,請在列出密鑰版本時加入 filter 字串。

篩選器範例

用途 篩選器
名稱包含 mysecret 子字串的密鑰 name:mysecret
具有特定標籤的密鑰 labels.environment=production
在日期/時間範圍內建立的密鑰 create_time<2021-01-01T06:00:00Z AND create_time>2021-01-01T12:00:00Z
具有自動複製功能的密鑰 replication.automatic:*
採用使用者管理複製功能,但未儲存在任一指定區域的密鑰 replication.user_managed.replicas.location:* AND NOT replication.user_managed.replicas.location:(us-central1 OR us-east1)
使用 CMEK 金鑰加密的密鑰 replication.user_managed.replicas.customerManagedEncryption:*
以特定 CMEK 金鑰加密的密鑰 replication.user_managed.replicas.customerManagedEncryption.kmsKeyName=projects/p/locations/us-central1/keyRings/kr/cryptoKeys/my-cmek-key
沒有輪替週期的密鑰 NOT rotation.next_rotation_time:*
輪替週期超過 30 天的密鑰 rotation.rotation_period>259200s
已設定到期日的密鑰 expire_time:*
在特定日期前到期的密鑰 expire_time<2021-07-31
已啟用或停用的版本 state:(ENABLED OR DISABLED)
已刪除的版本 (刪除日期) state:DESTROYED AND destroy_time>2021-01-01

篩選器語法

篩選器語法包含在篩選物件的一或多個欄位上執行的運算式。

您可以使用下列運算式運算子。

運算子 說明
= 等於。
> 大於。
< 小於。
>= 大於或等於。
<= 小於或等於。
!=
-
NOT
不等式。下列項目等效:
name!="topsecret"
-name="topsecret"
NOT name="topsecret"
:

包含。這是不區分大小寫的子字串比對。

例如,name:"myapp" 會篩選在資源名稱中包含 myapp (不區分大小寫) 的資源。

AND

邏輯 AND。

空格等於 AND,因此以下會產生相同結果:
name:"myapp" AND name:"secret1"
name:"myapp" name:"secret1"

OR 邏輯 OR。
*

萬用字元。

可做為獨立項目使用,其中 field:* 表示已設定 field

與 Cloud Search API 一致,除非使用括號明確定義不同的順序,否則系統會先評估 OR 作業,再評估 AND 作業。

篩選 time 值時,請將時間編碼為 RFC 3399 格式的字串,例如 2020-10-15T01:30:15Z

存取子欄位時,請使用 dot 語法。舉例來說,Secret 資源可能包含 labels 欄位,其值為鍵/值 map。如果使用 color 標籤,您可以按照下列方式,在子欄位 labels.color 中篩選 Secret 結果:

labels.color=red

如要只列出已設定 color 標籤的密鑰,請使用萬用字元:

labels.color:*

加引號的字串會解譯為單一值,而非一串值。

篩選欄位

您可以篩選 SecretSecretVersion 物件的任何欄位。

List 方法 可篩選欄位的連結
projects.secrets.list 密鑰欄位
projects.secrets.versions.list SecretVersion 欄位

結果總數

如果在清單要求中設定 filter,回應就不會指出結果總數 (回應中的 total_size=0)。

後續步驟