销毁密文版本

本页介绍了如何销毁密钥版本。在已销毁状态下,密文版本的内容将被舍弃。销毁 Secret 版本是一项永久性操作。版本销毁后,您将无法访问密文数据或将版本恢复为其他状态。

在销毁密文版本之前,请先尝试停用它,然后观察应用的行为。如果您遇到意外问题,可以重新启用密文版本。

停用或销毁密文或密文版本时,更改需要过一段时间才能应用于系统中。如有必要,您可以撤消对密文的访问权限。IAM 权限的更改会在数秒内达成一致。

所需的角色

如需获得销毁密钥版本所需的权限,请让您的管理员为您授予密钥的 Secret Manager Secret Version Manager (roles/secretmanager.secretVersionManager) IAM 角色。 如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

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

销毁密文版本

如需销毁 Secret 版本,请使用以下方法之一:

控制台

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

    前往 Secret Manager

  2. Secret Manager 页面上,点击某个 Secret 以访问其版本。

  3. 在密文详情页面的版本标签页中,选择要销毁的密文版本。

  4. 点击 操作,然后点击销毁

  5. 在随即显示的确认对话框中,输入要确认的密钥 ID,然后点击销毁所选版本

gcloud

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

  • VERSION_ID:Secret 版本的资源名称
  • SECRET_ID:Secret 的 ID 或 Secret 的完全限定标识符

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets versions destroy VERSION_ID --secret=SECRET_ID

Windows (PowerShell)

gcloud secrets versions destroy VERSION_ID --secret=SECRET_ID

Windows (cmd.exe)

gcloud secrets versions destroy VERSION_ID --secret=SECRET_ID

REST

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

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

HTTP 方法和网址:

POST https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID/versions/VERSION_ID:destroy

请求 JSON 正文:

{}

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID/versions/VERSION_ID:destroy"

PowerShell

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID/versions/VERSION_ID:destroy" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/VERSION_ID",
  "createTime": "2024-09-02T07:16:34.566706Z",
  "destroyTime": "2024-09-04T06:29:01.893743728Z",
  "state": "DESTROYED",
  "etag": "\"1621454a37ce7f\""
}

C#

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


using Google.Cloud.SecretManager.V1;

public class DestroySecretVersionSample
{
    public SecretVersion DestroySecretVersion(
      string projectId = "my-project", string secretId = "my-secret", string secretVersionId = "123")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretVersionName secretVersionName = new SecretVersionName(projectId, secretId, secretVersionId);

        // Call the API.
        SecretVersion version = client.DestroySecretVersion(secretVersionName);
        return version;
    }
}

Go

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

import (
	"context"
	"fmt"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
)

// destroySecretVersion destroys the given secret version, making the payload
// irrecoverable. Other secrets versions are unaffected.
func destroySecretVersion(name string) error {
	// name := "projects/my-project/secrets/my-secret/versions/5"

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &secretmanagerpb.DestroySecretVersionRequest{
		Name: name,
	}

	// Call the API.
	if _, err := client.DestroySecretVersion(ctx, req); err != nil {
		return fmt.Errorf("failed to destroy secret version: %w", err)
	}
	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.SecretVersion;
import com.google.cloud.secretmanager.v1.SecretVersionName;
import java.io.IOException;

public class DestroySecretVersion {

  public static void destroySecretVersion() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String secretId = "your-secret-id";
    String versionId = "your-version-id";
    destroySecretVersion(projectId, secretId, versionId);
  }

  // Destroy an existing secret version.
  public static void destroySecretVersion(String projectId, String secretId, String versionId)
      throws IOException {
    // 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 (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
      // Build the name from the version.
      SecretVersionName secretVersionName = SecretVersionName.of(projectId, secretId, versionId);

      // Destroy the secret version.
      SecretVersion version = client.destroySecretVersion(secretVersionName);
      System.out.printf("Destroyed secret version %s\n", version.getName());
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const name = 'projects/my-project/secrets/my-secret/versions/5';

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

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

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

  console.info(`Destroyed ${version.name}`);
}

destroySecretVersion();

PHP

如需运行此代码,请先了解如何在 Google Cloud 上使用 PHP安装 Secret Manager PHP SDK。 在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient;
use Google\Cloud\SecretManager\V1\DestroySecretVersionRequest;

/**
 * @param string $projectId Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $secretId  Your secret ID (e.g. 'my-secret')
 * @param string $versionId Your version ID (e.g. 'latest' or '5');
 */
function destroy_secret_version(string $projectId, string $secretId, string $versionId): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

    // Build the resource name of the secret version.
    $name = $client->secretVersionName($projectId, $secretId, $versionId);

    // Build the request.
    $request = DestroySecretVersionRequest::build($name);

    // Destroy the secret version.
    $response = $client->destroySecretVersion($request);

    // Print a success message.
    printf('Destroyed secret version: %s', $response->getName());
}

Python

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

def destroy_secret_version(
    project_id: str, secret_id: str, version_id: str
) -> secretmanager.DestroySecretVersionRequest:
    """
    Destroy the given secret version, making the payload irrecoverable. Other
    secrets versions are unaffected.
    """

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

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the secret version
    name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}"

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

    print(f"Destroyed secret version: {response.name}")

Ruby

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

# project_id = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# secret_id  = "YOUR-SECRET-ID"             # (e.g. "my-secret")
# version_id = "YOUR-VERSION"               # (e.g. "5" or "latest")

# Require the Secret Manager client library.
require "google/cloud/secret_manager"

# Create a Secret Manager client.
client = Google::Cloud::SecretManager.secret_manager_service

# Build the resource name of the secret version.
name = client.secret_version_path(
  project:        project_id,
  secret:         secret_id,
  secret_version: version_id
)

# Destroy the secret version.
response = client.destroy_secret_version name: name

# Print a success message.
puts "Destroyed secret version: #{response.name}"

推迟销毁密钥版本

Secret Manager 管理员可以通过在 Secret 上配置推迟销毁密钥版本功能来设置推迟销毁密钥版本。如果启用此功能,系统在收到请求后不会立即销毁密钥版本。相反,系统会停用密钥版本,并安排在日后销毁该版本。在此期间,Secret Manager 管理员可以恢复密钥版本。

后续步骤