リージョン シークレットのタグを作成して管理する

このガイドでは、リージョン シークレットのタグを作成して管理する方法について説明します。タグを使用すると、関連する Secret Manager のシークレットをグループ化し、タグに基づいてこれらのリソースに関するメタデータを保存できます。

タグについて

タグは、Google Cloud内のリソースに適用できる Key-Value ペアです。タグを使用すると、リソースに特定のタグが付加されているかどうかに基づいて、条件付きでポリシーの許可や拒否を行うことができます。たとえば、リソースに特定のタグがあるかどうかに基づいて、Identity and Access Management(IAM)のロールを条件付きで付与できます。詳細については、タグの概要をご覧ください。

タグは、タグと Google Cloud リソースを結びつけるタグ バインディング リソースを作成することによって、リソースに適用されます。

必要な権限

タグの管理に必要な権限を取得するため、次の IAM ロールを付与するように管理者に依頼してください。

  • タグが適用されているリソースに対する タグ閲覧者roles/resourcemanager.tagViewer
  • 組織レベルでタグを表示および管理する: 組織に対する組織閲覧者roles/resourcemanager.organizationViewer
  • タグの定義を作成、更新、削除する: タグの作成、更新、削除を行うリソースに対する Tag Administratorroles/resourcemanager.tagAdmin
  • リソースにタグを適用する、リソースからタグを削除する: タグの値、タグの値を適用または削除するリソースに対する Tag Userroles/resourcemanager.tagUser

ロールの付与については、プロジェクト、フォルダ、組織に対するアクセス権の管理をご覧ください。

必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

タグを Secret Manager シークレットに適用するには、Secret Manager 管理者ロール(roles/secretmanager.admin)が必要です。

タグキーとタグ値を作成する

タグを適用する前に、タグを作成してその値を構成する必要があります。詳細については、タグの作成タグ値の追加をご覧ください。

リソースの作成時にタグを追加する

タグは、リージョン シークレットの作成時に追加できます。これにより、リソースの重要なメタデータを提供できるだけでなく、整理、費用追跡、ポリシーの自動適用にも役立ちます。

コンソール

  1. Google Cloud コンソールの [Secret Manager] ページに移動します。
  2. Secret Manager に移動

  3. [Secret Manager] ページで、[リージョン シークレット] タブをクリックします。
  4. 新しいリージョン シークレットを作成するオプションを選択します。
  5. [タグを管理] をクリックします。
  6. 組織が [タグの管理] パネルに表示されない場合は、[タグのスコープを選択] をクリックして、組織またはプロジェクトを選択します。
  7. [タグを追加] をクリックします。
  8. リストからタグキーとタグ値を選択します。キーワードを使用してリストをフィルタできます。
  9. [保存] をクリックします。[タグ] セクションがタグ情報で更新されます。
  10. リージョン シークレットを作成します。新しいリージョン シークレットが、指定されたタグを使用して作成されます。

gcloud

後述のコマンドデータを使用する前に、次のように置き換えます。

  • SECRET_ID: シークレットの固有識別子。
  • 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: シークレットのロケーション
  • PROJECT_ID: プロジェクトの ID
  • SECRET_ID: シークレットの固有識別子
  • TAGKEY_NAME: 適用されているタグキーの永続 ID または名前空間付きの名前(例: tagKeys/567890123456)。
  • TAGVALUE_NAME: 適用されるタグ値の永続 ID または名前空間名(例: tagValues/567890123456)。

HTTP メソッドと URL:

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 で、リソースのタイプ(//secretmanager.googleapis.com/)を識別するために API ドメイン名が含まれています。たとえば、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 で、リソースのタイプ(//secretmanager.googleapis.com/)を識別するために API ドメイン名が含まれています。たとえば、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 で、リソースのタイプ(//secretmanager.googleapis.com/)を識別するために API ドメイン名が含まれています。たとえば、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 Conditions を使用すると、階層内のユーザーに条件付きでロール バインディングを付与できます。条件付きロール バインディングを含む IAM ポリシーが適用されている場合、リソースに適用されたタグを変更または削除すると、そのリソースへのユーザー アクセスを削除できます。詳細については、Identity and Access Management の条件とタグをご覧ください。

次のステップ