Crie e faça a gestão de etiquetas

Este guia descreve como criar e gerir etiquetas em segredos do Secret Manager. Pode usar etiquetas para agrupar segredos relacionados do Secret Manager e armazenar metadados sobre esses recursos com base nas respetivas etiquetas.

Acerca das etiquetas

Uma etiqueta é um par de chave-valor que pode ser anexado a um recurso no âmbito do Google Cloud. Pode usar etiquetas para permitir ou negar condicionalmente políticas com base no facto de um recurso ter uma etiqueta específica. Por exemplo, pode conceder condicionalmente funções de gestão de identidade e de acesso (IAM) com base no facto de um recurso ter uma etiqueta específica. Para mais informações, consulte o artigo Vista geral das etiquetas.

As etiquetas são anexadas a recursos através da criação de um recurso de associação de etiquetas que associa o valor ao recurso. Google Cloud

Autorizações necessárias

Para receber as autorizações de que precisa para gerir etiquetas, peça ao seu administrador que lhe conceda as seguintes funções de IAM:

  • Visualizador de etiquetas (roles/resourcemanager.tagViewer) nos recursos aos quais as etiquetas estão anexadas
  • Ver e gerir etiquetas ao nível da organização: Visitante da organização (roles/resourcemanager.organizationViewer) na organização
  • Criar, atualizar e eliminar definições de etiquetas: Administrador de etiquetas (roles/resourcemanager.tagAdmin) no recurso para o qual está a criar, atualizar ou eliminar etiquetas
  • Anexar e remover etiquetas de recursos: Utilizador de etiquetas (roles/resourcemanager.tagUser) no valor da etiqueta e nos recursos aos quais está a anexar ou remover o valor da etiqueta

Para mais informações sobre a atribuição de funções, consulte o artigo Faça a gestão do acesso a projetos, pastas e organizações.

Também pode conseguir as autorizações necessárias através de funções personalizadas ou outras funções predefinidas.

Para anexar etiquetas a segredos do Secret Manager, precisa da função Administrador do Secret Manager (roles/secretmanager.admin).

Crie chaves e valores de etiquetas

Antes de poder anexar uma etiqueta, tem de criar uma etiqueta e configurar o respetivo valor. Para mais informações, consulte os artigos Criar uma etiqueta e Adicionar um valor de etiqueta.

Adicione etiquetas durante a criação de recursos

Pode adicionar etiquetas quando cria segredos. Ao fazê-lo, pode fornecer metadados essenciais para os seus recursos e permite uma melhor organização, acompanhamento de custos e aplicação automática de políticas.

Consola

  1. Aceda à página Secret Manager na Google Cloud consola.
  2. Aceda ao Secret Manager

  3. Selecione a opção para criar um novo secret.
  4. Clique em Gerir etiquetas.
  5. Se a sua organização não aparecer no painel Gerir etiquetas, clique em Selecionar âmbito para etiquetas e selecione a sua organização ou projeto.
  6. Clique em Adicionar etiqueta.
  7. Selecione a chave de etiqueta e o valor da etiqueta na lista. Pode filtrar a lista através de palavras-chave.
  8. Clique em Guardar. A secção Etiquetas é atualizada com as informações das etiquetas.
  9. Crie o seu segredo. O novo segredo é criado com as etiquetas fornecidas.

gcloud

Antes de usar qualquer um dos dados de comandos abaixo, faça as seguintes substituições:

  • SECRET_ID: o identificador exclusivo do segredo.
  • TAG_KEY: o ID permanente ou o nome com espaço de nomes da chave de etiqueta anexada, por exemplo, tagKeys/567890123456.
  • TAG_VALUE: o ID permanente ou o nome com espaço de nomes do valor da etiqueta anexado, por exemplo, tagValues/567890123456.

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

Execute o seguinte comando:

Linux, macOS ou Cloud Shell

gcloud secrets create SECRET_ID --tags=TAG_KEY=TAG_VALUE

Windows (PowerShell)

gcloud secrets create SECRET_ID --tags=TAG_KEY=TAG_VALUE

Windows (cmd.exe)

gcloud secrets create SECRET_ID --tags=TAG_KEY=TAG_VALUE

REST

Antes de usar qualquer um dos dados do pedido, faça as seguintes substituições:

  • PROJECT_ID: o ID do projeto
  • SECRET_ID: o identificador exclusivo do segredo
  • TAGKEY_NAME: o ID permanente ou o nome com espaço de nomes da chave de etiqueta anexada, por exemplo, tagKeys/567890123456.
  • TAGVALUE_NAME: o ID permanente ou o nome com espaço de nomes do valor da etiqueta anexado, por exemplo, tagValues/567890123456.

Método HTTP e URL:

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

Corpo JSON do pedido:

{
  "replication": {
    "automatic": {}
  },
  "tags": {
    "TAGKEY_NAME": "TAGVALUE_NAME"
  }
}

Para enviar o seu pedido, escolha uma destas opções:

curl

Guarde o corpo do pedido num ficheiro com o nome request.json, e execute o seguinte 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.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID"

PowerShell

Guarde o corpo do pedido num ficheiro com o nome request.json, e execute o seguinte 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.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID" | Select-Object -Expand Content

Deve receber um código de estado de êxito (2xx) e uma resposta vazia.

C#

Para executar este código, primeiro configure um ambiente de programação em C# e instale o SDK em C# do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o âmbito cloud-platform.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;
using System.Collections.Generic;

public class CreateSecretWithTagsSample
{
    public Secret CreateSecretWithTags(
      string projectId = "my-project", string secretId = "my-secret", string tagKeyName = "tagKey/value", string tagValueName = "tagValue/value")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the parent resource name.
        ProjectName projectName = new ProjectName(projectId);

        // Build the secret.
        Secret secret = new Secret
        {
            Replication = new Replication
            {
                Automatic = new Replication.Types.Automatic(),
            },
            Tags =
            {
              { tagKeyName, tagValueName }
            },
        };

        // Call the API.
        Secret createdSecret = client.CreateSecret(projectName, secretId, secret);
        return createdSecret;
    }
}

Go

Para executar este código, primeiro configure um ambiente de desenvolvimento Go e instale o SDK Go do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o âmbito cloud-platform.

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
)

// createSecretWithTags creates a new secret with the given name and tags.
func createSecretWithTags(w io.Writer, parent, id, tagKey, tagValue string) error {
	// parent := "projects/my-project"
	// id := "my-secret"

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	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: id,
		Secret: &secretmanagerpb.Secret{
			Replication: &secretmanagerpb.Replication{
				Replication: &secretmanagerpb.Replication_Automatic_{
					Automatic: &secretmanagerpb.Replication_Automatic{},
				},
			},
			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 este código, primeiro configure um ambiente de desenvolvimento Java e instale o SDK Java do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o âmbito cloud-platform.

import com.google.cloud.secretmanager.v1.ProjectName;
import com.google.cloud.secretmanager.v1.Replication;
import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import java.io.IOException;

public class CreateSecretWithTags {

  public static void createSecretWithTags() throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // This is the id of the GCP project
    String projectId = "your-project-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";
    createSecretWithTags(projectId, secretId, tagKey, tagValue);
  }

  // Create a secret with tags.
  public static Secret createSecretWithTags(
       String projectId, String secretId, String tagKey, String tagValue) throws IOException {
    // 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()) {

      // Build the name.
      ProjectName projectName = ProjectName.of(projectId);

      // Build the secret to create with tags.
      Secret secret =
          Secret.newBuilder()
          .setReplication(
              Replication.newBuilder()
                  .setAutomatic(Replication.Automatic.newBuilder().build())
                  .build())
          .putTags(tagKey, tagValue)
          .build();

      // Create the secret.
      Secret createdSecret = client.createSecret(projectName, secretId, secret);
      System.out.printf("Created secret with Tags %s\n", createdSecret.getName());
      return createdSecret;
    }
  }
}

Node.js

Para executar este 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, tem de autenticar-se com o âmbito cloud-platform.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const secretId = 'my-secret';
// const tagKey = 'tagKeys/281475012216835';
// const tagValue = 'tagValues/281476592621530';
const parent = `projects/${projectId}`;

// Imports the library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Instantiates a client
const client = new SecretManagerServiceClient();

async function createSecretWithTags() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: {
      replication: {
        automatic: {},
      },
      tags: {
        [tagKey]: tagValue,
      },
    },
  });

  console.log(`Created secret ${secret.name}`);
}

createSecretWithTags();

PHP

Para executar este código, saiba primeiro como usar o PHP no Google Cloud e instale o SDK PHP do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o âmbito cloud-platform.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\CreateSecretRequest;
use Google\Cloud\SecretManager\V1\Replication;
use Google\Cloud\SecretManager\V1\Replication\Automatic;
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 $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_secret_with_tags(string $projectId, string $secretId, string $tagKey, string $tagValue): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

    // Build the resource name of the parent project.
    $parent = $client->projectName($projectId);

    $secret = new Secret([
        'replication' => new Replication([
            'automatic' => new Automatic(),
        ]),
    ]);

    // 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 este código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK Python do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o âmbito cloud-platform.

import argparse

# Import the Secret Manager client library.
from google.cloud import secretmanager


def create_secret_with_tags(
    project_id: str,
    secret_id: str,
    tag_key: str,
    tag_value: str,
) -> secretmanager.Secret:
    """
    Create a new 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.
    """

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent project.
    parent = f"projects/{project_id}"

    # Create the secret.
    response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
            "secret": {
                "replication": {"automatic": {}},
                "tags": {
                    tag_key: tag_value
                }
            },
        }
    )

    # Print the new secret name.
    print(f"Created secret: {response.name}")

    return response

Ruby

Para executar este código, primeiro configure um ambiente de desenvolvimento Ruby e instale o SDK Ruby do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o âmbito cloud-platform.

require "google/cloud/secret_manager"

##
# Create a secret with tags.
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @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_secret_with_tags project_id:, secret_id:, tag_key:, tag_value:
  # Create a Secret Manager client.
  client = Google::Cloud::SecretManager.secret_manager_service

  # Build the resource name of the parent project.
  parent = client.project_path project: project_id

  # Create the secret.
  secret = client.create_secret(
    parent:    parent,
    secret_id: secret_id,
    secret:    {
      replication: {
        automatic: {}
      },
      tags: {
        tag_key.name => tag_value.name
      }
    }
  )

  # Print the new secret name.
  puts "Created secret with tag: #{secret.name}"
end

Adicione etiquetas a recursos existentes

Para adicionar uma etiqueta a segredos existentes, siga estes passos:

Consola

  1. Aceda à página Secret Manager na Google Cloud consola.
  2. Aceda ao Secret Manager

  3. Selecione o segredo ao qual quer anexar uma etiqueta.
  4. Clique em Etiquetas.
  5. Se a sua organização não aparecer no painel Etiquetas, clique em Selecionar âmbito. Selecione a sua organização e clique em Abrir.
  6. Clique em Adicionar etiqueta.
  7. Selecione a chave de etiqueta e o valor da etiqueta na lista. Pode filtrar a lista através de palavras-chave.
  8. Clique em Guardar.
  9. Na caixa de diálogo Confirmar, clique em Confirmar para anexar a etiqueta.
  10. É apresentada uma notificação a confirmar que as etiquetas foram atualizadas.

gcloud

Para anexar uma etiqueta a um segredo, tem de criar um recurso de associação de etiquetas através do comando gcloud resource-manager tags bindings create:

Antes de usar qualquer um dos dados de comandos abaixo, faça as seguintes substituições:

  • TAGVALUE_NAME: o ID permanente ou o nome com espaço de nomes do valor da etiqueta anexado, por exemplo, tagValues/567890123456.
  • RESOURCE_ID é o ID completo do recurso, incluindo o nome do domínio da API para identificar o tipo de recurso (//secretmanager.googleapis.com/). Por exemplo, para anexar uma etiqueta a /projects/PROJECT_ID/secrets/SECRET_ID, o ID completo é //secretmanager.googleapis.com/projects/PROJECT_ID/secrets/SECRET_ID.

Execute o seguinte comando:

Linux, macOS ou Cloud Shell

gcloud resource-manager tags bindings create \
    --tag-value=TAGVALUE_NAME \
    --parent=RESOURCE_ID

Windows (PowerShell)

gcloud resource-manager tags bindings create `
    --tag-value=TAGVALUE_NAME `
    --parent=RESOURCE_ID

Windows (cmd.exe)

gcloud resource-manager tags bindings create ^
    --tag-value=TAGVALUE_NAME ^
    --parent=RESOURCE_ID

Node.js

Para executar este 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, tem de autenticar-se com o âmbito cloud-platform.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const secretId = 'my-secret';
// const tagValue = 'tagValues/281476592621530';
const parent = `projects/${projectId}`;

// Imports the library
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');
const {TagBindingsClient} = require('@google-cloud/resource-manager').v3;

// Instantiates a client
const client = new SecretManagerServiceClient();
const resourcemanagerClient = new TagBindingsClient();

async function bindTagsToSecret() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: {
      replication: {
        automatic: {},
      },
    },
  });

  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);
}

bindTagsToSecret();

PHP

Para executar este código, saiba primeiro como usar o PHP no Google Cloud e instale o SDK PHP do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o âmbito cloud-platform.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\CreateSecretRequest;
use Google\Cloud\SecretManager\V1\Replication;
use Google\Cloud\SecretManager\V1\Replication\Automatic;
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 $secretId  Your secret ID (e.g. 'my-secret')
 * @param string $tagValue  Your tag value (e.g. 'tagValues/281476592621530')
 */
function bind_tags_to_secret(string $projectId, string $secretId, string $tagValue): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

    // Build the resource name of the parent project.
    $parent = $client->projectName($projectId);

    $secret = new Secret([
        'replication' => new Replication([
            'automatic' => new Automatic(),
        ]),
    ]);

    // 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());

    $tagBindingsClient = new TagBindingsClient();
    $tagBinding = (new TagBinding())
        ->setParent('//secretmanager.googleapis.com/' . $newSecret->getName())
        ->setTagValue($tagValue);

    // Build the binding 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 este código, primeiro configure um ambiente de desenvolvimento Python e instale o SDK Python do Secret Manager. No Compute Engine ou no GKE, tem de autenticar-se com o â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_secret(
    project_id: str,
    secret_id: str,
    tag_value: str,
) -> resourcemanager_v3.TagBinding:
    """
    Create a new 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.
    """

    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

    # Build the resource name of the parent project.
    parent = f"projects/{project_id}"

    # Create the secret.
    secret_response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
            "secret": {
                "replication": {"automatic": {}},
            },
        }
    )

    # Print the new secret name.
    print(f"Created secret: {secret_response.name}")

    # Create the resource manager client
    resource_manager_client = resourcemanager_v3.TagBindingsClient()

    # 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 etiquetas anexadas a recursos

Pode ver uma lista de associações de etiquetas diretamente anexadas ou herdadas do segredo.

Consola

  1. Aceda à página Secret Manager na Google Cloud consola.
  2. Aceda ao Secret Manager

  3. As etiquetas são apresentadas na coluna Etiquetas do segredo.

gcloud

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

Antes de usar qualquer um dos dados de comandos abaixo, faça as seguintes substituições:

  • RESOURCE_ID é o ID completo do recurso, incluindo o nome do domínio da API para identificar o tipo de recurso (//secretmanager.googleapis.com/). Por exemplo, para anexar uma etiqueta a /projects/PROJECT_ID/secrets/SECRET_ID, o ID completo é //secretmanager.googleapis.com/projects/PROJECT_ID/secrets/SECRET_ID.

Execute o seguinte comando:

Linux, macOS ou Cloud Shell

gcloud resource-manager tags bindings list \
    --parent=RESOURCE_ID

Windows (PowerShell)

gcloud resource-manager tags bindings list `
    --parent=RESOURCE_ID

Windows (cmd.exe)

gcloud resource-manager tags bindings list ^
    --parent=RESOURCE_ID

Deve receber uma resposta semelhante à seguinte:

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

Desassocie etiquetas de recursos

Pode desanexar etiquetas que tenham sido anexadas diretamente a um segredo. As etiquetas herdadas podem ser substituídas anexando uma etiqueta com a mesma chave e um valor diferente, mas não podem ser desanexadas.

Consola

  1. Aceda à página Secret Manager na Google Cloud consola.
  2. Aceda ao Secret Manager

  3. Selecione o segredo do qual quer remover uma etiqueta.
  4. Clique em Etiquetas.
  5. No painel Etiquetas, junto à etiqueta que quer desassociar, clique em Eliminar item.
  6. Clique em Guardar.
  7. Na caixa de diálogo Confirmar, clique em Confirmar para desanexar a etiqueta.

É apresentada uma notificação a confirmar que as etiquetas foram atualizadas.

gcloud

Para eliminar uma associação de etiqueta, use o comando gcloud resource-manager tags bindings delete:

Antes de usar qualquer um dos dados de comandos abaixo, faça as seguintes substituições:

  • TAGVALUE_NAME: o ID permanente ou o nome com espaço de nomes do valor da etiqueta anexado, por exemplo, tagValues/567890123456.
  • RESOURCE_ID é o ID completo do recurso, incluindo o nome do domínio da API para identificar o tipo de recurso (//secretmanager.googleapis.com/). Por exemplo, para anexar uma etiqueta a /projects/PROJECT_ID/secrets/SECRET_ID, o ID completo é //secretmanager.googleapis.com/projects/PROJECT_ID/secrets/SECRET_ID.

Execute o seguinte comando:

Linux, macOS ou Cloud Shell

gcloud resource-manager tags bindings delete \
    --tag-value=TAGVALUE_NAME \
    --parent=RESOURCE_ID

Windows (PowerShell)

gcloud resource-manager tags bindings delete `
    --tag-value=TAGVALUE_NAME `
    --parent=RESOURCE_ID

Windows (cmd.exe)

gcloud resource-manager tags bindings delete ^
    --tag-value=TAGVALUE_NAME ^
    --parent=RESOURCE_ID

Elimine chaves e valores de etiquetas

Quando remover uma definição de chave ou valor de etiqueta, certifique-se de que a etiqueta está desassociada do segredo. Tem de eliminar as associações de etiquetas existentes, denominadas associações de etiquetas, antes de eliminar a própria definição de etiqueta. Para mais informações, consulte o artigo Eliminar etiquetas.

Condições e etiquetas da gestão de identidade e de acesso

Pode usar etiquetas e condições de IAM para conceder condicionalmente associações de funções a utilizadores na sua hierarquia. A alteração ou a eliminação da etiqueta anexada a um recurso pode remover o acesso do utilizador a esse recurso se tiver sido aplicada uma política do IAM com associações de funções condicionais. Para mais informações, consulte o artigo Condições e etiquetas da gestão de identidade e de acesso.

O que se segue?