Mostrar secretos regionales con filtro

Lista todos los secretos regionales con filtro

Investigar más

Para obtener documentación detallada que incluya este código de muestra, consulta lo siguiente:

Código de ejemplo

C#

Para saber cómo instalar y usar la biblioteca de cliente de Secret Manager, consulta el artículo Bibliotecas de cliente de Secret Manager.

Para autenticarte en Secret Manager, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;
using System;
using System.Collections.Generic;
using System.Linq;

public class ListRegionalSecretsWithFilterSample
{
    public List<Secret> ListRegionalSecretsWithFilter(
      string projectId = "my-project", string locationId = "my-location", string filter = "create_time>2024-01-01T00:00:00Z"
    )
    {
        // Create the Regional Secret Manager Client.
        SecretManagerServiceClient client = new SecretManagerServiceClientBuilder
        {
            Endpoint = $"secretmanager.{locationId}.rep.googleapis.com"
        }.Build();

        // Build the parent resource name.
        LocationName locationName = new LocationName(projectId, locationId);

        ListSecretsRequest request = new ListSecretsRequest
        {
            Parent = locationName.ToString(),
            Filter = filter,
        };

        // Call the API.
        List<Secret> secrets = client.ListSecrets(request).ToList();

        // Traverse the secret list.
        foreach (Secret secret in secrets)
        {
            Console.WriteLine($"Got regional secret : {secret.Name}");
        }

        return secrets;
    }
}

Go

Para saber cómo instalar y usar la biblioteca de cliente de Secret Manager, consulta el artículo Bibliotecas de cliente de Secret Manager.

Para autenticarte en Secret Manager, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
	"google.golang.org/api/iterator"
	"google.golang.org/api/option"
)

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

	// Create the client.
	ctx := context.Background()
	//Endpoint to send the request to regional server
	endpoint := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", locationId)
	client, err := secretmanager.NewClient(ctx, option.WithEndpoint(endpoint))

	if err != nil {
		return fmt.Errorf("failed to create regional secretmanager client: %w", err)
	}
	defer client.Close()

	parent := fmt.Sprintf("projects/%s/locations/%s", projectId, locationId)
	// 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 regional secrets: %w", err)
		}

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

	return nil
}

Java

Para saber cómo instalar y usar la biblioteca de cliente de Secret Manager, consulta el artículo Bibliotecas de cliente de Secret Manager.

Para autenticarte en Secret Manager, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

import com.google.cloud.secretmanager.v1.ListSecretsRequest;
import com.google.cloud.secretmanager.v1.LocationName;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient.ListSecretsPage;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient.ListSecretsPagedResponse;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import java.io.IOException;

public class ListRegionalSecretsWithFilter {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Your GCP project ID.
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // Filter to be applied. 
    // See 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";
    listRegionalSecretsWithFilter(projectId, locationId, filter);
  }

  // List all secrets for a project
  public static ListSecretsPage listRegionalSecretsWithFilter(
      String projectId, String locationId, String filter) throws IOException {

    // Endpoint to call the regional secret manager sever
    String apiEndpoint = String.format("secretmanager.%s.rep.googleapis.com:443", locationId);
    SecretManagerServiceSettings secretManagerServiceSettings =
        SecretManagerServiceSettings.newBuilder().setEndpoint(apiEndpoint).build();

    // Initialize the 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(secretManagerServiceSettings)) {
      // Build the parent name.
      LocationName parent = LocationName.of(projectId, locationId);

      // Get filtered secrets.
      ListSecretsRequest request =
          ListSecretsRequest.newBuilder()
              .setParent(parent.toString())
              .setFilter(filter)
              .build();

      ListSecretsPagedResponse pagedResponse = client.listSecrets(request);

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

      return pagedResponse.getPage();
    }
  }
}

Ruby

Para saber cómo instalar y usar la biblioteca de cliente de Secret Manager, consulta el artículo Bibliotecas de cliente de Secret Manager.

Para autenticarte en Secret Manager, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

# project_id = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# location_id = "YOUR-GOOGLE-CLOUD-LOCATION" # (e.g. "us-west1")
# filter      = "YOUR-FILTER-TO-APPLY"       # (e.g. "create_time>2024-01-01T00:00:00Z")
# Note : See https://cloud.google.com/secret-manager/docs/filtering for filter syntax and examples.

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

# Endpoint for the regional secret manager service.
api_endpoint = "secretmanager.#{location_id}.rep.googleapis.com"

# Create the Secret Manager client.
client = Google::Cloud::SecretManager.secret_manager_service do |config|
  config.endpoint = api_endpoint
end

# Build the resource name of the parent.
parent = client.location_path project: project_id, location: location_id

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

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

Siguientes pasos

Para buscar y filtrar ejemplos de código de otros Google Cloud productos, consulta el Google Cloud navegador de ejemplos.