Cómo ver las etiquetas de Secret

Cómo ver las etiquetas de un Secret

Muestra de código

Go

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Secret Manager, consulta la sección sobre bibliotecas cliente de Secret Manager.

Para autenticarte en Secret Manager, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import (
	"context"
	"fmt"
	"io"

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

// getSecret gets information about the given secret. This only returns metadata
// about the secret container, not any secret material.
func viewSecretLabels(w io.Writer, name string) error {
	// name := "projects/my-project/secrets/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.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
	fmt.Fprintf(w, "Found secret %s\n", result.Name)

	for key, value := range labels {
		fmt.Fprintf(w, "Label key %s : Label Value %s", key, value)
	}
	return nil
}

Java

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Secret Manager, consulta la sección sobre bibliotecas cliente de Secret Manager.

Para autenticarte en Secret Manager, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretName;
import java.io.IOException;
import java.util.Map;

public class ViewSecretLabels {

  public static void viewSecretLabels() 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 whose labels to view
    String secretId = "your-secret-id";
    viewSecretLabels(projectId, secretId);
  }

  // View the labels of an existing secret.
  public static Map<String, String> viewSecretLabels(
      String projectId,
      String secretId
  ) 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);

      // Create the secret.
      Secret secret = client.getSecret(secretName);

      Map<String, String> labels = secret.getLabels();

      System.out.printf("Secret %s \n", secret.getName());

      for (Map.Entry<String, String> label : labels.entrySet()) {
        System.out.printf("Label key : %s, Label Value : %s\n", label.getKey(), label.getValue());
      }

      return secret.getLabels();
    }
  }
}

Node.js

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Secret Manager, consulta la sección sobre bibliotecas cliente de Secret Manager.

Para autenticarte en Secret Manager, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

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

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

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

  for (const key in secret.labels) {
    console.log(`${key} : ${secret.labels[key]}`);
  }
}

getSecretLabels();

Python

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Secret Manager, consulta la sección sobre bibliotecas cliente de Secret Manager.

Para autenticarte en Secret Manager, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import argparse

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


def view_secret_labels(project_id: str, secret_id: str) -> None:
    """
    List all secret labels in the given secret.
    """
    # Create the Secret Manager client.
    client = secretmanager.SecretManagerServiceClient()

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

    response = client.get_secret(request={"name": name})

    print(f"Got secret {response.name} with labels :")
    for key in response.labels:
        print(f"{key} : {response.labels[key]}")

Ruby

Para obtener información sobre cómo instalar y usar la biblioteca cliente de Secret Manager, consulta la sección sobre bibliotecas cliente de Secret Manager.

Para autenticarte en Secret Manager, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

require "google/cloud/secret_manager"

##
# View labels of a secret.
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param secret_id [String] Your secret name (e.g. "my-secret")
#
def view_secret_labels project_id:, secret_id:
  # Create a Secret Manager client.
  client = Google::Cloud::SecretManager.secret_manager_service

  # Build the resource name of the secret.
  name = client.secret_path project: project_id, secret: secret_id

  # Get the existing secret.
  existing_secret = client.get_secret name: name

  # Get the existing secret's labels.
  existing_secret_labels = existing_secret.labels.to_h

  # Print the secret name and the labels.
  puts "Secret: #{existing_secret.name}"
  existing_secret_labels.each do |key, value|
    puts "Label Key: #{key}, Label Value: #{value}"
  end
end

¿Qué sigue?

Para buscar y filtrar muestras de código para otros productos de Google Cloud , consulta el navegador de muestras deGoogle Cloud .