刪除區域性密鑰版本

本頁說明如何銷毀密碼版本。在「已刪除」狀態下,系統會捨棄密鑰版本內容。而且這項操作無法復原。版本刪除後,您就無法存取密鑰資料,也無法將版本還原至其他狀態。

銷毀密鑰版本前,請先停用該版本,並觀察應用程式的行為。 如果發生非預期的問題,可以重新啟用密鑰版本。

停用或刪除密鑰或密鑰版本後,系統需要一段時間才能完成變更。如有需要,您可以撤銷密鑰存取權。身分與存取權管理權限會在幾秒內完成變更。

必要的角色

如要取得刪除密鑰版本所需的權限,請要求管理員為您授予密鑰的 Secret Manager 密鑰版本管理員 (roles/secretmanager.secretVersionManager) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

您或許還可透過自訂角色或其他預先定義的角色取得必要權限。

刪除密鑰版本

如要銷毀密鑰版本,請選擇下列其中一種做法:

控制台

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

    前往 Secret Manager

  2. 在「Secret Manager」頁面中,按一下「Regional secrets」分頁標籤,然後點選密鑰來存取其版本。

  3. 在密鑰詳細資料頁面的「版本」分頁中,選取要銷毀的密鑰版本。

  4. 按一下「動作」,然後按一下「銷毀」

  5. 在隨即顯示的確認對話方塊中,輸入密鑰 ID 進行確認,然後按一下「銷毀所選版本」

gcloud

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

  • VERSION_ID:密鑰版本的資源名稱
  • SECRET_ID:密鑰的 ID
  • 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:專案 ID Google Cloud
  • SECRET_ID:密鑰的 ID
  • VERSION_ID:密鑰版本的 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 Manager 管理員可以還原密鑰版本。

後續步驟