销毁区域性 Secret 版本

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

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

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

所需的角色

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

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

销毁密文版本

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

控制台

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

    前往 Secret Manager

  2. Secret Manager 页面上,点击区域性 Secret 标签页,然后点击某个 Secret 以访问其版本。

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

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

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

gcloud

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

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

执行以下命令:

Linux、macOS 或 Cloud Shell

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

Windows (PowerShell)

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

Windows (cmd.exe)

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

REST

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

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

HTTP 方法和网址:

POST https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/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.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/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.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/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\""
}

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"
	"google.golang.org/api/option"
)

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

	// 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.DestroySecretVersionRequest{
		Name: name,
	}

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

public class DestroyRegionalSecretVersion {

  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 destroy.
    String versionId = "your-version-id";
    destroyRegionalSecretVersion(projectId, locationId, secretId, versionId);
  }

  // Destroy an existing secret version.
  public static SecretVersion destroyRegionalSecretVersion(
      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);

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

      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 name = 'projects/my-project/secrets/my-secret/versions/5';
//
// const projectId = 'my-project';
// const locationId = 'my-location';
// const secretId = 'my-secret';
// const version = '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 destroySecretVersion() {
  const [version] = await client.destroySecretVersion({
    name: name,
  });

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

destroySecretVersion();

Python

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

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


def destroy_regional_secret_version(
    project_id: str,
    location_id: str,
    secret_id: str,
    version_id: str,
) -> secretmanager_v1.DestroySecretVersionRequest:
    """
    Destroys the given secret version, making the payload irrecoverable. Other
    secrets versions are unaffected.
    """

    # 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}"

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

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

    return response

推迟销毁密文版本

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

后续步骤