为密文添加标签

本页概述了标签,介绍了如何向 Secret 添加标签,以及如何查看和更新附加到 Secret 的标签。

什么是标签?

标签是一种键值对,可分配给 Google Cloud Secret Manager 中的密钥。它们可以帮助您按照所需的粒度大规模组织这些资源并管理费用。您可以将标签附加到各项资源,然后根据其标签对资源进行过滤。标签的相关信息会转发到结算系统,以便您按标签细分结算费用。使用内置的结算报告,您可以按资源标签对费用进行过滤和分组。您还可以使用标签查询结算数据导出

标签要求

应用于资源的标签必须符合以下要求:

  • 每个资源最多可以有 64 个标签。
  • 每个标签都必须采用键值对形式。
  • 键至少包含 1 个字符,最多包含 63 个字符,且不能为空。值可以为空,且最多包含 63 个字符。
  • 键和值只能包含小写字母、数字字符、下划线和短划线。所有字符必须使用 UTF-8 编码,允许使用国际字符。 键必须以小写字母或国际字符开头。
  • 标签的键部分在单个资源内必须是唯一的。不过,您可以将同一个键用于多个资源。

这些限制适用于每个标签的键和值,以及带有标签的各个 Google Cloud 资源。您可以对一个项目的所有资源应用任意数量的标签。

标签的常见用途

以下是标签的一些常见使用场景:

  • 团队或成本中心标签:根据团队或成本中心添加标签,以区分不同团队(例如 team:researchteam:analytics)所拥有的 Secret Manager Secret。您可以在进行成本核算或预算时使用此类标签。

  • 组件标签:例如 component:rediscomponent:frontendcomponent:ingestcomponent:dashboard

  • 环境或阶段标签:例如 environment:productionenvironment:test

  • 状态标签:例如 state:activestate:readytodeletestate:archive

  • 所有权标签:用于标识负责运营的团队,例如:team:shopping-cart

我们不建议创建大量唯一标签,例如为每个 API 调用的时间戳或个别值创建标签。这种方法的问题在于,当值经常变化或键导致目录杂乱时,很难有效地过滤和报告资源。

标签和标记

标签可用作资源可查询的注释,但不能用于设置政策的条件。通过对政策进行精细控制,标记提供了一种有条件地允许或拒绝政策的方法,具体取决于资源是否具有特定的标记。如需了解详情,请参阅标记概览

创建带有标签的 Secret

如需在创建 Secret 时添加标签,请按以下步骤操作:

控制台

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

    前往 Secret Manager

  2. Secret Manager 页面上,点击创建 Secret

  3. 创建 Secret 页面的名称字段中,输入 Secret 的名称。

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

  5. 前往标签部分,然后点击添加标签

  6. 输入键及其对应的值以创建标签。

  7. 点击创建密钥

gcloud

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

  • SECRET_ID:Secret 的 ID。
  • KEY:标签的键。
  • VALUE:标签的值。

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets create SECRET_ID --labels=KEY=VALUE

Windows (PowerShell)

gcloud secrets create SECRET_ID --labels=KEY=VALUE

Windows (cmd.exe)

gcloud secrets create SECRET_ID --labels=KEY=VALUE

REST

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

  • PROJECT_ID: Google Cloud 项目 ID。
  • SECRET_ID:Secret 的 ID。
  • KEY:标签的键。
  • VALUE:标签的值。

HTTP 方法和网址:

POST https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID?update_mask=labels

请求 JSON 正文:

{
  "labels": {
    "KEY": "VALUE"
  }
}

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

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.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID?update_mask=labels"

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.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID?update_mask=labels" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/secrets/SECRET_ID",
  "createTime": "2024-03-25T08:24:13.153705Z",
   "labels": {
    "key": "value"
  },
  "etag": "\"161477e6071da9\""
}

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 CreateSecretWithLabelsSample
{
    public Secret CreateSecretWithLabels(
      string projectId = "my-project", string secretId = "my-secret", string labelKey = "my-label-key", string labelValue = "my-label-value")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the parent resource name.
        ProjectName projectName = new ProjectName(projectId);

        // Build the secret.
        Secret secret = new Secret
        {
            Replication = new Replication
            {
                Automatic = new Replication.Types.Automatic(),
            },
            Labels =
            {
              { labelKey, labelValue }
            },
        };

        // Call the API.
        Secret createdSecret = client.CreateSecret(projectName, 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"
)

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

	labelKey := "labelkey"
	labelValue := "labelvalue"

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %w", err)
	}
	defer client.Close()

	// Build the request.
	req := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: id,
		Secret: &secretmanagerpb.Secret{
			Replication: &secretmanagerpb.Replication{
				Replication: &secretmanagerpb.Replication_Automatic_{
					Automatic: &secretmanagerpb.Replication_Automatic{},
				},
			},
			Labels: map[string]string{
				labelKey: labelValue,
			},
		},
	}

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

Java

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

import com.google.cloud.secretmanager.v1.ProjectName;
import com.google.cloud.secretmanager.v1.Replication;
import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import java.io.IOException;

public class CreateSecretWithLabels {

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

    // This is the id of the GCP project
    String projectId = "your-project-id";
    // This is the id of the secret to act on
    String secretId = "your-secret-id";
    // This is the key of the label to be added
    String labelKey = "your-label-key";
    // This is the value of the label to be added
    String labelValue = "your-label-value";
    createSecretWithLabels(projectId, secretId, labelKey, labelValue);
  }

  // Create a secret with labels.
  public static Secret createSecretWithLabels(
       String projectId, String secretId, String labelKey, String labelValue) throws IOException {
    // Initialize 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()) {

      // Build the name.
      ProjectName projectName = ProjectName.of(projectId);

      // Build the secret to create with labels.
      Secret secret =
          Secret.newBuilder()
                  .setReplication(
                  Replication.newBuilder()
                      .setAutomatic(Replication.Automatic.newBuilder().build())
                      .build())
                      .putLabels(labelKey, labelValue)
              .build();

      // Create the secret.
      Secret createdSecret = client.createSecret(projectName, 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 parent = 'projects/my-project';
// const secretId = 'my-secret';
// const labelKey = 'secretmanager';
// const labelValue = 'rocks';

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

async function createSecretWithLabels() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: {
      replication: {
        automatic: {},
      },
      labels: {
        [labelKey]: labelValue,
      },
    },
  });

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

createSecretWithLabels();

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\Replication;
use Google\Cloud\SecretManager\V1\Replication\Automatic;
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 $secretId   Your secret ID (e.g. 'my-secret')
 * @param string $labelKey   Your label key (e.g. 'label-key')
 * @param string $labelValue Your label value (e.g. 'label-value')
 */
function create_secret_with_labels(string $projectId, string $secretId, string $labelKey, string $labelValue): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

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

    $secret = new Secret([
        'replication' => new Replication([
            'automatic' => new Automatic(),
        ]),
    ]);

    // set the labels.
    $labels = [$labelKey => $labelValue];
    $secret->setLabels($labels);

    // 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 labels', $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


def create_secret_with_labels(
    project_id: str,
    secret_id: str,
    labels: typing.Dict[str, str],
    ttl: typing.Optional[str] = None,
) -> secretmanager.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.
    """

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent project.
    parent = f"projects/{project_id}"

    # Create the secret.
    response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
            "secret": {"replication": {"automatic": {}}, "ttl": ttl, "labels": labels},
        }
    )

    # 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 secret with labels.
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param secret_id [String] Your secret name (e.g. "my-secret")
# @param label_key [String] Your label key (e.g. "my-label-key")
# @param label_value [String] Your label value (e.g. "my-label-value")
#
def create_secret_with_labels project_id:, secret_id:, label_key:, label_value:
  # Create a Secret Manager client.
  client = Google::Cloud::SecretManager.secret_manager_service

  # Build the resource name of the parent project.
  parent = client.project_path project: project_id

  # Create the secret.
  secret = client.create_secret(
    parent:    parent,
    secret_id: secret_id,
    secret:    {
      replication: {
        automatic: {}
      },
      labels: {
        label_key => label_value
      }
    }
  )

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

查看 Secret 上的标签

如需查看分配的标签,请按以下步骤操作:

控制台

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

    前往 Secret Manager

  2. Secret Manager 页面上,选择要查看其标签的 Secret。

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

  4. 在面板中,点击标签标签页。系统会显示添加到相应 Secret 的所有标签。

gcloud

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

  • SECRET_ID:Secret 的 ID。

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets describe SECRET_ID

Windows (PowerShell)

gcloud secrets describe SECRET_ID

Windows (cmd.exe)

gcloud secrets describe SECRET_ID

REST

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

  • PROJECT_ID: Google Cloud 项目 ID。
  • SECRET_ID:Secret 的 ID。

HTTP 方法和网址:

GET https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=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.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=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.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/secrets/SECRET_ID",
  "createTime": "2024-03-25T08:24:13.153705Z",
   "labels": {
    "key": "value"
  },
  "etag": "\"161477e6071da9\""
}

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 ViewSecretLabelsSample
{
    public Secret ViewSecretLabels(
      string projectId = "my-project", string secretId = "my-secret")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

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

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

        // Get the secret's labels.
        MapField<string, string> secretLabels = secret.Labels;

        // Print the labels.
        foreach (var label in secret.Labels)
        {
            Console.WriteLine($"Annotation Key: {label.Key}, Annotation Value: {label.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"
)

// getSecret gets information about the given secret. This only returns metadata
// about the secret container, not any secret material.
func viewSecretLabels(w io.Writer, name string) error {
	// name := "projects/my-project/secrets/my-secret"

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %w", err)
	}
	defer client.Close()

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

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

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

	for key, value := range labels {
		fmt.Fprintf(w, "Label key %s : Label 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.SecretName;
import java.io.IOException;
import java.util.Map;

public class ViewSecretLabels {

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

    // This is the id of the GCP project
    String projectId = "your-project-id";
    // This is the id of the secret whose labels to view
    String secretId = "your-secret-id";
    viewSecretLabels(projectId, secretId);
  }

  // View the labels of an existing secret.
  public static Map<String, String> viewSecretLabels(
      String projectId,
      String secretId
  ) throws IOException {
    // Initialize 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()) {
      // Build the name.
      SecretName secretName = SecretName.of(projectId, secretId);

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

      Map<String, String> labels = secret.getLabels();

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

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

      return secret.getLabels();
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const parent = 'projects/my-project/secrets/my-secret';

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

async function getSecretLabels() {
  const [secret] = await client.getSecret({
    name: name,
  });

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

getSecretLabels();

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 $secretId  Your secret ID (e.g. 'my-secret')
 */
function view_secret_labels(string $projectId, string $secretId): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

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

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

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

    // get the secret labels
    $labels = $getSecret->getLabels();

    // print the secret name
    printf('Get secret %s with labels:' . PHP_EOL, $getSecret->getName());
    // we can even loop over all the labels
    foreach ($labels 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


def view_secret_labels(project_id: str, secret_id: str) -> None:
    """
    List all secret labels in the given secret.
    """
    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent secret.
    name = client.secret_path(project_id, secret_id)

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

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

Ruby

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

require "google/cloud/secret_manager"

##
# View labels of a secret.
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param secret_id [String] Your secret name (e.g. "my-secret")
#
def view_secret_labels project_id:, secret_id:
  # Create a Secret Manager client.
  client = Google::Cloud::SecretManager.secret_manager_service

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

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

  # Get the existing secret's labels.
  existing_secret_labels = existing_secret.labels.to_h

  # Print the secret name and the labels.
  puts "Secret: #{existing_secret.name}"
  existing_secret_labels.each do |key, value|
    puts "Label Key: #{key}, Label Value: #{value}"
  end
end

更新标签

如需更新标签,请按以下步骤操作:

控制台

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

    前往 Secret Manager

  2. 选择要修改的密钥。

  3. 打开信息面板,然后点击标签标签页。

  4. 更新标签的现有值,然后点击保存

    您还可以删除现有标签或添加新标签。如需修改标签的键,请添加具有相同键名称的新标签,然后删除旧标签。

gcloud

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

  • SECRET_ID:Secret 的 ID。
  • KEY:标签的键。
  • VALUE:标签的值。

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets update SECRET_ID --update-labels=KEY=VALUE

Windows (PowerShell)

gcloud secrets update SECRET_ID --update-labels=KEY=VALUE

Windows (cmd.exe)

gcloud secrets update SECRET_ID --update-labels=KEY=VALUE

REST

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

  • PROJECT_ID: Google Cloud 项目 ID。
  • SECRET_ID:Secret 的 ID。
  • KEY:标签的键。
  • VALUE:标签的值。

HTTP 方法和网址:

PATCH https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID?update_mask=labels

请求 JSON 正文:

{
  "labels": {
    "KEY": "VALUE"
  }
}

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

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.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID?update_mask=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.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID?update_mask=labels" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/secrets/SECRET_ID",
  "createTime": "2024-03-25T08:24:13.153705Z",
   "labels": {
    "key": "value"
  },
  "etag": "\"161477e6071da9\""
}

C#

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


using Google.Protobuf.WellKnownTypes;
using Google.Cloud.SecretManager.V1;

public class UpdateSecretSample
{
    public Secret UpdateSecret(string projectId = "my-project", string secretId = "my-secret")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the secret with updated fields.
        Secret secret = new Secret
        {
            SecretName = new SecretName(projectId, secretId),
        };
        secret.Labels["secretmanager"] = "rocks";

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

        // Call the API.
        Secret updatedSecret = client.UpdateSecret(secret, 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/genproto/protobuf/field_mask"
)

// createUpdateSecretLabel updates the labels about an existing secret.
// If the label key exists, it updates the label, otherwise it creates a new one.
func createUpdateSecretLabel(w io.Writer, name string) error {
	// name := "projects/my-project/secrets/my-secret"

	labelKey := "labelkey"
	labelValue := "updatedlabelvalue"

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %w", err)
	}
	defer client.Close()

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

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

	labels := result.Labels

	labels[labelKey] = labelValue

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

	// 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.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 CreateUpdateSecretLabel {

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

    // This is the id of the GCP project
    String projectId = "your-project-id";
    // This is the id of the secret to act on
    String secretId = "your-secret-id";
    // This is the key of the label to be added/updated
    String labelKey = "your-label-key";
    // This is the value of the label to be added/updated
    String labelValue = "your-label-value";
    createUpdateSecretLabel(projectId, secretId, labelKey, labelValue);
  }

  // Update an existing secret, by creating a new label or updating an existing label.
  public static Secret createUpdateSecretLabel(
       String projectId, String secretId, String labelKey, String labelValue) throws IOException {
    // Initialize 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()) {
      // Build the name.
      SecretName secretName = SecretName.of(projectId, secretId);

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

      Map<String, String> existingLabelsMap = 
                      new HashMap<String, String>(existingSecret.getLabels());

      // Add a new label key and value.
      existingLabelsMap.put(labelKey, labelValue);

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

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

      // 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 name = 'projects/my-project/secrets/my-secret';
// const labelKey = 'gcp';
// const labelValue = 'rocks';

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

async function getSecret() {
  const [secret] = await client.getSecret({
    name: name,
  });

  return secret;
}

async function createUpdateSecretLabel() {
  const oldSecret = await getSecret();
  oldSecret.labels[labelKey] = labelValue;
  const [secret] = await client.updateSecret({
    secret: {
      name: name,
      labels: oldSecret.labels,
    },
    updateMask: {
      paths: ['labels'],
    },
  });

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

createUpdateSecretLabel();

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 $secretId   Your secret ID (e.g. 'my-secret')
 * @param string $labelKey   Your label key (e.g. 'label-key')
 * @param string $labelValue Your label value (e.g. 'label-value')
 */
function edit_secret_labels(string $projectId, string $secretId, string $labelKey, string $labelValue): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

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

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

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

    // get the secret labels
    $labels = $getSecret->getLabels();

    // update the label - need to create a new labels map with the updated values
    $newLabels = [];
    foreach ($labels as $key => $value) {
        $newLabels[$key] = $value;
    }
    $newLabels[$labelKey] = $labelValue;
    $getSecret->setLabels($newLabels);

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

    // 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 labels' . 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


def create_update_secret_label(
    project_id: str, secret_id: str, new_labels: Dict[str, str]
) -> secretmanager.UpdateSecretRequest:
    """
    Create or update a label on an existing secret.
    """

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the secret.
    name = client.secret_path(project_id, secret_id)

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

    labels = response.labels

    # Update the labels
    for label_key in new_labels:
        labels[label_key] = new_labels[label_key]

    # Update the secret.
    secret = {"name": name, "labels": labels}
    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

Ruby

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

require "google/cloud/secret_manager"

##
# Update a secret's labels
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param secret_id [String] Your secret name (e.g. "my-secret")
#
def update_secret project_id:, secret_id:
  # Create a Secret Manager client.
  client = Google::Cloud::SecretManager.secret_manager_service

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

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

  # Print the updated secret name and the new label value.
  puts "Updated secret: #{secret.name}"
  puts "New label: #{secret.labels['secretmanager']}"
end

移除标签

如需移除标签,请按以下步骤操作:

控制台

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

    前往 Secret Manager

  2. 选择要修改的密钥。

  3. 打开信息面板,然后点击标签标签页。

  4. 点击删除,移除您不再需要的标签。

  5. 点击保存

gcloud

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

  • SECRET_ID:Secret 的 ID。

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets update SECRET_ID --clear-labels

Windows (PowerShell)

gcloud secrets update SECRET_ID --clear-labels

Windows (cmd.exe)

gcloud secrets update SECRET_ID --clear-labels

REST

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

  • PROJECT_ID: Google Cloud 项目 ID。
  • SECRET_ID:Secret 的 ID。

HTTP 方法和网址:

PATCH https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID?update_mask=labels

请求 JSON 正文:

{
  "labels": {}
}

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

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.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID?update_mask=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.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID?update_mask=labels" | Select-Object -Expand Content

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

{
  "name": "projects/PROJECT_ID/secrets/SECRET_ID",
  "createTime": "2024-03-25T08:24:13.153705Z",
  "etag": "\"161477e6071da9\"",
  "labels": {}
}

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/genproto/protobuf/field_mask"
)

// deleteSecret updates the metadata about an existing secret and remove an existing label.
func deleteSecretLabel(w io.Writer, name string) error {
	// name := "projects/my-project/secrets/my-secret"

	labelKey := "labelkey"

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %w", err)
	}
	defer client.Close()

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

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

	labels := result.Labels

	delete(labels, labelKey)

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

	// Call the API.
	updateResult, err := client.UpdateSecret(ctx, updateReq)
	if err != nil {
		return fmt.Errorf("failed to update secret: %w", err)
	}
	fmt.Fprintf(w, "Updated secret: %s\n", updateResult.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.SecretName;
import com.google.protobuf.FieldMask;
import com.google.protobuf.FieldMaskOrBuilder;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class DeleteSecretLabel {

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

    // This is the id of the GCP project
    String projectId = "your-project-id";
    // This is the id of the secret to act on
    String secretId = "your-secret-id";
    // This is the key of the label to be deleted
    String labelKey = "your-label-key";
    deleteSecretLabel(projectId, secretId, labelKey);
  }

  // Update an existing secret, by deleting a label.
  public static Secret deleteSecretLabel(
                     String projectId, String secretId, String labelKey) throws IOException {
    // Initialize 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()) {
      // Build the name.
      SecretName secretName = SecretName.of(projectId, secretId);

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

      Map<String, String> existingLabelsMap = 
              new HashMap<String, String>(existingSecret.getLabels());
      existingLabelsMap.remove(labelKey);

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

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

      // 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 name = 'projects/my-project/secrets/my-secret';
// const labelKey = 'secretmanager';

// Imports the Secret Manager library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

async function getSecret() {
  const [secret] = await client.getSecret({
    name: name,
  });

  return secret;
}

async function deleteSecretLabel() {
  const oldSecret = await getSecret();
  delete oldSecret.labels[labelKey];
  const [secret] = await client.updateSecret({
    secret: {
      name: name,
      labels: oldSecret.labels,
    },
    updateMask: {
      paths: ['labels'],
    },
  });

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

deleteSecretLabel();

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

/**
 * @param string $projectId Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $secretId  Your secret ID (e.g. 'my-secret')
 * @param string $labelKey  Your label key (e.g. 'label-key')
 */
function delete_secret_label(string $projectId, string $secretId, string $labelKey): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

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

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

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

    // get the secret labels
    $labels = $getSecret->getLabels();

    // delete the label
    unset($labels[$labelKey]);

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

    // build the secret
    $secret = new Secret();
    $secret->setLabels($labels);
    $secret->setName($getSecret->getName());

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

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

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

Python

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

import argparse

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


def delete_secret_label(
    project_id: str, secret_id: str, label_key: str
) -> secretmanager.UpdateSecretRequest:
    """
    Delete a label on an existing secret.
    """

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the secret.
    name = client.secret_path(project_id, secret_id)

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

    labels = response.labels

    # Delete the label
    labels.pop(label_key, None)

    # Update the secret.
    secret = {"name": name, "labels": labels}
    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

后续步骤