创建和管理区域级密钥的标记

本指南介绍了如何创建和管理区域级 Secret 的标记。您可以使用标记对相关的 Secret Manager 密文进行分组,并根据这些资源的标记存储有关它们的元数据。

关于标记

标记是一种可附加到Google Cloud中的资源的键值对。您可以使用标记,根据资源是否有特定标记,有条件地允许或拒绝政策。例如,您可以根据资源是否具有特定标记,有条件地授予 Identity and Access Management (IAM) 角色。如需了解详情,请参阅标记概览

通过创建可将值关联到 Google Cloud 资源的标记绑定资源,系统会将标记附加到资源。

所需权限

如需获得管理标记所需的权限,请让您的管理员为您授予以下 IAM 角色:

  • 针对标记附加到的资源的 Tag Viewer (roles/resourcemanager.tagViewer)
  • 在组织级层查看和管理标记:针对组织的 Organization Viewer (roles/resourcemanager.organizationViewer)
  • 创建、更新和删除标记定义:针对您要为其创建、更新或删除标记的资源的 Tag Administrator (roles/resourcemanager.tagAdmin)
  • 在资源中附加和移除标记:针对标记值以及您要为其附加或移除标记值的资源的 Tag User (roles/resourcemanager.tagUser)

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

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

如需将标记附加到 Secret Manager Secret,您需要拥有 Secret Manager Admin 角色 (roles/secretmanager.admin)。

创建标记键和标记值

在附加标记之前,您需要创建标记并配置其值。如需了解详情,请参阅创建标记添加标记值

在创建资源期间添加标记

您可以在创建区域级 Secret 时添加标记。这样做可为资源提供必要的元数据,并有助于更好地进行组织管理、费用跟踪和自动应用政策。

控制台

  1. 前往 Google Cloud 控制台中的 Secret Manager 页面。
  2. 前往 Secret Manager

  3. Secret Manager 页面上,点击区域性 Secret 标签页。
  4. 选择用于创建新的区域级密钥的选项。
  5. 点击管理标签
  6. 如果您的组织未显示在管理标记面板中,请点击选择标记范围,然后选择您的组织或项目。
  7. 点击添加标记
  8. 从列表中选择标记键和标记值。您可以使用关键字过滤列表。
  9. 点击保存。系统会使用标记信息更新标记部分。
  10. 创建区域级密钥。系统会使用提供的标记创建新的区域级密文。

gcloud

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

  • SECRET_ID:相应 Secret 的唯一标识符。
  • LOCATION:相应 Secret 的位置。
  • TAG_KEY:所附加的标记键的永久 ID 或命名空间名称,例如 tagKeys/567890123456
  • TAG_VALUE:所附加的标记值的永久 ID 或命名空间名称,例如 tagValues/567890123456

通过使用英文逗号分隔标记来指定多个标记,例如 TAGKEY1=TAGVALUE1,TAGKEY2=TAGVALUE2

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets create SECRET_ID --location=LOCATION --tags=TAG_KEY=TAG_VALUE

Windows (PowerShell)

gcloud secrets create SECRET_ID --location=LOCATION --tags=TAG_KEY=TAG_VALUE

Windows (cmd.exe)

gcloud secrets create SECRET_ID --location=LOCATION --tags=TAG_KEY=TAG_VALUE

REST

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

  • LOCATION:相应 Secret 的位置
  • PROJECT_ID:项目的 ID
  • SECRET_ID:相应 Secret 的唯一标识符
  • TAGKEY_NAME:所附加的标记键的永久 ID 或命名空间名称,例如 tagKeys/567890123456
  • TAGVALUE_NAME:所附加的标记值的永久 ID 或命名空间名称,例如 tagValues/567890123456

HTTP 方法和网址:

POST https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?secretId=SECRET_ID

请求 JSON 正文:

{
  "tags": {
    "TAGKEY_NAME": "TAGVALUE_NAME"
  }
}

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

curl

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

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?secretId=SECRET_ID"

PowerShell

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

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

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?secretId=SECRET_ID" | Select-Object -Expand Content

您应该会收到一个成功的状态代码 (2xx) 和一个空响应。

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 CreateRegionalSecretWithTagsSample
{
    public Secret CreateRegionalSecretWithTags(
      string projectId = "my-project",
      string locationId = "my-location",
      string secretId = "my-secret",
      string tagKeyName = "tagKey/value",
      string tagValueName = "tagValue/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
        {
            Tags =
            {
                { tagKeyName, tagValueName }
            },
        };

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

// createSecretWithTags creates a new regional secret with the given name and tags.
func createRegionalSecretWithTags(w io.Writer, projectId, locationId, secretId, tagKey, tagValue string) error {
	parent := fmt.Sprintf("projects/%s/locations/%s", projectId, locationId)

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

	// Build the request.
	req := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: secretId,
		Secret: &secretmanagerpb.Secret{
			Tags: map[string]string{
				tagKey: tagValue,
			},
		},
	}

	// 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 tags: %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 CreateRegionalSecretWithTags {

  public static void createRegionalSecretWithTags() 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 tag to be added
    String tagKey = "your-tag-key";
    // This is the value of the tag to be added
    String tagValue = "your-tag-value";
    createRegionalSecretWithTags(projectId, locationId, secretId, tagKey, tagValue);
  }

  // Create a secret with tags.
  public static Secret createRegionalSecretWithTags(
       String projectId,
       String locationId,
       String secretId,
       String tagKey,
       String tagValue)
      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 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 tags.
      Secret secret =
          Secret.newBuilder()
            .putTags(tagKey, tagValue)
            .build();

      // Create the secret.
      Secret createdSecret = client.createSecret(location.toString(), secretId, secret);
      System.out.printf("Created secret with Tags%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 = 'my-location';
// const secretId = 'my-secret';
// const tagKey = 'tagKeys/281475012216835';
// const tagValue = 'tagValues/281476592621530';
const parent = `projects/${projectId}/locations/${locationId}`;

// Imports the 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 createRegionalSecretWithTags() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: {
      tags: {
        [tagKey]: tagValue,
      },
    },
  });

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

createRegionalSecretWithTags();

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 $tagKey     Your tag key (e.g. 'tagKeys/281475012216835')
 * @param string $tagValue   Your tag value (e.g. 'tagValues/281476592621530')
 */
function create_regional_secret_with_tags(string $projectId, string $locationId, string $secretId, string $tagKey, string $tagValue): 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 tags.
    $tags = [$tagKey => $tagValue];
    $secret ->setTags($tags);

    // 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 tag', $newSecret->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_v1


def create_regional_secret_with_tags(
    project_id: str,
    location_id: str,
    secret_id: str,
    tag_key: str,
    tag_value: str,
) -> secretmanager_v1.Secret:
    """
    Create a new regional secret with the given name and associated tags. 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 API.
    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 secret.
    parent = f"projects/{project_id}/locations/{location_id}"

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

    # 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 tags
#
# @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 tag_key [String] Your tag key (e.g. "my-tag-key")
# @param tag_value [String] Your tag value (e.g "my-tag-value")
#
def create_regional_secret_with_tags project_id:, location_id:, secret_id:, tag_key:, tag_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: {
      tags: {
        tag_key.name => tag_value.name
      }
    }
  )

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

为现有资源添加标记

如需为现有区域级 Secret 添加标记,请按照以下步骤操作:

控制台

  1. 前往 Google Cloud 控制台中的 Secret Manager 页面。
  2. 前往 Secret Manager

  3. 选择要附加标记的区域级密钥。
  4. 点击 标记
  5. 如果您的组织未显示在标记面板中,请点击选择范围。选择您的组织,然后点击打开
  6. 点击添加标记
  7. 从列表中选择标记键和标记值。您可以使用关键字过滤列表。
  8. 点击保存
  9. 确认对话框中,点击确认以附加标记。
  10. 系统会显示一条通知以确认您的标记已更新。

gcloud

如需将标记附加到区域级 Secret,您必须使用 gcloud resource-manager tags bindings create 命令创建标记绑定资源:

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

  • TAGVALUE_NAME 是所附加的标记值的永久 ID 或命名空间名称,例如 tagValues/567890123456
  • RESOURCE_ID 是资源的完整 ID,包括用于标识资源类型的 API 域名 (//secretmanager.googleapis.com/)。例如,如需将标记附加到 projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID,则完整 ID 为 //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID
  • LOCATION:资源的位置。如果您要将标记附加到全球性资源(例如文件夹或项目),请省略此标志。如果您要将标记附加到区域级或可用区级资源,则必须指定位置,例如 us-central1(区域)或 us-central1-a(可用区)。

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud resource-manager tags bindings create \
    --tag-value=TAGVALUE_NAME \
    --parent=RESOURCE_ID \
    --location=LOCATION

Windows (PowerShell)

gcloud resource-manager tags bindings create `
    --tag-value=TAGVALUE_NAME `
    --parent=RESOURCE_ID `
    --location=LOCATION

Windows (cmd.exe)

gcloud resource-manager tags bindings create ^
    --tag-value=TAGVALUE_NAME ^
    --parent=RESOURCE_ID ^
    --location=LOCATION

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 tagValue = 'tagValues/281476592621530';
const parent = `projects/${projectId}/locations/${locationId}`;

// Imports the library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');
const {TagBindingsClient} = require('@google-cloud/resource-manager').v3;

// Adding the endpoint to call the regional
const options = {};
const bindingOptions = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;
bindingOptions.apiEndpoint = `${locationId}-cloudresourcemanager.googleapis.com`;

// Instantiates a client
const client = new SecretManagerServiceClient(options);
const resourcemanagerClient = new TagBindingsClient(bindingOptions);

async function bindTagsToRegionalSecret() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
  });

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

  const [operation] = await resourcemanagerClient.createTagBinding({
    tagBinding: {
      parent: `//secretmanager.googleapis.com/${secret.name}`,
      tagValue: tagValue,
    },
  });
  const [response] = await operation.promise();
  console.log('Created Tag Binding', response.name);
}

bindTagsToRegionalSecret();

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;
use Google\Cloud\ResourceManager\V3\Client\TagBindingsClient;
use Google\Cloud\ResourceManager\V3\CreateTagBindingRequest;
use Google\Cloud\ResourceManager\V3\TagBinding;

/**
 * @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 $tagValue   Your tag value (e.g. 'tagValues/281476592621530')
 */
function bind_tags_to_regional_secret(string $projectId, string $locationId, string $secretId, string $tagValue): 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();

    // 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' . PHP_EOL, $newSecret->getName());

    // Specify regional endpoint.
    $tagBindOptions = ['apiEndpoint' => "$locationId-cloudresourcemanager.googleapis.com"];
    $tagBindingsClient = new TagBindingsClient($tagBindOptions);
    $tagBinding = (new TagBinding())
        ->setParent('//secretmanager.googleapis.com/' . $newSecret->getName())
        ->setTagValue($tagValue);

    // Build the request.
    $request = (new CreateTagBindingRequest())
        ->setTagBinding($tagBinding);

    // Create the tag binding.
    $operationResponse = $tagBindingsClient->createTagBinding($request);
    $operationResponse->pollUntilComplete();

    // Check if the operation succeeded.
    if ($operationResponse->operationSucceeded()) {
        printf('Tag binding created for secret %s with tag value %s' . PHP_EOL, $newSecret->getName(), $tagValue);
    } else {
        $error = $operationResponse->getError();
        printf('Error in creating tag binding: %s' . PHP_EOL, $error->getMessage());
    }
}

Python

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

import argparse

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


def bind_tags_to_regional_secret(
    project_id: str,
    location_id: str,
    secret_id: str,
    tag_value: str,
) -> resourcemanager_v3.TagBinding:
    """
    Create a new regional secret with the given name, and then bind an existing
    tag to it. 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.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.
    secret_response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
        }
    )

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

    # Endpoint to call the regional secret manager sever
    resource_manager_api_endpoint = f"{location_id}-cloudresourcemanager.googleapis.com"

    # Create the resource manager client
    resource_manager_client = resourcemanager_v3.TagBindingsClient(
        client_options={"api_endpoint": resource_manager_api_endpoint},
    )

    # Create the tag binding
    request = resourcemanager_v3.CreateTagBindingRequest(
        tag_binding=resourcemanager_v3.TagBinding(
            parent=f"//secretmanager.googleapis.com/{secret_response.name}",
            tag_value=f"{tag_value}",
        ),
    )

    # Create the tag binding
    operation = resource_manager_client.create_tag_binding(request=request)

    # Wait for the operation to complete
    response = operation.result()

    # Print the tag binding
    print(f"Created tag binding: {response.name}")

    return response

列出附加到资源的标记

您可以查看直接附加到区域级 Secret 或由区域级 Secret 继承的标记绑定的列表。

控制台

  1. 前往 Google Cloud 控制台中的 Secret Manager 页面。
  2. 前往 Secret Manager

  3. 标记会显示在相应 Secret 的标记列中。

gcloud

如需获取附加到资源的标记绑定列表,请使用 gcloud resource-manager tags bindings list 命令:

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

  • RESOURCE_ID 是资源的完整 ID,包括用于标识资源类型的 API 域名 (//secretmanager.googleapis.com/)。例如,如需将标记附加到 projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID,则完整 ID 为 //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID
  • LOCATION:资源的位置。如果您要查看附加到全球性资源(例如文件夹或项目)的标记,请省略此标志。如果您要查看附加到区域级或可用区级资源的标记,则必须指定位置,例如 us-central1(区域)或 us-central1-a(可用区)。

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud resource-manager tags bindings list \
    --parent=RESOURCE_ID \
    --location=LOCATION

Windows (PowerShell)

gcloud resource-manager tags bindings list `
    --parent=RESOURCE_ID `
    --location=LOCATION

Windows (cmd.exe)

gcloud resource-manager tags bindings list ^
    --parent=RESOURCE_ID ^
    --location=LOCATION

您应该会收到类似如下所示的响应:

  name: tagBindings/%2F%2Fcloudresourcemanager.googleapis.com%2Fprojects%2F7890123456/tagValues/567890123456
    tagValue: tagValues/567890123456
    resource: //secretmanager.googleapis.com/projects/project-abc/secrets/secret-xyz

将标记与资源分离

您可以分离直接附加到区域级密文的标记。可以通过附加具有相同键和不同值的标记来替换继承的标记,但不能分离这些标记。

控制台

  1. 前往 Google Cloud 控制台中的 Secret Manager 页面。
  2. 前往 Secret Manager

  3. 选择要从中移除标记的区域级密钥。
  4. 点击 标记
  5. 标记面板中,点击要分离的标记旁边的 删除项
  6. 点击保存
  7. 确认对话框中,点击确认以分离标记。

系统会显示一条通知以确认您的标记已更新。

gcloud

如需删除标记绑定,请使用 gcloud resource-manager tags bindings delete 命令:

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

  • TAGVALUE_NAME 是所附加的标记值的永久 ID 或命名空间名称,例如 tagValues/567890123456
  • RESOURCE_ID 是资源的完整 ID,包括用于标识资源类型的 API 域名 (//secretmanager.googleapis.com/)。例如,如需将标记附加到 projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID,则完整 ID 为 //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID
  • LOCATION:资源的位置。如果您要将标记附加到全球性资源(例如文件夹或项目),请省略此标志。如果您要将标记附加到区域级或可用区级资源,则必须指定位置,例如 us-central1(区域)或 us-central1-a(可用区)。

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud resource-manager tags bindings delete \
    --tag-value=TAGVALUE_NAME \
    --parent=RESOURCE_ID \
    --location=LOCATION

Windows (PowerShell)

gcloud resource-manager tags bindings delete `
    --tag-value=TAGVALUE_NAME `
    --parent=RESOURCE_ID `
    --location=LOCATION

Windows (cmd.exe)

gcloud resource-manager tags bindings delete ^
    --tag-value=TAGVALUE_NAME ^
    --parent=RESOURCE_ID ^
    --location=LOCATION

删除标记键和标记值

移除标记键或值定义时,请确保标记已与区域级密钥分离。在删除标记定义本身之前,您必须先删除现有的标记连接(称为标记绑定)。如需了解详情,请参阅删除标记

Identity and Access Management 条件和标记

您可以使用标记和 IAM 条件来有条件地向层次结构中的用户授予角色绑定。如果应用了具有条件角色绑定的 IAM 政策,则更改或删除附加到资源的标记可能会移除用户对该资源的访问权限。如需了解详情,请参阅 Identity and Access Management 条件和标记

后续步骤