Criar ou atualizar rótulo secreto

Cria ou atualiza os rótulos de um secret

Exemplo de código

Go

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 (
	"context"
	"fmt"
	"io"

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

// createUpdateSecretLabel updates the labels about an existing secret.
// If the label key exists, it updates the label, otherwise it creates a new one.
func createUpdateSecretLabel(w io.Writer, name string) error {
	// name := "projects/my-project/secrets/my-secret"

	labelKey := "labelkey"
	labelValue := "updatedlabelvalue"

	// 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

	labels[labelKey] = labelValue

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

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

Java

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 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.util.FieldMaskUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CreateUpdateSecretLabel {

  public static void createUpdateSecretLabel() 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 added/updated
    String labelKey = "your-label-key";
    // This is the value of the label to be added/updated
    String labelValue = "your-label-value";
    createUpdateSecretLabel(projectId, secretId, labelKey, labelValue);
  }

  // Update an existing secret, by creating a new label or updating an existing label.
  public static Secret createUpdateSecretLabel(
       String projectId, String secretId, String labelKey, String labelValue) 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());

      // Add a new label key and value.
      existingLabelsMap.put(labelKey, labelValue);

      // 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 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.

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

// 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 createUpdateSecretLabel() {
  const oldSecret = await getSecret();
  oldSecret.labels[labelKey] = labelValue;
  const [secret] = await client.updateSecret({
    secret: {
      name: name,
      labels: oldSecret.labels,
    },
    updateMask: {
      paths: ['labels'],
    },
  });

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

createUpdateSecretLabel();

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
from typing import Dict

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


def create_update_secret_label(
    project_id: str, secret_id: str, new_labels: Dict[str, str]
) -> secretmanager.UpdateSecretRequest:
    """
    Create or update 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

    # Update the labels
    for label_key in new_labels:
        labels[label_key] = new_labels[label_key]

    # 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.