Criar e gerenciar tags para secrets regionais

Neste guia, descrevemos como criar e gerenciar tags em secrets regionais. É possível usar tags para agrupar secrets relacionados do Secret Manager e armazenar metadados sobre esses recursos com base nas tags deles.

Sobre as tags

Uma tag é um par de chave-valor que pode ser anexado a um recurso no Google Cloud. É possível usar tags para permitir ou negar políticas condicionalmente com base no fato de um recurso ter uma tag específica ou não. Por exemplo, é possível conceder condicionalmente papéis do Identity and Access Management (IAM) com base no fato de um recurso ter uma tag específica ou não. Para mais informações, consulte Visão geral das tags.

As tags são anexadas aos recursos criando um recurso de vinculação de tags que vincula o valor ao recurso do Google Cloud .

Permissões necessárias

Para receber as permissões necessárias para gerenciar tags, peça ao administrador que conceda a você os seguintes papéis do IAM:

  • Leitor de tags (roles/resourcemanager.tagViewer) nos recursos a que as tags estão anexadas
  • Visualizar e gerenciar tags no nível da organização: Leitor da organização (roles/resourcemanager.organizationViewer) na organização
  • Criar, atualizar e excluir definições de tags: Administrador de tags (roles/resourcemanager.tagAdmin) no recurso em que você está criando, atualizando ou excluindo tags
  • Anexar e remover tags de recursos: Usuário de tag (roles/resourcemanager.tagUser) no valor da tag e nos recursos a que você está anexando ou removendo o valor da tag

Para mais informações sobre a concessão de papéis, consulte Gerenciar o acesso a projetos, pastas e organizações.

Também é possível conseguir as permissões necessárias usando papéis personalizados ou outros papéis predefinidos.

Para anexar tags a secrets do Secret Manager, você precisa do papel Administrador do Secret Manager (roles/secretmanager.admin).

Criar chaves e valores de tags

Antes de anexar uma tag, é preciso criá-la e configurar o valor dela. Para mais informações, consulte Como criar uma tag e Como adicionar um valor de tag.

Adicionar tags durante a criação de recursos

É possível adicionar tags ao criar secrets regionais. Assim, você fornece metadados essenciais para seus recursos e permite uma melhor organização, rastreamento de custos e aplicação automatizada de políticas.

Console

  1. Acesse a página Secret Manager no console Google Cloud .
  2. Acessar o Secret Manager

  3. Na página Secret Manager, clique na guia Secrets regionais.
  4. Selecione a opção para criar um novo secret regional.
  5. Clique em Gerenciar tags.
  6. Se a organização não aparecer no painel Gerenciar tags, clique em Selecionar escopo para tags e escolha sua organização ou projeto.
  7. Clique em Adicionar tag.
  8. Selecione a chave e o valor da tag na lista. É possível filtrar a lista usando palavras-chave.
  9. Clique em Salvar. A seção Tags é atualizada com as informações das tags.
  10. Crie seu secret regional. O novo Secret regional é criado com as tags fornecidas.

gcloud

Antes de usar os dados do comando abaixo, faça estas substituições:

  • SECRET_ID: o identificador exclusivo do secret.
  • LOCATION: o local do secret.
  • TAG_KEY: o ID permanente ou o nome do namespace da chave de tag anexada. Por exemplo, tagKeys/567890123456.
  • TAG_VALUE: o ID permanente ou o nome do namespace do valor da tag anexado; por exemplo, tagValues/567890123456.

Especifique várias tags separando-as por vírgula, por exemplo, TAGKEY1=TAGVALUE1,TAGKEY2=TAGVALUE2.

Execute o seguinte comando:

Linux, macOS ou 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 os dados da solicitação abaixo, faça as substituições a seguir:

  • LOCATION: o local do secret
  • PROJECT_ID: o ID do projeto
  • SECRET_ID: o identificador exclusivo do secret
  • TAGKEY_NAME: o ID permanente ou o nome do namespace da chave de tag anexada. Por exemplo, tagKeys/567890123456.
  • TAGVALUE_NAME: o ID permanente ou o nome do namespace do valor da tag anexado; por exemplo, tagValues/567890123456.

Método HTTP e URL:

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

Corpo JSON da solicitação:

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

Para enviar a solicitação, escolha uma destas opções:

curl

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando abaixo:

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

Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:

$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

Você receberá um código de status bem-sucedido (2xx) e uma resposta vazia.

C#

Para executar esse código, primeiro configure um ambiente de desenvolvimento em C# e instale o SDK do C# do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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 executar esse código, primeiro configure um ambiente de desenvolvimento do Go e instale o SDK do Go do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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 executar esse código, primeiro configure um ambiente de desenvolvimento do Java e instale o SDK do Java do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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 executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Node.js do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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 executar este código, veja primeiro como usar o PHP no Google Cloud e instalar o SDK do PHP do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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 executar esse código, primeiro configure um ambiente de desenvolvimento do Python e instale o SDK do Python do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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 executar esse código, primeiro configure um ambiente de desenvolvimento em Ruby e instale o SDK do Ruby do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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

Adicionar tags a recursos atuais

Para adicionar uma tag a segredos regionais atuais, siga estas etapas:

Console

  1. Acesse a página Secret Manager no console Google Cloud .
  2. Acessar o Secret Manager

  3. Selecione o secret regional a que você quer anexar uma tag.
  4. Clique em Tags.
  5. Se a organização não aparecer no painel Tags, clique em Selecionar escopo. Selecione sua organização e clique em Abrir.
  6. Clique em Adicionar tag.
  7. Selecione a chave e o valor da tag na lista. É possível filtrar a lista usando palavras-chave.
  8. Clique em Salvar.
  9. Na caixa de diálogo Confirmar, clique em Confirmar para anexar a tag.
  10. Uma notificação confirma que suas tags foram atualizadas.

gcloud

Para anexar uma tag a um secret regional, crie um recurso de vinculação de tag usando o comando gcloud resource-manager tags bindings create:

Antes de usar os dados do comando abaixo, faça estas substituições:

  • TAGVALUE_NAME: o ID permanente ou o nome do namespace do valor da tag anexado; por exemplo: tagValues/567890123456.
  • RESOURCE_ID é o ID completo do recurso, incluindo o nome de domínio da API para identificar o tipo de recurso (//secretmanager.googleapis.com/). Por exemplo, para anexar uma tag a projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, o ID completo é //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: a localização do recurso. Se você estiver anexando uma tag a um recurso global, como uma pasta ou um projeto, omita essa flag. Se você estiver anexando uma tag a um recurso regional ou zonal, especifique o local, por exemplo: us-central1 (região) ou us-central1-a (zona).

Execute o seguinte comando:

Linux, macOS ou 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 executar esse código, primeiro configure um ambiente de desenvolvimento do Node.js e instale o SDK do Node.js do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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 executar este código, veja primeiro como usar o PHP no Google Cloud e instalar o SDK do PHP do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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 executar esse código, primeiro configure um ambiente de desenvolvimento do Python e instale o SDK do Python do Secret Manager. No Compute Engine ou no GKE, você precisa fazer a autenticação com o escopo do 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

Listar tags anexadas a recursos

É possível consultar uma lista de vinculações de tags anexadas diretamente ou herdadas pelo secret regional.

Console

  1. Acesse a página Secret Manager no console Google Cloud .
  2. Acessar o Secret Manager

  3. As tags são mostradas na coluna Tags do secret.

gcloud

Para consultar uma lista de vinculações de tags anexadas a um recurso, use o comando gcloud resource-manager tags bindings list:

Antes de usar os dados do comando abaixo, faça estas substituições:

  • RESOURCE_ID é o ID completo do recurso, incluindo o nome de domínio da API para identificar o tipo de recurso (//secretmanager.googleapis.com/). Por exemplo, para anexar uma tag a projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, o ID completo é //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: a localização do recurso. Se você estiver visualizando uma tag anexada a um recurso global, como uma pasta ou projeto, omita essa flag. Se você estiver visualizando uma tag anexada a um recurso regional ou zonal, especifique o local, por exemplo, us-central1 (região) ou us-central1-a (zona).

Execute o seguinte comando:

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

Você receberá uma resposta semelhante a esta:

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

Remover tags de recursos

É possível desanexar tags que foram anexadas diretamente a um secret regional. As tags herdadas podem ser substituídas anexando uma tag com a mesma chave e um valor diferente, mas não podem ser removidas.

Console

  1. Acesse a página Secret Manager no console Google Cloud .
  2. Acessar o Secret Manager

  3. Selecione o secret regional de que você quer remover uma tag.
  4. Clique em Tags.
  5. No painel Tags, ao lado da tag que você quer remover, clique em Excluir item.
  6. Clique em Salvar.
  7. Na caixa de diálogo Confirmar, clique em Confirmar para remover a tag.

Uma notificação confirma que suas tags foram atualizadas.

gcloud

Para excluir uma vinculação de tag, use o comando gcloud resource-manager tags bindings delete:

Antes de usar os dados do comando abaixo, faça estas substituições:

  • TAGVALUE_NAME: o ID permanente ou o nome do namespace do valor da tag anexado; por exemplo: tagValues/567890123456.
  • RESOURCE_ID é o ID completo do recurso, incluindo o nome de domínio da API para identificar o tipo de recurso (//secretmanager.googleapis.com/). Por exemplo, para anexar uma tag a projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, o ID completo é //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: a localização do recurso. Se você estiver anexando uma tag a um recurso global, como uma pasta ou um projeto, omita essa flag. Se você estiver anexando uma tag a um recurso regional ou zonal, especifique o local, por exemplo: us-central1 (região) ou us-central1-a (zona).

Execute o seguinte comando:

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

Excluir chaves e valores de tags

Ao remover uma chave de tag ou uma definição de valor, verifique se a tag está separada do secret regional. Você precisa excluir os anexos de tag, chamados de vinculações de tag, antes de excluir a definição da tag. Para mais informações, consulte Excluir tags.

Condições e tags do Identity and Access Management

Você pode usar tags e condições do IAM para conceder vinculações de papéis condicionalmente aos usuários na sua hierarquia. Alterar ou excluir a tag anexada a um recurso removerá o acesso do usuário a esse recurso se uma política do IAM com vinculações de papéis condicionais tiver sido aplicada. Para mais informações, consulte Condições e tags do Identity and Access Management.

A seguir