List secret versions containing a filter

Shows how to list all secret versions and metadata for a secret with a specified 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"
)

// listSecretVersionsWithFilter lists all filter-matching secret versions in the given
// secret and their metadata.
func listSecretVersionsWithFilter(w io.Writer, parent string, filter string) error {
	// parent := "projects/my-project/secrets/my-secret"
	// Follow https://cloud.google.com/secret-manager/docs/filtering
	// for filter syntax and examples.
	// filter := "create_time>2021-01-01T00:00:00Z"

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

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

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

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

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

public class ListSecretVersionsWithFilter {

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

  // List all secret versions for a secret.
  public static void listSecretVersions(String projectId, String secretId, 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.
      SecretName secretName = SecretName.of(projectId, secretId);

      // Get filtered versions.
      ListSecretVersionsRequest request =
          ListSecretVersionsRequest.newBuilder()
              .setParent(secretName.toString())
              .setFilter(filter)
              .build();

      ListSecretVersionsPagedResponse pagedResponse = client.listSecretVersions(request);

      // List all versions and their state.
      pagedResponse
          .iterateAll()
          .forEach(
              version -> {
                System.out.printf("Secret version %s, %s\n", version.getName(), version.getState());
              });
    }
  }
}

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_secret_versions_with_filter(
    project_id: str, secret_id: str, filter_str: str = "state:ENABLED"
) -> None:
    """
    List all secret versions in the given secret and their metadata.

    Args:
      project_id: Parent project id
      secret_id: Parent secret id
      filter_str: Secret version 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 secret.
    parent = client.secret_path(project_id, secret_id)

    # List all secret versions.
    for version in client.list_secret_versions(
        request={"parent": parent, "filter": filter_str}
    ):
        print(f"Found secret version: {version.name}")

What's next

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