List secrets

Lists all secrets.

Explore further

For detailed documentation that includes this code sample, see the following:

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;

public class ListSecretsSample
{
    public void ListSecrets(string projectId = "my-project")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        ProjectName projectName = new ProjectName(projectId);

        // Call the API.
        foreach (Secret secret in client.ListSecrets(projectName))
        {
            // ...
        }
    }
}

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"
	"google.golang.org/api/iterator"
)

// listSecrets lists all secrets in the given project.
func listSecrets(w io.Writer, parent string) error {
	// parent := "projects/my-project"

	// 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.ListSecretsRequest{
		Parent: parent,
	}

	// Call the API.
	it := client.ListSecrets(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}

		if err != nil {
			return fmt.Errorf("failed to list secrets: %w", err)
		}

		fmt.Fprintf(w, "Found secret %s\n", resp.Name)
	}

	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.ProjectName;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient.ListSecretsPagedResponse;
import java.io.IOException;

public class ListSecrets {

  public static void listSecrets() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    listSecrets(projectId);
  }

  // List all secrets for a project
  public static void listSecrets(String projectId) 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. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) {
      // Build the parent name.
      ProjectName projectName = ProjectName.of(projectId);

      // Get all secrets.
      ListSecretsPagedResponse pagedResponse = client.listSecrets(projectName);

      // List all secrets.
      pagedResponse
          .iterateAll()
          .forEach(
              secret -> {
                System.out.printf("Secret %s\n", secret.getName());
              });
    }
  }
}

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';

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

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

async function listSecrets() {
  const [secrets] = await client.listSecrets({
    parent: parent,
  });

  secrets.forEach(secret => {
    const policy = secret.replication.userManaged
      ? secret.replication.userManaged
      : secret.replication.automatic;
    console.log(`${secret.name} (${policy})`);
  });
}

listSecrets();

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\ListSecretsRequest;

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

    // Build the resource name of the parent secret.
    $parent = $client->projectName($projectId);

    // Build the request.
    $request = ListSecretsRequest::build($parent);

    // List all secrets.
    foreach ($client->listSecrets($request) as $secret) {
        printf('Found secret %s', $secret->getName());
    }
}

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.

def list_secrets(project_id: str) -> None:
    """
    List all secrets in the given project.
    """

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

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

    # Build the resource name of the parent project.
    parent = f"projects/{project_id}"

    # List all secrets.
    for secret in client.list_secrets(request={"parent": parent}):
        print(f"Found secret: {secret.name}")

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.

# project_id = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")

# Require the Secret Manager client library.
require "google/cloud/secret_manager"

# Create a Secret Manager client.
client = Google::Cloud::SecretManager.secret_manager_service

# Build the resource name of the parent.
parent = client.project_path project: project_id

# Get the list of secrets.
list = client.list_secrets parent: parent

# Print out all secrets.
list.each do |secret|
  puts "Got secret #{secret.name}"
end

What's next

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