List secrets with a filter

Shows how to list all secrets in a project that match a filter.

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

// listSecretsWithFilter lists all filter-matching secrets in the given project.
func listSecretsWithFilter(w io.Writer, parent string, filter string) error {
	// parent := "projects/my-project"
	// Follow https://cloud.google.com/secret-manager/docs/filtering
	// for filter syntax and examples.
	// filter := "name:name-substring"

	// 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,
		Filter: filter,
	}

	// 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.ListSecretsRequest;
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 ListSecretsWithFilter {

  public static void listSecrets() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    // Follow https://cloud.google.com/secret-manager/docs/filtering
    // for filter syntax and examples.
    String filter = "name:your-secret-substring AND expire_time<2022-01-01T00:00:00Z";
    listSecrets(projectId, filter);
  }

  // List all secrets for a project
  public static void listSecrets(String projectId, String filter) 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 filtered secrets.
      ListSecretsRequest request =
          ListSecretsRequest.newBuilder()
              .setParent(projectName.toString())
              .setFilter(filter)
              .build();

      ListSecretsPagedResponse pagedResponse = client.listSecrets(request);

      // List all secrets.
      pagedResponse
          .iterateAll()
          .forEach(
              secret -> {
                System.out.printf("Secret %s\n", 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_with_filter(project_id: str, filter_str: str) -> None:
    """
    List all secrets in the given project.

    Args:
      project_id: Parent project id
      filter_str: Secret filter, constructing according to
                  https://cloud.google.com/secret-manager/docs/filtering
    """

    # 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, "filter": filter_str}):
        print(f"Found secret: {secret.name}")

What's next

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