修改区域级密钥

本页介绍了如何修改密文的元数据。您可以更新密钥的许多属性,例如加密类型、轮替政策、失效日期、标签和事件通知。您还可以为 Secret 版本添加注解和设置别名。您无法修改密钥的名称或值。如需向 Secret 添加新值,您必须创建新的 Secret 版本

所需的角色

如需获得更新密文元数据所需的权限,请让您的管理员向您授予密文或项目的 Secret Manager Admin (roles/secretmanager.admin) IAM 角色。 如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

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

修改 Secret

如需修改 Secret,请使用以下方法之一:

控制台

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

    前往 Secret Manager

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

  3. 如需修改 Secret,请使用以下方法之一:

    • 在列表中找到相应 Secret,然后点击与该 Secret 关联的 Actions 菜单。在操作菜单中,点击修改

    • 点击 Secret 名称可前往 Secret 详情页面。在密钥详情页面上,点击 修改密钥

  4. 修改 Secret 页面上,根据需要更新 Secret 的属性,然后点击更新 Secret

gcloud

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

  • SECRET_ID:Secret 的 ID 或 Secret 的完全限定标识符
  • LOCATION:密钥的 Google Cloud 位置
  • KEY:标签键
  • VALUE:标签的相应值

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets update SECRET_ID --location=LOCATION \
    --update-labels=KEY=VALUE

Windows (PowerShell)

gcloud secrets update SECRET_ID --location=LOCATION `
    --update-labels=KEY=VALUE

Windows (cmd.exe)

gcloud secrets update SECRET_ID --location=LOCATION ^
    --update-labels=KEY=VALUE

响应会返回更新后的 Secret。

REST

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

  • LOCATION:密钥的 Google Cloud 位置
  • PROJECT_ID:Google Cloud 项目 ID
  • SECRET_ID:Secret 的 ID 或 Secret 的完全限定标识符
  • KEY:标签键
  • VALUE:标签的相应值

HTTP 方法和网址:

PATCH https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID?updateMask=labels

请求 JSON 正文:

{'labels': {'KEY': 'VAL'}}

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

curl

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

curl -X PATCH \
-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?updateMask=labels"

PowerShell

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

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

Invoke-WebRequest `
-Method PATCH `
-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?updateMask=labels" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
  "createTime": "2024-09-02T07:14:00.281541Z",
  "labels": {
    "key": "value"
  },
  "etag": "\"16211dc7d040b1\""
}

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"
	"google.golang.org/genproto/protobuf/field_mask"
)

// updateSecret updates the metadata about an existing secret.
func UpdateRegionalSecret(w io.Writer, projectId, locationId, secretId string) error {
	// name := "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()

	name := fmt.Sprintf("projects/%s/locations/%s/secrets/%s", projectId, locationId, secretId)

	// Build the request.
	req := &secretmanagerpb.UpdateSecretRequest{
		Secret: &secretmanagerpb.Secret{
			Name: name,
			Labels: map[string]string{
				"secretmanager": "rocks",
			},
		},
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"labels"},
		},
	}

	// Call the API.
	result, err := client.UpdateSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to update regional secret: %w", err)
	}
	fmt.Fprintf(w, "Updated regional secret: %s\n", result.Name)
	return nil
}

Java

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

import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretName;
import com.google.protobuf.FieldMask;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;

public class UpdateRegionalSecret {

  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 to update.
    String secretId = "your-secret-id";
    updateRegionalSecret(projectId, locationId, secretId);
  }

  // Update an existing secret.
  public static Secret updateRegionalSecret(
      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 name.
      SecretName secretName = 
          SecretName.ofProjectLocationSecretName(projectId, locationId, secretId);

      // Build the updated secret.
      Secret secret =
          Secret.newBuilder()
              .setName(secretName.toString())
              .putLabels("secretmanager", "rocks")
              .build();

      // Build the field mask.
      FieldMask fieldMask = FieldMaskUtil.fromString("labels");

      // Update the secret.
      Secret updatedSecret = client.updateSecret(secret, fieldMask);
      System.out.printf("Updated regional secret %s\n", updatedSecret.getName());

      return updatedSecret;
    }
  }
}

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 name = `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 updateRegionalSecret() {
  const [secret] = await client.updateSecret({
    secret: {
      name: name,
      labels: {
        secretmanager: 'rocks',
      },
    },
    updateMask: {
      paths: ['labels'],
    },
  });

  console.info(`Updated secret ${secret.name}`);
}

updateRegionalSecret();

Python

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

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


def update_regional_secret(
    project_id: str, location_id: str, secret_id: str
) -> secretmanager_v1.UpdateSecretRequest:
    """
    Updates the metadata about an existing secret.
    """

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

    # Update the secret.
    secret = {"name": name, "labels": {"secretmanager": "rocks"}}
    update_mask = {"paths": ["labels"]}
    response = client.update_secret(
        request={"secret": secret, "update_mask": update_mask}
    )

    # Print the new secret name.
    print(f"Updated secret: {response.name}")

    return response

修改多个 Secret 的权限和标签

您可以使用 Google Cloud 控制台修改多个 Secret 的权限和标签。

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

    前往 Secret Manager

  2. Secret Manager 页面上,点击区域性 Secret 标签页,然后选择要修改权限和标签的 Secret。

  3. 如果信息面板已关闭,请点击显示信息面板以显示信息。

  4. 为所有 Secret 配置的权限和标签会显示在信息面板的对应标签页下。前往各个标签页,然后根据需要更新值。

  5. 完成后,点击保存

后续步骤