Membuat dan mengelola tag untuk rahasia regional

Panduan ini menjelaskan cara membuat dan mengelola tag pada secret regional. Anda dapat menggunakan tag untuk mengelompokkan secret Secret Manager terkait dan menyimpan metadata tentang resource tersebut berdasarkan tagnya.

Tentang tag

Tag adalah pasangan nilai kunci yang dapat dilampirkan ke resource di Google Cloud. Anda dapat menggunakan tag untuk mengizinkan atau menolak kebijakan bersyarat berdasarkan apakah resource memiliki tag tertentu. Misalnya, Anda dapat memberikan peran Identity and Access Management (IAM) secara bersyarat berdasarkan apakah resource memiliki tag tertentu atau tidak. Untuk mengetahui informasi selengkapnya, lihat Ringkasan tag.

Tag dikaitkan ke resource dengan membuat resource binding tag yang menautkan nilai ke resource Google Cloud .

Izin yang diperlukan

Untuk mendapatkan izin yang Anda perlukan guna mengelola tag, minta administrator untuk memberi Anda peran IAM berikut:

  • Tag Viewer (roles/resourcemanager.tagViewer) pada resource yang dikaitkan dengan tag
  • Melihat dan mengelola tag di tingkat organisasi: Organization Viewer (roles/resourcemanager.organizationViewer) pada organisasi
  • Membuat, memperbarui, dan menghapus definisi tag: Administrator Tag (roles/resourcemanager.tagAdmin) pada resource yang tag-nya Anda buat, perbarui, atau hapus
  • Melampirkan dan menghapus tag dari resource: Tag User (roles/resourcemanager.tagUser) pada nilai tag dan resource tempat Anda melampirkan atau menghapus nilai tag

Untuk mengetahui informasi selengkapnya tentang pemberian peran, lihat Mengelola akses ke project, folder, dan organisasi.

Anda mungkin juga bisa mendapatkan izin yang diperlukan melalui peran khusus atau peran bawaan lainnya.

Untuk melampirkan tag ke secret Secret Manager, Anda memerlukan peran Admin Secret Manager (roles/secretmanager.admin).

Membuat kunci dan nilai tag

Sebelum dapat mengaitkan tag, Anda harus membuat tag dan mengonfigurasi nilainya. Untuk mengetahui informasi selengkapnya, lihat Membuat tag dan Menambahkan nilai tag.

Menambahkan tag selama pembuatan resource

Anda dapat menambahkan tag saat membuat secret regional. Dengan melakukannya, Anda dapat memberikan metadata penting untuk resource dan memungkinkan pengaturan yang lebih baik, pelacakan biaya, dan penerapan kebijakan otomatis.

Konsol

  1. Buka halaman Secret Manager di konsol Google Cloud .
  2. Buka Secret Manager

  3. Di halaman Secret Manager, klik tab Regional secrets.
  4. Pilih opsi untuk membuat secret regional baru.
  5. Klik Kelola tag.
  6. Jika organisasi Anda tidak muncul di panel Kelola tag, klik Pilih cakupan untuk tag, lalu pilih organisasi atau project Anda.
  7. Klik Tambahkan tag.
  8. Pilih kunci tag dan nilai tag dari daftar. Anda dapat memfilter daftar menggunakan kata kunci.
  9. Klik Simpan. Bagian Tag diperbarui dengan informasi tag.
  10. Buat secret regional Anda. Secret regional baru dibuat dengan tag yang diberikan.

gcloud

Sebelum menggunakan salah satu data perintah di bawah, lakukan penggantian berikut:

  • SECRET_ID: ID unik secret.
  • LOCATION: lokasi secret.
  • TAG_KEY: ID permanen atau nama dengan namespace dari kunci tag yang dilampirkan-misalnya, tagKeys/567890123456.
  • TAG_VALUE: ID permanen atau nama dengan namespace dari nilai tag yang dilampirkan—misalnya, tagValues/567890123456.

Tentukan beberapa tag dengan memisahkan tag menggunakan koma, misalnya, TAGKEY1=TAGVALUE1,TAGKEY2=TAGVALUE2.

Jalankan perintah berikut:

Linux, macOS, atau 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

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • LOCATION: lokasi secret
  • PROJECT_ID: ID project
  • SECRET_ID: ID unik secret
  • TAGKEY_NAME: ID permanen atau nama dengan namespace dari kunci tag yang dilampirkan—misalnya, tagKeys/567890123456.
  • TAGVALUE_NAME: ID permanen atau nama dengan namespace dari nilai tag yang dilampirkan—misalnya, tagValues/567890123456.

Metode HTTP dan URL:

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

Meminta isi JSON:

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

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

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

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$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

Anda akan menerima kode status berhasil (2xx) dan respons kosong.

C#

Untuk menjalankan kode ini, siapkan lingkungan pengembangan C# terlebih dahulu dan instal Secret Manager C# SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan 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

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Go terlebih dahulu dan instal Secret Manager Go SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan 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

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Java terlebih dahulu dan instal Secret Manager Java SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan 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

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Node.js terlebih dahulu dan instal Secret Manager Node.js SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan 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

Untuk menjalankan kode ini, pelajari terlebih dahulu cara menggunakan PHP di Google Cloud dan instal Secret Manager PHP SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan 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

Untuk menjalankan kode ini, pertama-tama siapkan lingkungan pengembangan Python dan instal Secret Manager Python SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan 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

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Ruby terlebih dahulu dan instal Secret Manager Ruby SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan 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

Menambahkan tag ke resource yang ada

Untuk menambahkan tag ke secret regional yang ada, ikuti langkah-langkah berikut:

Konsol

  1. Buka halaman Secret Manager di konsol Google Cloud .
  2. Buka Secret Manager

  3. Pilih secret regional yang ingin Anda lampiri tag.
  4. Klik Tag.
  5. Jika organisasi Anda tidak muncul di panel Tag, klik Pilih cakupan. Pilih organisasi Anda, lalu klik Buka.
  6. Klik Tambahkan tag.
  7. Pilih kunci tag dan nilai tag dari daftar. Anda dapat memfilter daftar menggunakan kata kunci.
  8. Klik Simpan.
  9. Dalam dialog Konfirmasi, klik Konfirmasi untuk melampirkan tag.
  10. Notifikasi mengonfirmasi bahwa tag Anda telah diperbarui.

gcloud

Untuk melampirkan tag ke secret regional, Anda harus membuat resource binding tag menggunakan perintah gcloud resource-manager tags bindings create:

Sebelum menggunakan salah satu data perintah di bawah, lakukan penggantian berikut:

  • TAGVALUE_NAME: ID permanen atau nama dengan namespace dari nilai tag yang dikaitkan—misalnya, tagValues/567890123456.
  • RESOURCE_ID adalah ID lengkap resource, termasuk nama domain API untuk mengidentifikasi jenis resource (//secretmanager.googleapis.com/). Misalnya, untuk melampirkan tag ke projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, ID lengkapnya adalah //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: lokasi resource Anda. Jika Anda mengaitkan tag ke resource global, seperti folder atau project, hilangkan flag ini. Jika mengaitkan tag ke resource regional atau zona, Anda harus menentukan lokasinya—misalnya, us-central1 (region) atau us-central1-a (zona).

Jalankan perintah berikut:

Linux, macOS, atau 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

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Node.js terlebih dahulu dan instal Secret Manager Node.js SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan 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

Untuk menjalankan kode ini, pelajari terlebih dahulu cara menggunakan PHP di Google Cloud dan instal Secret Manager PHP SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan 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

Untuk menjalankan kode ini, pertama-tama siapkan lingkungan pengembangan Python dan instal Secret Manager Python SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan 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

Mencantumkan tag yang dilampirkan ke resource

Anda dapat melihat daftar binding tag yang dikaitkan langsung atau diwarisi oleh secret regional.

Konsol

  1. Buka halaman Secret Manager di konsol Google Cloud .
  2. Buka Secret Manager

  3. Tag ditampilkan di kolom Tags rahasia.

gcloud

Untuk mendapatkan daftar binding tag yang dipasang ke resource, gunakan perintah gcloud resource-manager tags bindings list:

Sebelum menggunakan salah satu data perintah di bawah, lakukan penggantian berikut:

  • RESOURCE_ID adalah ID lengkap resource, termasuk nama domain API untuk mengidentifikasi jenis resource (//secretmanager.googleapis.com/). Misalnya, untuk melampirkan tag ke projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, ID lengkapnya adalah //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: lokasi resource Anda. Jika Anda melihat tag yang dikaitkan ke resource global, seperti folder atau project, hilangkan tanda ini. Jika melihat tag yang dikaitkan ke resource regional atau zona, Anda harus menentukan lokasinya—misalnya, us-central1 (region) atau us-central1-a (zona).

Jalankan perintah berikut:

Linux, macOS, atau 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

Anda akan melihat respons seperti berikut:

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

Melepaskan tag dari resource

Anda dapat melepaskan tag yang telah dikaitkan secara langsung ke secret regional. Tag yang diwariskan dapat diganti dengan melampirkan tag dengan kunci yang sama dan nilai yang berbeda, tetapi tag tersebut tidak dapat dilepaskan.

Konsol

  1. Buka halaman Secret Manager di konsol Google Cloud .
  2. Buka Secret Manager

  3. Pilih secret regional yang ingin Anda hapus tag-nya.
  4. Klik Tag.
  5. Di panel Tag, di samping tag yang ingin dilepas, klik Hapus item.
  6. Klik Simpan.
  7. Dalam dialog Konfirmasi, klik Konfirmasi untuk melepas tag.

Notifikasi mengonfirmasi bahwa tag Anda telah diperbarui.

gcloud

Untuk menghapus binding tag, gunakan perintah gcloud resource-manager tags bindings delete:

Sebelum menggunakan salah satu data perintah di bawah, lakukan penggantian berikut:

  • TAGVALUE_NAME: ID permanen atau nama dengan namespace dari nilai tag yang dikaitkan—misalnya, tagValues/567890123456.
  • RESOURCE_ID adalah ID lengkap resource, termasuk nama domain API untuk mengidentifikasi jenis resource (//secretmanager.googleapis.com/). Misalnya, untuk melampirkan tag ke projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, ID lengkapnya adalah //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: lokasi resource Anda. Jika Anda mengaitkan tag ke resource global, seperti folder atau project, hilangkan flag ini. Jika mengaitkan tag ke resource regional atau zona, Anda harus menentukan lokasinya—misalnya, us-central1 (region) atau us-central1-a (zona).

Jalankan perintah berikut:

Linux, macOS, atau 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

Menghapus kunci dan nilai tag

Saat menghapus kunci tag atau definisi nilai, pastikan tag tersebut dilepaskan dari secret regional. Anda harus menghapus lampiran tag yang ada, yang disebut binding tag, sebelum menghapus definisi tag itu sendiri. Untuk mengetahui informasi selengkapnya, lihat Menghapus tag.

Kondisi dan tag Identity and Access Management

Anda dapat menggunakan tag dan kondisi IAM untuk memberikan binding peran bersyarat kepada pengguna dalam hierarki Anda. Mengubah atau menghapus tag yang dikaitkan ke resource dapat menghapus akses pengguna ke resource tersebut jika kebijakan IAM dengan binding peran bersyarat telah diterapkan. Untuk mengetahui informasi selengkapnya, lihat Kondisi dan tag Identity and Access Management.

Langkah berikutnya