Creare e gestire i tag per i secret regionali

Questa guida descrive come creare e gestire i tag nei secret regionali. Puoi utilizzare i tag per raggruppare i secret di Secret Manager correlati e memorizzare i metadati di queste risorse in base ai tag.

Informazioni sui tag

Un tag è una coppia chiave-valore che può essere collegata a una risorsa all'interno di Google Cloud. Puoi utilizzare i tag per consentire o negare in modo condizionale i criteri a seconda che una risorsa abbia un tag specifico. Ad esempio, puoi concedere in modo condizionale i ruoli IAM (Identity and Access Management) a seconda che una risorsa abbia un tag specifico. Per saperne di più, consulta la panoramica dei tag.

I tag vengono collegati alle risorse creando una risorsa di associazione dei tag che collega il valore alla risorsa Google Cloud .

Autorizzazioni obbligatorie

Per ottenere le autorizzazioni necessarie per gestire i tag, chiedi all'amministratore di concederti i seguenti ruoli IAM:

  • Tag Viewer (roles/resourcemanager.tagViewer) sulle risorse a cui sono collegati i tag
  • Visualizza e gestisci i tag a livello di organizzazione: Visualizzatore organizzazione (roles/resourcemanager.organizationViewer) sull'organizzazione
  • Crea, aggiorna ed elimina le definizioni dei tag: Amministratore tag (roles/resourcemanager.tagAdmin) nella risorsa per cui stai creando, aggiornando o eliminando i tag
  • Associa e rimuovi i tag dalle risorse: Utente tag (roles/resourcemanager.tagUser) sul valore del tag e sulle risorse a cui stai associando o rimuovendo il valore del tag

Per saperne di più sulla concessione dei ruoli, consulta Gestisci l'accesso a progetti, cartelle e organizzazioni.

Potresti anche riuscire a ottenere le autorizzazioni richieste tramite i ruoli personalizzati o altri ruoli predefiniti.

Per collegare tag ai secret di Secret Manager, devi disporre del ruolo Amministratore Secret Manager (roles/secretmanager.admin).

Crea chiavi e valori dei tag

Prima di poter allegare un tag, devi crearne uno e configurarne il valore. Per ulteriori informazioni, vedi Creare un tag e Aggiungere un valore del tag.

Aggiungere tag durante la creazione della risorsa

Puoi aggiungere tag quando crei secret regionali. In questo modo puoi fornire metadati essenziali per le tue risorse e consentire una migliore organizzazione, un migliore monitoraggio dei costi e l'applicazione automatica delle norme.

Console

  1. Vai alla pagina Secret Manager nella console Google Cloud .
  2. Vai a Secret Manager

  3. Nella pagina Secret Manager, fai clic sulla scheda Secret regionali.
  4. Seleziona l'opzione per creare un nuovo secret regionale.
  5. Fai clic su Gestisci tag.
  6. Se la tua organizzazione non viene visualizzata nel riquadro Gestisci tag, fai clic su Seleziona ambito per i tag e seleziona la tua organizzazione o il tuo progetto.
  7. Fai clic su Aggiungi tag.
  8. Seleziona la chiave e il valore del tag dall'elenco. Puoi filtrare l'elenco utilizzando le parole chiave.
  9. Fai clic su Salva. La sezione Tag viene aggiornata con le informazioni sui tag.
  10. Crea il secret regionale. Il nuovo secret regionale viene creato con i tag forniti.

gcloud

Prima di utilizzare i dati dei comandi riportati di seguito, effettua le seguenti sostituzioni:

  • SECRET_ID: l'identificatore univoco del secret.
  • LOCATION: la posizione del secret.
  • TAG_KEY: l'ID permanente o il nome con spazio dei nomi della chiave del tag allegata, ad esempio tagKeys/567890123456.
  • TAG_VALUE: l'ID permanente o il nome con spazio dei nomi del valore del tag allegato, ad esempio tagValues/567890123456.

Specifica più tag separandoli con una virgola, ad esempio TAGKEY1=TAGVALUE1,TAGKEY2=TAGVALUE2.

Esegui questo 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

Prima di utilizzare i dati della richiesta, apporta le sostituzioni seguenti:

  • LOCATION: la posizione del secret
  • PROJECT_ID: l'ID progetto
  • SECRET_ID: l'identificatore univoco del secret
  • TAGKEY_NAME: l'ID permanente o il nome con spazio dei nomi della chiave del tag allegata, ad esempio tagKeys/567890123456.
  • TAGVALUE_NAME: l'ID permanente o il nome con spazio dei nomi del valore del tag allegato, ad esempio tagValues/567890123456.

Metodo HTTP e URL:

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

Corpo JSON della richiesta:

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

Per inviare la richiesta, scegli una di queste opzioni:

curl

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

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

Salva il corpo della richiesta in un file denominato request.json, quindi esegui il comando seguente:

$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

Dovresti ricevere un codice di stato riuscito (2xx) e una risposta vuota.

C#

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo C# e installare l'SDK C# Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito 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

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Go e installare l'SDK Go di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito 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

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Java e installare l'SDK Java di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito 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

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Node.js e installare l'SDK Node.js di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito 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

Per eseguire questo codice, scopri prima come utilizzare PHP su Google Cloud e installa l'SDK PHP di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito 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

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Python e installare l'SDK Python di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito 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

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Ruby e installare l'SDK Ruby di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito 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

Aggiungere tag alle risorse esistenti

Per aggiungere un tag ai secret regionali esistenti:

Console

  1. Vai alla pagina Secret Manager nella console Google Cloud .
  2. Vai a Secret Manager

  3. Seleziona il secret regionale a cui vuoi allegare un tag.
  4. Fai clic su Tag.
  5. Se la tua organizzazione non viene visualizzata nel riquadro Tag, fai clic su Seleziona ambito. Seleziona la tua organizzazione e fai clic su Apri.
  6. Fai clic su Aggiungi tag.
  7. Seleziona la chiave e il valore del tag dall'elenco. Puoi filtrare l'elenco utilizzando le parole chiave.
  8. Fai clic su Salva.
  9. Nella finestra di dialogo Conferma, fai clic su Conferma per allegare il tag.
  10. Una notifica conferma che i tag sono stati aggiornati.

gcloud

Per collegare un tag a un secret regionale, devi creare una risorsa di associazione tag utilizzando il comando gcloud resource-manager tags bindings create:

Prima di utilizzare i dati dei comandi riportati di seguito, effettua le seguenti sostituzioni:

  • TAGVALUE_NAME: l'ID permanente o il nome con spazio dei nomi del valore tag allegato, ad esempio tagValues/567890123456.
  • RESOURCE_ID è l'ID completo della risorsa, incluso il nome di dominio dell'API per identificare il tipo di risorsa (//secretmanager.googleapis.com/). Ad esempio, per collegare un tag a projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, l'ID completo è //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: la posizione della risorsa. Se stai collegando un tag a una risorsa globale, come una cartella o un progetto, ometti questo flag. Se colleghi un tag a una risorsa regionale o di zona, devi specificare la località, ad esempio us-central1 (regione) o us-central1-a (zona).

Esegui questo 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

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Node.js e installare l'SDK Node.js di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito 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

Per eseguire questo codice, scopri prima come utilizzare PHP su Google Cloud e installa l'SDK PHP di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito 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

Per eseguire questo codice, devi innanzitutto configurare un ambiente di sviluppo Python e installare l'SDK Python di Secret Manager. Su Compute Engine o GKE, devi autenticarti con l'ambito 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

Elenca i tag collegati alle risorse

Puoi visualizzare un elenco di associazioni di tag direttamente collegate o ereditate dal secret regionale.

Console

  1. Vai alla pagina Secret Manager nella console Google Cloud .
  2. Vai a Secret Manager

  3. I tag vengono visualizzati nella colonna Tag del segreto.

gcloud

Per ottenere un elenco di associazioni di tag collegate a una risorsa, utilizza il comando gcloud resource-manager tags bindings list:

Prima di utilizzare i dati dei comandi riportati di seguito, effettua le seguenti sostituzioni:

  • RESOURCE_ID è l'ID completo della risorsa, incluso il nome di dominio dell'API per identificare il tipo di risorsa (//secretmanager.googleapis.com/). Ad esempio, per collegare un tag a projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, l'ID completo è //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: la posizione della risorsa. Se stai visualizzando un tag collegato a una risorsa globale, ad esempio una cartella o un progetto, ometti questo flag. Se visualizzi un tag associato a una risorsa regionale o di zona, devi specificare la località, ad esempio us-central1 (regione) o us-central1-a (zona).

Esegui questo 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

Dovresti ricevere una risposta simile alla seguente:

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

Scollegare i tag dalle risorse

Puoi scollegare i tag che sono stati collegati direttamente a un secret regionale. I tag ereditati possono essere sostituiti collegando un tag con la stessa chiave e un valore diverso, ma non possono essere scollegati.

Console

  1. Vai alla pagina Secret Manager nella console Google Cloud .
  2. Vai a Secret Manager

  3. Seleziona il secret regionale da cui vuoi rimuovere un tag.
  4. Fai clic su Tag.
  5. Nel riquadro Tag, accanto al tag da scollegare, fai clic su Elimina elemento.
  6. Fai clic su Salva.
  7. Nella finestra di dialogo Conferma, fai clic su Conferma per staccare il tag.

Una notifica conferma che i tag sono stati aggiornati.

gcloud

Per eliminare un'associazione di tag, utilizza il comando gcloud resource-manager tags bindings delete:

Prima di utilizzare i dati dei comandi riportati di seguito, effettua le seguenti sostituzioni:

  • TAGVALUE_NAME: l'ID permanente o il nome con spazio dei nomi del valore tag allegato, ad esempio tagValues/567890123456.
  • RESOURCE_ID è l'ID completo della risorsa, incluso il nome di dominio dell'API per identificare il tipo di risorsa (//secretmanager.googleapis.com/). Ad esempio, per collegare un tag a projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID, l'ID completo è //secretmanager.googleapis.com/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID.
  • LOCATION: la posizione della risorsa. Se stai collegando un tag a una risorsa globale, come una cartella o un progetto, ometti questo flag. Se colleghi un tag a una risorsa regionale o di zona, devi specificare la località, ad esempio us-central1 (regione) o us-central1-a (zona).

Esegui questo 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

Eliminare chiavi e valori dei tag

Quando rimuovi una definizione di chiave o valore del tag, assicurati che il tag sia scollegato dal secret regionale. Prima di eliminare la definizione del tag, devi eliminare gli allegati esistenti, chiamati associazioni di tag. Per ulteriori informazioni, vedi Eliminazione dei tag.

Condizioni e tag di Identity and Access Management

Puoi utilizzare i tag e le condizioni IAM per concedere in modo condizionale le associazioni di ruoli agli utenti della gerarchia. La modifica o l'eliminazione del tag associato a una risorsa può rimuovere l'accesso utente a quella risorsa se è stata applicata una policy IAM con associazioni di ruoli condizionali. Per saperne di più, consulta Condizioni e tag di Identity and Access Management.

Passaggi successivi