Crear y gestionar etiquetas de secretos regionales

En esta guía se describe cómo crear y gestionar etiquetas en secretos regionales. Puedes usar etiquetas para agrupar secretos relacionados de Secret Manager y almacenar metadatos sobre esos recursos en función de sus etiquetas.

Acerca de las etiquetas

Una etiqueta es un par clave-valor que se puede adjuntar a un recurso deGoogle Cloud. Puedes usar etiquetas para permitir o denegar políticas de forma condicional en función de si un recurso tiene una etiqueta específica. Por ejemplo, puedes conceder roles de Gestión de Identidades y Accesos (IAM) de forma condicional en función de si un recurso tiene una etiqueta específica. Para obtener más información, consulta el artículo Descripción general de las etiquetas.

Las etiquetas se adjuntan a los recursos creando un recurso TagBinding que vincula el valor al recurso. Google Cloud

Permisos obligatorios

Para obtener los permisos que necesitas para gestionar etiquetas, pide a tu administrador que te conceda los siguientes roles de gestión de identidades y accesos:

  • Lector de etiquetas (roles/resourcemanager.tagViewer) en los recursos a los que están asociadas las etiquetas
  • Ver y gestionar etiquetas a nivel de organización: Lector de organización (roles/resourcemanager.organizationViewer) en la organización
  • Crear, actualizar y eliminar definiciones de etiquetas: Administrador de etiquetas (roles/resourcemanager.tagAdmin) en el recurso para el que vas a crear, actualizar o eliminar etiquetas
  • Asignar y quitar etiquetas de recursos: Etiquetador de usuarios (roles/resourcemanager.tagUser) en el valor de la etiqueta y los recursos a los que asignes o quites el valor de la etiqueta

Para obtener más información sobre cómo conceder roles, consulta el artículo Gestionar acceso a proyectos, carpetas y organizaciones.

También puedes conseguir los permisos necesarios a través de roles personalizados u otros roles predefinidos.

Para adjuntar etiquetas a los secretos de Secret Manager, necesitas el rol Administrador de Secret Manager (roles/secretmanager.admin).

Crear claves y valores de etiquetas

Para poder adjuntar una etiqueta, primero debes crearla y configurar su valor. Para obtener más información, consulta los artículos Crear una etiqueta y Añadir un valor de etiqueta.

Añadir etiquetas durante la creación de recursos

Puede añadir etiquetas al crear secretos regionales. De esta forma, puedes proporcionar metadatos esenciales para tus recursos y disfrutar de una mejor organización, un seguimiento de costes más preciso y una aplicación de políticas automatizada.

Consola

  1. Ve a la página Secret Manager en la consola de Google Cloud .
  2. Ir a Secret Manager

  3. En la página Secret Manager, haz clic en la pestaña Secretos regionales.
  4. Selecciona la opción para crear un secreto regional.
  5. Haz clic en Gestionar etiquetas.
  6. Si tu organización no aparece en el panel Gestionar etiquetas, haz clic en Seleccionar ámbito de las etiquetas y selecciona tu organización o proyecto.
  7. Haz clic en Añadir etiqueta.
  8. Selecciona la clave y el valor de la etiqueta en la lista. Puedes filtrar la lista por palabras clave.
  9. Haz clic en Guardar. La sección Etiquetas se actualiza con la información de las etiquetas.
  10. Crea tu secreto regional. El nuevo secreto regional se crea con las etiquetas proporcionadas.

gcloud

Antes de usar cualquiera de los datos de los comandos que se indican a continuación, haz las siguientes sustituciones:

  • SECRET_ID: identificador único del secreto.
  • LOCATION: la ubicación del secreto.
  • TAG_KEY: el ID permanente o el nombre con espacio de nombres de la clave de etiqueta que se ha adjuntado (por ejemplo, tagKeys/567890123456).
  • TAG_VALUE: el ID permanente o el nombre con espacio de nombres del valor de la etiqueta adjunta (por ejemplo, tagValues/567890123456).

Para especificar varias etiquetas, sepáralas con comas (por ejemplo, TAGKEY1=TAGVALUE1,TAGKEY2=TAGVALUE2).

Ejecuta el siguiente comando:

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

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • LOCATION: la ubicación del secreto
  • PROJECT_ID: el ID del proyecto
  • SECRET_ID: identificador único del secreto
  • TAGKEY_NAME: el ID permanente o el nombre con espacio de nombres de la clave de etiqueta adjunta (por ejemplo, tagKeys/567890123456).
  • TAGVALUE_NAME: el ID permanente o el nombre con espacio de nombres del valor de la etiqueta que se adjunta. Por ejemplo, tagValues/567890123456.

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

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

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$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

Deberías recibir un código de estado que indique que la operación se ha realizado correctamente (2xx) y una respuesta vacía.

C#

Para ejecutar este código, primero debes configurar un entorno de desarrollo de C# e instalar el SDK de C# de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito 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

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Go e instalar el SDK de Go de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito 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

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Java e instalar el SDK de Java de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito 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

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Node.js e instalar el SDK de Node.js de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito 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

Para ejecutar este código, primero debes consultar información sobre cómo usar PHP en Google Cloud e instalar el SDK de PHP de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito 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

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito 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

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Ruby e instalar el SDK de Ruby de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito 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

Añadir etiquetas a recursos

Para añadir una etiqueta a secretos regionales, sigue estos pasos:

Consola

  1. Ve a la página Secret Manager en la consola de Google Cloud .
  2. Ir a Secret Manager

  3. Selecciona el secreto regional al que quieras adjuntar una etiqueta.
  4. Haga clic en Etiquetas.
  5. Si tu organización no aparece en el panel Etiquetas, haz clic en Seleccionar ámbito. Selecciona tu organización y haz clic en Abrir.
  6. Haz clic en Añadir etiqueta.
  7. Selecciona la clave y el valor de la etiqueta en la lista. Puedes filtrar la lista por palabras clave.
  8. Haz clic en Guardar.
  9. En el cuadro de diálogo Confirmar, haz clic en Confirmar para adjuntar la etiqueta.
  10. Recibirás una notificación para confirmar que se han actualizado las etiquetas.

gcloud

Para adjuntar una etiqueta a un secreto regional, debes crear un recurso de vinculación de etiquetas mediante el comando gcloud resource-manager tags bindings create:

Antes de usar cualquiera de los datos de los comandos que se indican a continuación, haz las siguientes sustituciones:

  • TAGVALUE_NAME: el ID permanente o el nombre con espacio de nombres del valor de la etiqueta adjunta (por ejemplo, tagValues/567890123456).
  • RESOURCE_ID es el ID completo del recurso, incluido el nombre de dominio de la API, para identificar el tipo de recurso (//secretmanager.googleapis.com/). Por ejemplo, para adjuntar una etiqueta a projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, el ID completo es //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: la ubicación de tu recurso. Si vas a asociar una etiqueta a un recurso global, como una carpeta o un proyecto, omite esta marca. Si vas a asociar una etiqueta a un recurso regional o zonal, debes especificar la ubicación. Por ejemplo, us-central1 (región) o us-central1-a (zona).

Ejecuta el siguiente comando:

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

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Node.js e instalar el SDK de Node.js de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito 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

Para ejecutar este código, primero debes consultar información sobre cómo usar PHP en Google Cloud e instalar el SDK de PHP de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito 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

Para ejecutar este código, primero debes configurar un entorno de desarrollo de Python e instalar el SDK de Python de Secret Manager. En Compute Engine o GKE, debes autenticarte con el ámbito 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

Mostrar las etiquetas asociadas a los recursos

Puede ver una lista de enlaces de etiquetas adjuntos directamente al secreto regional o heredados por él.

Consola

  1. Ve a la página Secret Manager en la consola de Google Cloud .
  2. Ir a Secret Manager

  3. Las etiquetas se muestran en la columna Etiquetas del secreto.

gcloud

Para obtener una lista de las vinculaciones de etiquetas asociadas a un recurso, usa el comando gcloud resource-manager tags bindings list:

Antes de usar cualquiera de los datos de los comandos que se indican a continuación, haz las siguientes sustituciones:

  • RESOURCE_ID es el ID completo del recurso, incluido el nombre de dominio de la API, para identificar el tipo de recurso (//secretmanager.googleapis.com/). Por ejemplo, para adjuntar una etiqueta a projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, el ID completo es //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: la ubicación de tu recurso. Si estás viendo una etiqueta asociada a un recurso global, como una carpeta o un proyecto, omite esta marca. Si estás viendo una etiqueta asociada a un recurso regional o zonal, debes especificar la ubicación. Por ejemplo, us-central1 (región) o us-central1-a (zona).

Ejecuta el siguiente comando:

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

Deberías recibir una respuesta similar a la siguiente:

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

Desvincular etiquetas de recursos

Puedes separar las etiquetas que se hayan adjuntado directamente a un secreto regional. Las etiquetas heredadas se pueden anular adjuntando una etiqueta con la misma clave y un valor diferente, pero no se pueden separar.

Consola

  1. Ve a la página Secret Manager en la consola de Google Cloud .
  2. Ir a Secret Manager

  3. Selecciona el secreto regional del que quieras quitar una etiqueta.
  4. Haga clic en Etiquetas.
  5. En el panel Etiquetas, junto a la etiqueta que quieras desvincular, haz clic en Eliminar elemento.
  6. Haz clic en Guardar.
  7. En el cuadro de diálogo Confirmar, haz clic en Confirmar para separar la etiqueta.

Recibirás una notificación para confirmar que se han actualizado las etiquetas.

gcloud

Para eliminar un enlace de etiqueta, usa el comando gcloud resource-manager tags bindings delete:

Antes de usar cualquiera de los datos de los comandos que se indican a continuación, haz las siguientes sustituciones:

  • TAGVALUE_NAME: el ID permanente o el nombre con espacio de nombres del valor de la etiqueta adjunta (por ejemplo, tagValues/567890123456).
  • RESOURCE_ID es el ID completo del recurso, incluido el nombre de dominio de la API, para identificar el tipo de recurso (//secretmanager.googleapis.com/). Por ejemplo, para adjuntar una etiqueta a projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, el ID completo es //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: la ubicación de tu recurso. Si vas a asociar una etiqueta a un recurso global, como una carpeta o un proyecto, omite esta marca. Si vas a asociar una etiqueta a un recurso regional o zonal, debes especificar la ubicación. Por ejemplo, us-central1 (región) o us-central1-a (zona).

Ejecuta el siguiente comando:

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

Eliminar claves y valores de etiquetas

Cuando elimine una definición de clave o valor de etiqueta, asegúrese de que la etiqueta esté separada del secreto regional. Debes eliminar los archivos adjuntos de etiquetas, denominados enlaces de etiquetas, antes de eliminar la definición de la etiqueta. Para obtener más información, consulta Eliminar etiquetas.

Condiciones y etiquetas de gestión de identidades y accesos

Puedes usar etiquetas y condiciones de gestión de identidades y accesos para conceder enlaces de roles de forma condicional a los usuarios de tu jerarquía. Si se cambia o se elimina la etiqueta asociada a un recurso, se puede retirar el acceso de los usuarios a ese recurso si se ha aplicado una política de IAM con enlaces de roles condicionales. Para obtener más información, consulta Condiciones y etiquetas de Gestión de Identidades y Accesos.

Siguientes pasos