리전 보안 비밀의 태그 만들기 및 관리

이 가이드에서는 리전 보안 비밀에 태그를 만들고 관리하는 방법을 설명합니다. 태그를 사용하여 관련 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 페이지에서 리전 보안 비밀 탭을 클릭합니다.
  4. 새 리전 보안 비밀을 만드는 옵션을 선택합니다.
  5. 태그 관리를 클릭합니다.
  6. 조직이 태그 관리 패널에 표시되지 않으면 태그 범위 선택을 클릭하고 조직 또는 프로젝트를 선택합니다.
  7. 태그 추가를 클릭합니다.
  8. 목록에서 태그 키와 태그 값을 선택합니다. 키워드를 사용하여 목록을 필터링할 수 있습니다.
  9. 저장을 클릭합니다. 태그 섹션이 태그 정보로 업데이트됩니다.
  10. 리전 보안 비밀을 만듭니다. 새 리전 보안 비밀이 제공된 태그로 생성됩니다.

gcloud

아래의 명령어 데이터를 사용하기 전에 다음을 바꿉니다.

  • SECRET_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: 보안 비밀의 고유 식별자
  • 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

이 코드를 실행하려면 먼저 자바 개발 환경을 설정하고 Secret Manager 자바 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는 리소스 유형 (//secretmanager.googleapis.com/)을 식별하는 API 도메인 이름을 포함한 리소스의 전체 ID입니다. 예를 들어 태그를 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는 리소스 유형 (//secretmanager.googleapis.com/)을 식별하는 API 도메인 이름을 포함한 리소스의 전체 ID입니다. 예를 들어 태그를 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는 리소스 유형 (//secretmanager.googleapis.com/)을 식별하는 API 도메인 이름을 포함한 리소스의 전체 ID입니다. 예를 들어 태그를 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 조건 및 태그를 참조하세요.

다음 단계