View secret labels

View the labels of a secret

Code sample

C#

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.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;
using Google.Protobuf.Collections;
using Google.Protobuf.WellKnownTypes;
using System;

public class ViewSecretLabelsSample
{
    public Secret ViewSecretLabels(
      string projectId = "my-project", string secretId = "my-secret")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretName secretName = new SecretName(projectId, secretId);

        // Fetch the secret.
        Secret secret = client.GetSecret(secretName);

        // Get the secret's labels.
        MapField<string, string> secretLabels = secret.Labels;

        // Print the labels.
        foreach (var label in secret.Labels)
        {
            Console.WriteLine($"Annotation Key: {label.Key}, Annotation Value: {label.Value}");
        }
        return secret;
    }
}

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();

PHP

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 the Secret Manager client library.
use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient;
use Google\Cloud\SecretManager\V1\GetSecretRequest;

/**
 * @param string $projectId Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $secretId  Your secret ID (e.g. 'my-secret')
 */
function view_secret_labels(string $projectId, string $secretId): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

    // Build the resource name of the parent project.
    $name = $client->secretName($projectId, $secretId);

    // Build the request.
    $request = GetSecretRequest::build($name);

    // get the secret.
    $getSecret = $client->getSecret($request);

    // get the secret labels
    $labels = $getSecret->getLabels();

    // print the secret name
    printf('Get secret %s with labels:' . PHP_EOL, $getSecret->getName());
    // we can even loop over all the labels
    foreach ($labels as $key => $val) {
        printf("\t$key: $val" . PHP_EOL);
    }
}

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

Ruby

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.

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

What's next

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