建立及管理區域性密鑰的標記

本指南說明如何建立及管理地區密鑰的標記。您可以透過標籤將相關的 Secret Manager 密鑰分組,並根據標籤儲存這些資源的中繼資料。

關於代碼

標記是可附加至Google Cloud內資源的鍵/值組合。您可以將資源是否具備特定標記設為條件,並按照這項條件允許或拒絕政策。舉例來說,您可以根據資源是否具備特定標記,有條件地授予 Identity and Access Management (IAM) 角色。詳情請參閱「標記總覽」。

如要將標記附加至資源,請建立標記繫結資源,將值連結至 Google Cloud 資源。

所需權限

如要取得管理標記所需的權限,請要求管理員授予您下列 IAM 角色:

  • 標記檢視者 (roles/resourcemanager.tagViewer) 標記附加至的資源
  • 在機構層級查看及管理標記: 機構檢視者 (roles/resourcemanager.organizationViewer) 機構
  • 建立、更新及刪除代碼定義: 代碼管理員 (roles/resourcemanager.tagAdmin) 適用於您要建立、更新或刪除代碼的資源
  • 在資源中附加及移除標記: 標記使用者 (roles/resourcemanager.tagUser) 在標記值和您要附加或移除標記值的資源上

如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

如要將標記附加至 Secret Manager 密鑰,您需要 Secret Manager 管理員角色 (roles/secretmanager.admin)。

建立標記鍵和值

您必須先建立標記並設定其值,才能附加標記。 詳情請參閱「建立標記」和「新增標記值」。

在建立資源時新增標籤

建立區域性密鑰時,您可以新增標記。這樣做可為資源提供必要的中繼資料,並有助於妥善分類、追蹤費用,以及自動套用政策。

控制台

  1. 前往 Google Cloud 控制台的「Secret Manager」頁面。
  2. 前往 Secret Manager

  3. 在「Secret Manager」頁面中,按一下「Regional secrets」分頁標籤。
  4. 選取建立新區域性密鑰的選項。
  5. 按一下「管理代碼」
  6. 如果「管理代碼」面板中未顯示貴機構,請按一下「選取代碼範圍」,然後選取貴機構或專案。
  7. 按一下「新增代碼」
  8. 從清單中選取標記鍵和標記值。你可以使用關鍵字篩選清單。
  9. 按一下 [儲存]。「標記」部分會更新標記資訊。
  10. 建立區域性密鑰。系統會使用提供的標記建立新的區域性密鑰。

gcloud

使用下列任何指令資料之前,請先替換以下項目:

  • SECRET_ID:密鑰的專屬 ID。
  • LOCATION:密鑰的位置。
  • 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:密鑰的位置
  • PROJECT_ID:專案 ID
  • SECRET_ID:密鑰的專屬 ID
  • 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

為現有資源新增標記

如要為現有的區域密鑰新增標記,請按照下列步驟操作:

控制台

  1. 前往 Google Cloud 控制台的「Secret Manager」頁面。
  2. 前往 Secret Manager

  3. 選取要附加標記的區域密鑰。
  4. 按一下「代碼」
  5. 如果「標記」面板中未顯示貴機構,請按一下「選取範圍」。選取機構,然後按一下「開啟」
  6. 按一下「新增代碼」
  7. 從清單中選取標記鍵和標記值。你可以使用關鍵字篩選清單。
  8. 按一下 [儲存]
  9. 在「確認」對話方塊中,按一下「確認」即可附加代碼。
  10. 系統會發送通知,確認標記已更新。

gcloud

如要將標記附加至區域密鑰,請使用 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

列出附加至資源的標記

您可以查看直接附加至或由區域密鑰繼承的標記繫結清單。

控制台

  1. 前往 Google Cloud 控制台的「Secret Manager」頁面。
  2. 前往 Secret Manager

  3. 標記會顯示在密碼的「標記」欄中。

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

刪除標籤鍵和值

移除標籤鍵或值定義時,請務必將標籤從區域密鑰中分離。您必須先刪除現有代碼附件 (稱為代碼繫結),才能刪除代碼定義本身。詳情請參閱「刪除代碼」。

身分與存取權管理條件和標記

您可以使用標記和 IAM 條件,有條件地將角色繫結授予階層中的使用者。如果已套用具有條件式角色繫結的 IAM 政策,變更或刪除附加至資源的標記,可能會移除使用者對該資源的存取權。詳情請參閱「身分與存取權管理條件和標記」。

後續步驟