列出区域 Secret 版本并查看版本详情

本页介绍了如何检索一段时间内创建的某个 Secret 的所有不同版本的列表,以及如何查看特定 Secret 版本的元数据。

所需的角色

如需获得列出密文版本和查看版本详情所需的权限,请让管理员向您授予密文、项目、文件夹或组织的 Secret Manager Viewer (roles/secretmanager.viewer) IAM 角色。 如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

您也可以通过自定义角色或其他预定义角色来获取所需的权限。

列出密钥的版本

列出 Secret 的版本有以下用途:

  • 您可以查看某个密钥随时间的变化情况、更改者以及更改时间。这是必填字段 进行审核和合规

  • 如果密钥意外更新或遭到入侵,您可以回滚到之前已知良好的版本。

  • 您可以识别不再使用的版本,可以将其安全删除。

  • 您可以进行问题排查。例如,如果应用出现问题,您可以 检查之前版本的密钥,看看更改是否是导致密钥更改的原因。

如需列出密钥的所有版本,请使用以下方法之一:

控制台

  1. 转到 Google Cloud 控制台中的 Secret Manager 页面。

    前往 Secret Manager

  2. Secret Manager 页面上,点击 Regional secrets(区域级 Secret)标签页。

  3. 点击某个密钥以访问其版本。

    属于该 Secret 的版本会显示在版本表中。

gcloud

在使用下面的命令数据之前,请先进行以下替换:

  • SECRET_ID:密钥的 ID 或密钥的完全限定标识符。
  • LOCATION:密钥的 Google Cloud 位置

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets versions list SECRET_ID --location=LOCATION

Windows (PowerShell)

gcloud secrets versions list SECRET_ID --location=LOCATION

Windows (cmd.exe)

gcloud secrets versions list SECRET_ID --location=LOCATION

响应包含该密钥。

REST

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION:Secret 的 Google Cloud 位置
  • PROJECT_ID:Google Cloud 项目 ID
  • SECRET_ID:密钥的 ID 或密钥的完全限定标识符

HTTP 方法和网址:

GET https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions

请求 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/SECRET_ID/versions"

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

您应该收到类似以下内容的 JSON 响应:

{
  "versions": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/VERSION_ID",
      "createTime": "2024-09-04T06:41:57.859674Z",
      "state": "ENABLED",
      "etag": "\"1621457b3c1459\""
    }
  ],
  "totalSize": 1
}

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

// listSecretVersions lists all secret versions in the given secret and their
// metadata.
func ListRegionalSecretVersions(w io.Writer, projectId, locationId, secretId string) error {
	// parent := "projects/my-project/locations/my-location/secrets/my-secret"

	// 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/secrets/%s", projectId, locationId, secretId)
	// Build the request.
	req := &secretmanagerpb.ListSecretVersionsRequest{
		Parent: parent,
	}

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

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

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

	return nil
}

Java

要运行此代码,请先设置 Java 开发环境安装 Secret Manager Java SDK。 在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient.ListSecretVersionsPagedResponse;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretName;
import java.io.IOException;

public class ListRegionalSecretVersions {

  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";
    // Resource ID of the secret.
    String secretId = "your-secret-id";
    listRegionalSecretVersions(projectId, locationId, secretId);
  }

  // List all secret versions for a secret.
  public static ListSecretVersionsPagedResponse listRegionalSecretVersions(
      String projectId, String locationId, String secretId)
      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.
      SecretName secretName = 
          SecretName.ofProjectLocationSecretName(projectId, locationId, secretId);

      // Get all versions.
      ListSecretVersionsPagedResponse pagedResponse = client.listSecretVersions(secretName);

      // List all versions and their state.
      pagedResponse
          .iterateAll()
          .forEach(
              version -> {
                System.out.printf("Regional secret version %s, %s\n", 
                    version.getName(), version.getState());
              });

      return pagedResponse;
    }
  }
}

Node.js

要运行此代码,请先设置 Node.js 开发环境安装 Secret Manager Node.js SDK。 在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const locationId = 'my-location';
// const secretId = 'my-secret';

const parent = `projects/${projectId}/locations/${locationId}/secrets/${secretId}`;

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Adding the endpoint to call the regional secret manager sever
const options = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;

// Instantiates a client
const client = new SecretManagerServiceClient(options);

async function listRegionalSecretVersions() {
  const [versions] = await client.listSecretVersions({
    parent: parent,
  });

  versions.forEach(version => {
    console.log(`${version.name}: ${version.state}`);
  });
}

listRegionalSecretVersions();

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_secret_versions(
    project_id: str, location_id: str, secret_id: str
) -> None:
    """
    Lists all secret versions in the given secret and their metadata.
    """

    # 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 secret.
    parent = f"projects/{project_id}/locations/{location_id}/secrets/{secret_id}"

    # List all secret versions.
    for version in client.list_secret_versions(request={"parent": parent}):
        print(f"Found secret version: {version.name}")

获取有关密文版本的详细信息

通过此过程,您可以查看 Secret 版本的元数据,例如版本 ID、创建日期和时间、加密详情和状态。查看 Secret 版本的元数据意味着访问有关 Secret 版本的信息,但不包括实际 Secret 值本身。如需查看 Secret 值,请参阅访问地区性 Secret 版本

如需查看 Secret 版本的元数据,请使用以下方法之一:

控制台

  1. 转到 Google Cloud 控制台中的 Secret Manager 页面。

    前往 Secret Manager

  2. Secret Manager 页面上,点击 Regional secrets(区域级 Secret)标签页。

  3. 点击某个密钥以访问其版本。

    属于该密钥的版本显示在版本表格中。 对于每个版本,版本 ID 及其元数据也会在表格中显示。

gcloud

在使用下面的命令数据之前,请先进行以下替换:

  • VERSION_ID:Secret 版本的 ID
  • SECRET_ID:密钥的 ID 或密钥的完全限定标识符。
  • LOCATION:Secret 的 Google Cloud 位置

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets versions describe VERSION_ID --secret=SECRET_ID --location=LOCATION

Windows (PowerShell)

gcloud secrets versions describe VERSION_ID --secret=SECRET_ID --location=LOCATION

Windows (cmd.exe)

gcloud secrets versions describe VERSION_ID --secret=SECRET_ID --location=LOCATION

响应包含密钥。

REST

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION:密钥的 Google Cloud 位置
  • PROJECT_ID:Google Cloud 项目 ID
  • SECRET_ID:密钥的 ID 或密钥的完全限定标识符
  • VERSION_ID:Secret 版本的 ID

HTTP 方法和网址:

GET https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/VERSION_ID

请求 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/SECRET_ID/versions/VERSION_ID"

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/SECRET_ID/versions/VERSION_ID" | Select-Object -Expand Content

您应该收到类似以下内容的 JSON 响应:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/VERSION_ID",
  "createTime": "2024-09-04T06:41:57.859674Z",
  "state": "ENABLED",
  "etag": "\"1621457b3c1459\""
}

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/option"
)

// getSecretVersion gets information about the given secret version. It does not
// include the payload data.
func GetRegionalSecretVersion(w io.Writer, projectId, locationId, secretId, versionId string) error {
	// name := "projects/my-project/locations/my-location/secrets/my-secret/versions/5"
	// name := "projects/my-project/locations/my-location/secrets/my-secret/versions/latest"

	// 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()

	name := fmt.Sprintf("projects/%s/locations/%s/secrets/%s/versions/%s", projectId, locationId, secretId, versionId)
	// Build the request.
	req := &secretmanagerpb.GetSecretVersionRequest{
		Name: name,
	}

	// Call the API.
	result, err := client.GetSecretVersion(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get regional secret version: %w", err)
	}

	fmt.Fprintf(w, "Found regional secret version %s with state %s\n",
		result.Name, result.State)
	return nil
}

Java

要运行此代码,请先设置 Java 开发环境安装 Secret Manager Java SDK。 在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.cloud.secretmanager.v1.SecretVersionName;
import java.io.IOException;

public class GetRegionalSecretVersion {

  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";
    // Resource ID of the secret.
    String secretId = "your-secret-id";
    // Version of the Secret ID you want to retrieve.
    String versionId = "your-version-id";
    getRegionalSecretVersion(projectId, locationId, secretId, versionId);
  }

  // Get an existing secret version.
  public static SecretVersion getRegionalSecretVersion(
      String projectId, String locationId, String secretId, String versionId)
      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 name from the version.
      SecretVersionName secretVersionName = 
          SecretVersionName.ofProjectLocationSecretSecretVersionName(
          projectId, locationId, secretId, versionId);

      // Create the secret.
      SecretVersion version = client.getSecretVersion(secretVersionName);
      System.out.printf("Regional secret version %s, state %s\n", 
          version.getName(), version.getState());

      return version;
    }
  }
}

Node.js

如需运行此代码,请先设置 Node.js 开发环境安装 Secret Manager Node.js SDK。 在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */

// const projectId = 'my-project';
// const locationId = 'my-location';
// const secretId = 'my-secret';
// const versionId = 'my-version';

const name = `projects/${projectId}/locations/${locationId}/secrets/${secretId}/versions/${version}`;

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Adding the endpoint to call the regional secret manager sever
const options = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;

// Instantiates a client
const client = new SecretManagerServiceClient(options);

async function getRegionalSecretVersion() {
  const [version] = await client.getSecretVersion({
    name: name,
  });

  console.info(`Found secret ${version.name} with state ${version.state}`);
}

getRegionalSecretVersion();

Python

如需运行此代码,请先设置 Python 开发环境安装 Secret Manager Python SDK。在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

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


def get_regional_secret_version(
    project_id: str,
    location_id: str,
    secret_id: str,
    version_id: str,
) -> secretmanager_v1.GetSecretVersionRequest:
    """
    Gets information about the given secret version. It does not include the
    payload data.
    """

    # 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 secret version.
    name = f"projects/{project_id}/locations/{location_id}/secrets/{secret_id}/versions/{version_id}"

    # Get the secret version.
    response = client.get_secret_version(request={"name": name})

    # Print information about the secret version.
    state = response.state.name
    print(f"Got secret version {response.name} with state {state}")

    return response

后续步骤