创建和管理注释

本页面介绍了如何向区域密文添加注释,以及如何修改和查看这些注释。

概览

您可以使用注解来存储有关 Secret 的自定义元数据。例如,您可能需要使用 Secret 将要挂载到的路径来注释 Secret。注释有助于:

  • 根据密钥的用途、环境(开发、预演、生产)或敏感度级别对密钥进行分类。这样一来,您就可以更轻松地在 Secret Manager 中搜索、过滤和整理 Secret。

  • 用于指明 Secret 值的具体格式或结构,帮助工作负载正确解读该值。

  • 提供有关如何使用密钥的提示或有关处理密钥的任何特殊注意事项。

例如,如果您有一个包含数据库密码的 Secret,可以添加如下注释:

  • environment:production

  • purpose:database_access

  • owner:database_team

借助这些注释,您可以轻松确定相应 Secret 的用途、环境以及负责人员。此外,访问此 Secret 的工作负载可以使用注释来确认其使用的是生产环境的正确密码。

注释与标签不同。标签用于对资源进行排序、过滤和分组,而注释用于在 Secret 上存储任意非身份元数据。在标签中指定元数据时,字符和字符长度会受到限制。注解中的元数据可大可小、结构化或非结构化,还可以包含标签不允许使用的字符。

所需的角色

  • 在密文上添加注释和更新注释需要具有密文、项目、文件夹或组织的 Secret Manager 管理员角色 (roles/secretmanager.admin)。

  • 如需查看注释,需要具有密文、项目、文件夹或组织的 Secret Manager 查看者角色 (roles/secretmanager.viewer)。

不能对密文版本授予 Identity and Access Management (IAM) 角色。如需了解详情,请参阅使用 IAM 进行访问权限控制

向 Secret 添加注释

您可以在创建新 Secret 或更新现有 Secret 时添加注释。注解中的元数据以键值对的形式存储。如需添加注释,请使用以下方法之一:

控制台

  1. 在 Google Cloud 控制台中,前往 Secret Manager 页面。

    前往 Secret Manager

  2. Secret Manager 页面上,点击区域性 Secret 标签页,然后点击创建区域性 Secret

  3. 创建区域级 Secret 页面上,在名称字段中输入 Secret 的名称。

  4. 输入 Secret 的值(例如 abcd1234)。您还可以使用上传文件选项上传包含 Secret 值的文本文件。此操作会自动创建 Secret 版本。

  5. 区域列表中选择您要存储区域级密钥的位置。

  6. 前往注解部分,然后点击添加注解

  7. 输入键和对应的值。

  8. 点击创建密钥

gcloud

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

  • SECRET_ID:相应 Secret 的 ID
  • LOCATION:相应 Secret 的 Google Cloud 位置
  • KEY:注解键
  • VALUE:注解键的对应值

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets create SECRET_ID --location=LOCATION \
    --set-annotations=KEY1=VAL1,KEY2=VAL2

Windows (PowerShell)

gcloud secrets create SECRET_ID --location=LOCATION `
    --set-annotations=KEY1=VAL1,KEY2=VAL2

Windows (cmd.exe)

gcloud secrets create SECRET_ID --location=LOCATION ^
    --set-annotations=KEY1=VAL1,KEY2=VAL2

响应包含密钥和注释。

REST

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

  • LOCATION:相应 Secret 的 Google Cloud 位置
  • PROJECT_ID: Google Cloud 项目 ID
  • SECRET_ID:相应 Secret 的 ID
  • KEY:注解键
  • VALUE:注解键的对应值

HTTP 方法和网址:

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

请求 JSON 正文:

{'annotations': {'KEY1': 'VALUE1', 'KEY2': 'VALUE2' }}

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

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=annotations"

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=annotations" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
  "createTime": "2024-09-02T07:14:00.281541Z",
  "etag": "\"16211dcd99c386\"",
  "annotations": {
    "key1": "value1",
    "key2": "value2"
  }
}

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;
using System.Collections.Generic;

public class CreateRegionalSecretWithAnnotationsSample
{
    public Secret CreateRegionalSecretWithAnnotations(
      string projectId = "my-project",
      string locationId = "my-location",
      string secretId = "my-secret",
      string annotationKey = "my-annotation-key",
      string annotationValue = "my-annotation-value"
    )
    {
        // Create the Regional Secret Manager Client.
        SecretManagerServiceClient client = new SecretManagerServiceClientBuilder
        {
            Endpoint = $"secretmanager.{locationId}.rep.googleapis.com"
        }.Build();

        // Build the parent resource name.
        LocationName location = new LocationName(projectId, locationId);

        // Build the secret.
        Secret secret = new Secret
        {
            Annotations =
          {
              { annotationKey, annotationValue }
          },
        };

        // Call the API.
        Secret createdSecret = client.CreateSecret(location, secretId, secret);
        return createdSecret;
    }
}

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

// createRegionalSecretWithAnnotations creates a new secret with the given name and annotations.
func createRegionalSecretWithAnnotations(w io.Writer, projectId, locationId, secretId string) error {
	// parent := "projects/my-project"
	// id := "my-secret"

	annotationKey := "annotationkey"
	annotationValue := "annotationvalue"

	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 secretmanager client: %w", err)
	}
	defer client.Close()

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

	// Build the request.
	req := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: secretId,
		Secret: &secretmanagerpb.Secret{
			Annotations: map[string]string{
				annotationKey: annotationValue,
			},
		},
	}

	result, err := client.CreateSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create secret: %w", err)
	}
	fmt.Fprintf(w, "Created secret with annotations: %s\n", result.Name)
	return nil
}

Java

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

import com.google.cloud.secretmanager.v1.LocationName;
import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import java.io.IOException;

public class CreateRegionalSecretWithAnnotations {

  public static void createRegionalSecretWithAnnotations() throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // This is the id of the GCP project
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // This is the id of the secret to act on
    String secretId = "your-secret-id";
    // This is the key of the annotation to be added
    String annotationKey = "your-annotation-key";
    // This is the value of the annotation to be added
    String annotationValue = "your-annotation-value";
    createRegionalSecretWithAnnotations(
        projectId, locationId, secretId, annotationKey, annotationValue
    );
  }

  // Create a secret with annotations.
  public static Secret createRegionalSecretWithAnnotations(
        String projectId,
        String locationId,
        String secretId,
        String annotationKey,
        String annotationValue
  ) 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 parent name from the project.
      LocationName location = LocationName.of(projectId, locationId);

      // Build the secret to create with labels.
      Secret secret =
          Secret.newBuilder()
                .putAnnotations(annotationKey, annotationValue)
                .build();

      // Create the secret.
      Secret createdSecret = client.createSecret(location.toString(), secretId, secret);
      System.out.printf("Created secret %s\n", createdSecret.getName());
      return createdSecret;
    }
  }
}

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 = 'locationId';
// const secretId = 'my-secret';
// const annotationKey = 'exampleannotationkey';
// const annotationValue = 'exampleannotationvalue';

const parent = `projects/${projectId}/locations/${locationId}`;

// 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 createRegionalSecretWithAnnotations() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: {
      annotations: {
        [annotationKey]: annotationValue,
      },
    },
  });

  console.log(`Created secret ${secret.name}`);
}

createRegionalSecretWithAnnotations();

PHP

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

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

/**
 * @param string $projectId       Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $locationId      Your Google Cloud Location ID (e.g. 'us-central1')
 * @param string $secretId        Your secret ID (e.g. 'my-secret')
 * @param string $annotationKey   Your annotation key (e.g. 'annotation-key')
 * @param string $annotationValue Your annotation value (e.g. 'annotation-value')
 */
function create_regional_secret_with_annotations(string $projectId, string $locationId, string $secretId, string $annotationKey, string $annotationValue): void
{
    // Specify regional endpoint.
    $options = ['apiEndpoint' => "secretmanager.$locationId.rep.googleapis.com"];

    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient($options);

    // Build the resource name of the parent project.
    $parent = $client->locationName($projectId, $locationId);

    $secret = new Secret();

    // set the annotations.
    $annotations = [$annotationKey => $annotationValue];
    $secret->setAnnotations($annotations);

    // Build the request.
    $request = CreateSecretRequest::build($parent, $secretId, $secret);

    // Create the secret.
    $newSecret = $client->createSecret($request);

    // Print the new secret name.
    printf('Created secret %s with annotations', $newSecret->getName());
}

Python

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

import argparse
import typing

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


def create_regional_secret_with_annotations(
    project_id: str,
    location_id: str,
    secret_id: str,
    annotations: typing.Dict[str, str],
) -> secretmanager_v1.Secret:
    """
    Create a new secret with the given name. A secret is a logical wrapper
    around a collection of secret versions. Secret versions hold the actual
    secret material.
    """

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

    # Create the secret.
    response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
            "secret": {"annotations": annotations},
        }
    )

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

    return response

Ruby

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

require "google/cloud/secret_manager"

##
# Create a regional secret with annotations
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location_id [String] Your Google Cloud location (e.g. "us-west1")
# @param secret_id [String] Your secret name (e.g. "my-secret")
# @param annotation_key [String] Your annotation key (e.g. "my-annotation-key")
# @param annotation_value [String] Your annotation value (e.g "my-annotation-value")
#
def create_regional_secret_with_annotations project_id:, location_id:, secret_id:, annotation_key:, annotation_value:
  # Endpoint for the regional secret manager service.
  api_endpoint = "secretmanager.#{location_id}.rep.googleapis.com"

  # Create the Secret Manager client.
  client = Google::Cloud::SecretManager.secret_manager_service do |config|
    config.endpoint = api_endpoint
  end

  # Build the resource name of the parent project.
  parent = client.location_path project: project_id, location: location_id

  # Create the secret.
  secret = client.create_secret(
    parent:    parent,
    secret_id: secret_id,
    secret: {
      annotations: {
        annotation_key => annotation_value
      }
    }
  )

  # Print the new secret name.
  puts "Created regional secret with annotations: #{secret.name}"
end

如需向现有 Secret 添加注释,请参阅本文档的修改注释部分。

注释键具有以下要求:

  • 密钥必须是相应 Secret 的唯一密钥。您不能在同一 Secret 中重复使用某个密钥。

  • 键的长度必须介于 1 到 63 个字符之间。

  • 键所用的 UTF-8 编码上限为 128 个字节。

  • 密钥必须以字母数字字符开头和结尾。

  • 键可以在字母数字字符之间包含短划线、下划线和英文句点。

  • 注解键和值的总大小必须小于 16KiB。

修改注释

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

控制台

  1. 在 Google Cloud 控制台中,前往 Secret Manager 页面。

    前往 Secret Manager

  2. Secret Manager 页面上,点击区域性 Secret 标签页。

  3. 在列表中找到相应密钥,然后点击与该密钥关联的操作菜单。在操作菜单中,点击修改

  4. 修改 Secret 页面上,前往注释部分。您可以在此处更改现有注解的值、删除注解或添加新注解。

  5. 完成更改后,点击更新密钥

gcloud

修改现有注释

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

  • SECRET_ID:相应 Secret 的 ID
  • LOCATION:相应 Secret 的 Google Cloud 位置
  • KEY:注解键
  • VALUE:注解键的对应值

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets update SECRET_ID --location=LOCATION --update-annotations= KEY=VAL

Windows (PowerShell)

gcloud secrets update SECRET_ID --location=LOCATION --update-annotations= KEY=VAL

Windows (cmd.exe)

gcloud secrets update SECRET_ID --location=LOCATION --update-annotations= KEY=VAL

响应会修改 Secret 和注释。

移除特定注解

如需移除注释,请使用以下命令:

gcloud secrets update SECRET_ID --location=LOCATION --remove-annotations= KEY=VAL

清除所有注释

如需清除所有注释,请使用以下命令:

gcloud secrets update SECRET_ID --location=LOCATION --clear-annotations

REST

如需清除所有注释,请使用以下命令:

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

  • LOCATION:相应 Secret 的 Google Cloud 位置
  • PROJECT_ID: Google Cloud 项目 ID
  • SECRET_ID:相应 Secret 的 ID

HTTP 方法和网址:

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

请求 JSON 正文:

{'annotations': {}}

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

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=annotations"

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=annotations" | Select-Object -Expand Content

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

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

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;
using Google.Protobuf.Collections;
using Google.Protobuf.WellKnownTypes;


public class EditRegionalSecretAnnotationsSample
{
    public Secret EditRegionalSecretAnnotations(
      string projectId = "my-project",
      string locationId = "my-location",
      string secretId = "my-secret",
      string annotationKey = "my-annotation-key",
      string annotationValue = "my-annotation-value"
    )
    {
        // Create the Regional Secret Manager Client.
        SecretManagerServiceClient client = new SecretManagerServiceClientBuilder
        {
            Endpoint = $"secretmanager.{locationId}.rep.googleapis.com"
        }.Build();

        // Build the resource name.
        SecretName secretName = SecretName.FromProjectLocationSecret(projectId, locationId, secretId);

        // Get the exisitng secret.
        Secret existingSecret = client.GetSecret(secretName);

        // Add the mapping to the secret's annotations
        existingSecret.Annotations[annotationKey] = annotationValue;

        // Build the field mask.
        FieldMask fieldMask = FieldMask.FromString("annotations");

        // Call the update secret API.
        Secret updatedSecret = client.UpdateSecret(existingSecret, fieldMask);

        return updatedSecret;

    }
}

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

// editRegionalSecretAnnotations updates the annotations about an existing secret.
// If the annotation key exists, it updates the annotation, otherwise it creates a new one.
func editRegionalSecretAnnotation(w io.Writer, projectId, locationId, secretId string) error {
	// name := "projects/my-project/secrets/my-secret"

	annotationKey := "annotationkey"
	annotationValue := "updatedannotationvalue"

	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 secretmanager client: %w", err)
	}
	defer client.Close()

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

	// Build the request to get the secret.
	req := &secretmanagerpb.GetSecretRequest{
		Name: name,
	}

	result, err := client.GetSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get secret: %w", err)
	}

	annotations := result.Annotations

	annotations[annotationKey] = annotationValue

	// Build the request to update the secret.
	update_req := &secretmanagerpb.UpdateSecretRequest{
		Secret: &secretmanagerpb.Secret{
			Name:        name,
			Annotations: annotations,
		},
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"annotations"},
		},
	}

	// Call the API.
	update_result, err := client.UpdateSecret(ctx, update_req)
	if err != nil {
		return fmt.Errorf("failed to update secret: %w", err)
	}
	fmt.Fprintf(w, "Updated secret: %s\n", update_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;
import java.util.HashMap;
import java.util.Map;

public class EditRegionalSecretAnnotations {

  public static void editRegionalSecretAnnotations() throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // This is the id of the GCP project
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // This is the id of the secret to act on
    String secretId = "your-secret-id";
    // This is the key of the annotation to be added/updated
    String annotationKey = "your-annotation-key";
    // This is the value of the annotation to be added/updated
    String annotationValue = "your-annotation-value";
    editRegionalSecretAnnotations(
        projectId, locationId, secretId, annotationKey, annotationValue
    );
  }

  // Update an existing secret, by creating a new annotation or updating an existing annotation.
  public static Secret editRegionalSecretAnnotations(
      String projectId,
      String locationId,
      String secretId,
      String annotationKey,
      String annotationValue
  ) 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);

      // Get the existing secret
      Secret existingSecret = client.getSecret(secretName);

      Map<String, String> existingAnnotationsMap = 
          new HashMap<String, String>(existingSecret.getAnnotationsMap());

      // Add a new annotation key and value.
      existingAnnotationsMap.put(annotationKey, annotationValue);

      // Build the updated secret.
      Secret secret =
          Secret.newBuilder()
              .setName(secretName.toString())
              .putAllAnnotations(existingAnnotationsMap)
              .build();

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

      // Update the secret.
      Secret updatedSecret = client.updateSecret(secret, fieldMask);
      System.out.printf("Updated 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 = 'locationId';
// const secretId = 'my-secret';
// const annotationKey = 'updatedannotationkey';
// const annotationValue = 'updatedannotationvalue';

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 getSecret() {
  const [secret] = await client.getSecret({
    name: name,
  });

  return secret;
}

async function editRegionalSecretAnnotations() {
  const oldSecret = await getSecret();
  oldSecret.annotations[annotationKey] = annotationValue;
  const [secret] = await client.updateSecret({
    secret: {
      name: name,
      annotations: oldSecret.annotations,
    },
    updateMask: {
      paths: ['annotations'],
    },
  });

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

editRegionalSecretAnnotations();

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\GetSecretRequest;
use Google\Cloud\SecretManager\V1\UpdateSecretRequest;
use Google\Protobuf\FieldMask;

/**
 * @param string $projectId       Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $locationId      Your secret Location (e.g. 'us-central1')
 * @param string $secretId        Your secret ID (e.g. 'my-secret')
 * @param string $annotationKey   Your annotation key (e.g. 'annotation-key')
 * @param string $annotationValue Your annotation value (e.g. 'annotation-value')
 */
function edit_regional_secret_annotations(string $projectId, string $locationId, string $secretId, string $annotationKey, string $annotationValue): void
{
    // Specify regional endpoint.
    $options = ['apiEndpoint' => "secretmanager.$locationId.rep.googleapis.com"];

    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient($options);

    // Build the resource name of the secret.
    $name = $client->projectLocationSecretName($projectId, $locationId, $secretId);

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

    // get the secret.
    $getSecret = $client->getSecret($request);

    // get the annotations
    $annotations = $getSecret->getAnnotations();

    // update the annotation - need to create a new annotations map with the updated values
    $newAnnotations = [];
    foreach ($annotations as $key => $value) {
        $newAnnotations[$key] = $value;
    }
    $newAnnotations[$annotationKey] = $annotationValue;
    $getSecret->setAnnotations($newAnnotations);

    // set the field mask
    $fieldMask = new FieldMask();
    $fieldMask->setPaths(['annotations']);

    // build the secret
    $request = new UpdateSecretRequest();
    $request->setSecret($getSecret);
    $request->setUpdateMask($fieldMask);

    // update the secret
    $updateSecret = $client->updateSecret($request);

    // print the updated secret
    printf('Updated secret %s annotations' . PHP_EOL, $updateSecret->getName());
}

Python

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


import argparse
from typing import Dict

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


def edit_regional_secret_annotations(
    project_id: str, location_id: str, secret_id: str, new_annotations: Dict[str, str]
) -> secretmanager_v1.UpdateSecretRequest:
    """
    Create or update a annotation on 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.
    name = f"projects/{project_id}/locations/{location_id}/secrets/{secret_id}"

    # Get the secret.
    response = client.get_secret(request={"name": name})

    annotations = response.annotations

    # Update the annotations
    for annotation_key in new_annotations:
        annotations[annotation_key] = new_annotations[annotation_key]

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

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

    return response

Ruby

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

require "google/cloud/secret_manager"

##
# Edit a regional secret annotations
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location_id [String] Your Google Cloud location (e.g. "us-west11")
# @param secret_id [String] Your secret name (e.g. "my-secret")
# @param annotation_key [String] Your annotation key (e.g. "my-annotation-key")
# @param annotation_value [String] Your annotation value (e.g. "my-annotation-value")
#
def edit_regional_secret_annotations project_id:, location_id:, secret_id:, annotation_key:, annotation_value:
  # Endpoint for the regional secret manager service.
  api_endpoint = "secretmanager.#{location_id}.rep.googleapis.com"

  # Create the Secret Manager client.
  client = Google::Cloud::SecretManager.secret_manager_service do |config|
    config.endpoint = api_endpoint
  end

  # Build the resource name of the secret.
  name = client.secret_path project: project_id, location: location_id, secret: secret_id

  # Get the existing secret.
  existing_secret = client.get_secret name: name

  # Get the existing secret's annotations.
  existing_secret_annotations = existing_secret.annotations.to_h

  # Add a new annotation key and value.
  existing_secret_annotations[annotation_key] = annotation_value

  # Updates the secret.
  secret = client.update_secret(
    secret: {
      name: name,
      annotations: existing_secret_annotations
    },
    update_mask: {
      paths: ["annotations"]
    }
  )

  # Print the updated secret name and annotations.
  puts "Updated regional secret: #{secret.name}"
  puts "New updated annotations: #{secret.annotations}"
end

查看注释

如需查看附加到 Secret 的注释,请使用以下方法之一:

控制台

  1. 在 Google Cloud 控制台中,前往 Secret Manager 页面。

    前往 Secret Manager

  2. Secret Manager 页面上,点击区域性 Secret 标签页,然后点击要查看注释的 Secret。

  3. 系统会打开 Secret 详情页面。点击概览标签页。 您可以在此处查看附加到密文的注释。键列在左侧,值显示在右侧。

gcloud

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

  • SECRET_ID:相应 Secret 的 ID
  • LOCATION:相应 Secret 的 Google Cloud 位置

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets describe SECRET_ID --location=LOCATION

Windows (PowerShell)

gcloud secrets describe SECRET_ID --location=LOCATION

Windows (cmd.exe)

gcloud secrets describe SECRET_ID --location=LOCATION

响应包含密钥和注释。

REST

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

  • LOCATION:相应 Secret 的 Google Cloud 位置
  • PROJECT_ID: Google Cloud 项目 ID
  • SECRET_ID:相应 Secret 的 ID

HTTP 方法和网址:

GET https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID

请求 JSON 正文:

{}

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

curl

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

curl -X GET \
-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"

PowerShell

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

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

Invoke-WebRequest `
-Method GET `
-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" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
  "createTime": "2024-09-02T07:14:00.281541Z",
  "etag": "\"16211dcd99c386\"",
  "annotations": {
    "key1": "value1",
    "key2": "value2"
  }
}

C#

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


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;
using Google.Protobuf.Collections;
using Google.Protobuf.WellKnownTypes;
using System;


public class ViewRegionalSecretAnnotationsSample
{
    public Secret ViewRegionalSecretAnnotations(
      string projectId = "my-project",
      string locationId = "my-location",
      string secretId = "my-secret"
    )
    {
        // Create the Regional Secret Manager Client.
        SecretManagerServiceClient client = new SecretManagerServiceClientBuilder
        {
            Endpoint = $"secretmanager.{locationId}.rep.googleapis.com"
        }.Build();

        // Build the resource name.
        SecretName secretName = SecretName.FromProjectLocationSecret(projectId, locationId, secretId);

        // Get the secret.
        Secret secret = client.GetSecret(secretName);

        // Get the secret's annotations.
        MapField<string, string> secretAnnotations = secret.Annotations;

        // Print the annotations.
        foreach (var annotation in secret.Annotations)
        {
            Console.WriteLine($"Annotation Key: {annotation.Key}, Annotation Value: {annotation.Value}");
        }

        return secret;
    }
}

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

// viewRegionalSecretAnnotations gets annotations with the given secret.
func viewRegionalSecretAnnotations(w io.Writer, projectId, locationId, secretId string) error {
	// name := "projects/my-project/secrets/my-secret"

	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 secretmanager client: %w", err)
	}
	defer client.Close()

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

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

	result, err := client.GetSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get secret: %w", err)
	}

	annotations := result.Annotations
	fmt.Fprintf(w, "Found secret %s\n", result.Name)

	for key, value := range annotations {
		fmt.Fprintf(w, "Annotations key %s : Annotations Value %s", key, value)
	}
	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 java.io.IOException;
import java.util.Map;

public class ViewRegionalSecretAnnotations {

  public static void viewRegionalSecretAnnotations() throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // This is the id of the GCP project
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // This is the id of the secret whose annotations to view
    String secretId = "your-secret-id";
    viewRegionalSecretAnnotations(projectId, locationId, secretId);
  }

  // View the annotations of an existing secret.
  public static Map<String, String> viewRegionalSecretAnnotations(
      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);

      // Create the secret.
      Secret secret = client.getSecret(secretName);

      Map<String, String> annotations = secret.getAnnotationsMap();

      System.out.printf("Secret %s \n", secret.getName());

      for (Map.Entry<String, String> annotation : annotations.entrySet()) {
        System.out.printf("Annotation key : %s, Annotation Value : %s\n", 
            annotation.getKey(), annotation.getValue());
      }

      return secret.getAnnotationsMap();
    }
  }
}

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 = 'locationId';
// 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 viewRegionalSecretAnnotations() {
  const [secret] = await client.getSecret({
    name: name,
  });

  for (const key in secret.annotations) {
    console.log(`${key} : ${secret.annotations[key]}`);
  }
}

viewRegionalSecretAnnotations();

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\GetSecretRequest;

/**
 * @param string $projectId  Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $locationId Your secret Location (e.g. 'us-central1')
 * @param string $secretId   Your secret ID (e.g. 'my-secret')
 */
function view_regional_secret_annotations(string $projectId, string $locationId, string $secretId): void
{
    // Specify regional endpoint.
    $options = ['apiEndpoint' => "secretmanager.$locationId.rep.googleapis.com"];

    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient($options);

    // Build the resource name of the secret.
    $name = $client->projectLocationSecretName($projectId, $locationId, $secretId);

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

    // get the secret.
    $getSecret = $client->getSecret($request);

    // get the annotations
    $annotations = $getSecret->getAnnotations();

    // print the secret name
    printf('Get secret %s with annotation:' . PHP_EOL, $getSecret->getName());
    // we can even loop over all the annotations
    foreach ($annotations as $key => $val) {
        printf("\t$key: $val" . PHP_EOL);
    }
}

Python

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

import argparse

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


def view_regional_secret_annotations(
    project_id: str, location_id: str, secret_id: str
) -> None:
    """
    List all secret annotations in the given 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.
    name = f"projects/{project_id}/locations/{location_id}/secrets/{secret_id}"

    response = client.get_secret(request={"name": name})

    print(f"Got secret {response.name} with annotations :")
    for key in response.annotations:
        print(f"{key} : {response.annotations[key]}")

Ruby

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

require "google/cloud/secret_manager"

##
# Edit a regional secret annotations
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location_id [String] Your Google Cloud location (e.g. "us-west11")
# @param secret_id [String] Your secret name (e.g. "my-secret")
#
def view_regional_secret_annotations project_id:, location_id:, secret_id:
  # Endpoint for the regional secret manager service.
  api_endpoint = "secretmanager.#{location_id}.rep.googleapis.com"

  # Create the Secret Manager client.
  client = Google::Cloud::SecretManager.secret_manager_service do |config|
    config.endpoint = api_endpoint
  end

  # Build the resource name of the secret.
  name = client.secret_path project: project_id, location: location_id, secret: secret_id

  # Get the existing secret.
  existing_secret = client.get_secret name: name

  # Get the existing secret's annotations.
  existing_secret_annotations = existing_secret.annotations.to_h

  # Print the secret name and the annotations.
  puts "Regional Secret: #{existing_secret.name}"
  existing_secret_annotations.each do |key, value|
    puts "Annotation Key: #{key}, Annotation Value: #{value}"
  end
end

后续步骤