View secret labels

View the labels of a secret

Code sample

Go

To learn how to install and use the client library for Secret Manager, see Secret Manager client libraries.

To authenticate to Secret Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To learn how to install and use the client library for Secret Manager, see Secret Manager client libraries.

To authenticate to Secret Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To learn how to install and use the client library for Secret Manager, see Secret Manager client libraries.

To authenticate to Secret Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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

To learn how to install and use the client library for Secret Manager, see Secret Manager client libraries.

To authenticate to Secret Manager, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

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]}")

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.