Excluir rótulo secreto

Exclui o rótulo de um secret

Exemplo de código

Go

Para aprender a instalar e usar a biblioteca de cliente do Secret Manager, consulte Bibliotecas de cliente do Secret Manager.

Para autenticar no Secret Manager, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
	"google.golang.org/genproto/protobuf/field_mask"
)

// deleteSecret updates the metadata about an existing secret and remove an existing label.
func deleteSecretLabel(w io.Writer, name string) error {
	// name := "projects/my-project/secrets/my-secret"

	labelKey := "labelkey"

	// 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 to get the secret.
	req := &secretmanagerpb.GetSecretRequest{
		Name: name,
	}

	// Call the API.
	result, err := client.GetSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get secret: %w", err)
	}

	labels := result.Labels

	delete(labels, labelKey)

	// Build the request to update the secret.
	updateReq := &secretmanagerpb.UpdateSecretRequest{
		Secret: &secretmanagerpb.Secret{
			Name:   name,
			Labels: labels,
		},
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{"labels"},
		},
	}

	// Call the API.
	updateResult, err := client.UpdateSecret(ctx, updateReq)
	if err != nil {
		return fmt.Errorf("failed to update secret: %w", err)
	}
	fmt.Fprintf(w, "Updated secret: %s\n", updateResult.Name)
	return nil
}

Java

Para aprender a instalar e usar a biblioteca de cliente do Secret Manager, consulte Bibliotecas de cliente do Secret Manager.

Para autenticar no Secret Manager, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretName;
import com.google.protobuf.FieldMask;
import com.google.protobuf.FieldMaskOrBuilder;
import com.google.protobuf.util.FieldMaskUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class DeleteSecretLabel {

  public static void deleteSecretLabel() 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 label to be deleted
    String labelKey = "your-label-key";
    deleteSecretLabel(projectId, secretId, labelKey);
  }

  // Update an existing secret, by deleting a label.
  public static Secret deleteSecretLabel(
                     String projectId, String secretId, String labelKey) 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.
      SecretName secretName = SecretName.of(projectId, secretId);

      // Get the existing secret
      Secret existingSecret = client.getSecret(secretName);

      Map<String, String> existingLabelsMap = 
              new HashMap<String, String>(existingSecret.getLabels());
      existingLabelsMap.remove(labelKey);

      // Build the updated secret.
      Secret secret =
          Secret.newBuilder()
              .setName(secretName.toString())
              .putAllLabels(existingLabelsMap)
              .build();

      // Build the field mask.
      FieldMask fieldMask = FieldMaskUtil.fromString("labels");

      // Update the secret.
      Secret updatedSecret = client.updateSecret(secret, fieldMask);
      System.out.printf("Updated secret %s\n", updatedSecret.getName());

      return updatedSecret;
    }
  }
}

Node.js

Para aprender a instalar e usar a biblioteca de cliente do Secret Manager, consulte Bibliotecas de cliente do Secret Manager.

Para autenticar no Secret Manager, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const name = 'projects/my-project/secrets/my-secret';
// const labelKey = 'secretmanager';

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

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

async function getSecret() {
  const [secret] = await client.getSecret({
    name: name,
  });

  return secret;
}

async function deleteSecretLabel() {
  const oldSecret = await getSecret();
  delete oldSecret.labels[labelKey];
  const [secret] = await client.updateSecret({
    secret: {
      name: name,
      labels: oldSecret.labels,
    },
    updateMask: {
      paths: ['labels'],
    },
  });

  console.info(`Updated secret ${secret.name}`);
}

deleteSecretLabel();

Python

Para saber como instalar e usar a biblioteca de cliente do Secret Manager, consulte Bibliotecas de cliente do Secret Manager.

Para autenticar no Secret Manager, configure o Application Default Credentials. Para mais informações, consulte Configurar a autenticação para um ambiente de desenvolvimento local.

import argparse

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


def delete_secret_label(
    project_id: str, secret_id: str, label_key: str
) -> secretmanager.UpdateSecretRequest:
    """
    Delete a label on an existing secret.
    """

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

    # Build the resource name of the secret.
    name = client.secret_path(project_id, secret_id)

    # Get the secret.
    response = client.get_secret(request={"name": name})

    labels = response.labels

    # Delete the label
    labels.pop(label_key, None)

    # Update the secret.
    secret = {"name": name, "labels": labels}
    update_mask = {"paths": ["labels"]}
    response = client.update_secret(
        request={"secret": secret, "update_mask": update_mask}
    )

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

    return response

A seguir

Para pesquisar e filtrar exemplos de código de outros produtos do Google Cloud, consulte a pesquisa de exemplos de código do Google Cloud.