启用已停用的区域性 Secret 版本

本页面介绍了如何启用已停用的 Secret 版本,以便能够访问 版本及其包含的 Secret 数据。

所需的角色

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

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

启用已停用的 Secret 版本

如需启用已停用的 Secret 版本,请使用以下方法之一:

控制台

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

    前往 Secret Manager

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

  3. 在密文详情页面的版本标签页中,选择要启用的已停用的密文版本。

  4. 点击 操作,然后点击启用

  5. 在显示的确认对话框中,点击启用所选版本

gcloud

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

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

执行以下命令:

Linux、macOS 或 Cloud Shell

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

Windows (PowerShell)

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

Windows (cmd.exe)

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

REST

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

  • LOCATION:Secret 的 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:enable

请求 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:enable"

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:enable" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/VERSION_ID",
  "createTime": "2024-09-02T07:16:34.566706Z",
  "state": "ENABLED",
  "etag": "\"16214547e7583e\""
}

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

// enableSecretVersion enables the given secret version, enabling it to be
// accessed after previously being disabled. Other secrets versions are
// unaffected.
func EnableRegionalSecretVersion(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.EnableSecretVersionRequest{
		Name: name,
	}

	// Call the API.
	if _, err := client.EnableSecretVersion(ctx, req); err != nil {
		return fmt.Errorf("failed to enable 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 EnableRegionalSecretVersion {

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

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

      // Enable the secret version.
      SecretVersion version = client.enableSecretVersion(secretVersionName);
      System.out.printf("Enabled 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 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 enableRegionalSecretVersion() {
  const [version] = await client.enableSecretVersion({
    name: name,
  });

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

enableRegionalSecretVersion();

Python

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

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


def enable_regional_secret_version(
    project_id: str,
    location_id: str,
    secret_id: str,
    version_id: str,
) -> secretmanager_v1.EnableSecretVersionRequest:
    """
    Enables the given secret version, enabling it to be accessed after
    previously being disabled. 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}"

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

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

    return response

后续步骤