Répertorier les secrets

Répertorie tous les secrets.

En savoir plus

Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :

Exemple de code

C#

Pour savoir comment installer et utiliser la bibliothèque cliente pour Secret Manager, consultez la section Bibliothèques clientes Secret Manager.

Pour vous authentifier auprès de Secret Manager, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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

Pour savoir comment installer et utiliser la bibliothèque cliente pour Secret Manager, consultez la section Bibliothèques clientes Secret Manager.

Pour vous authentifier auprès de Secret Manager, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour savoir comment installer et utiliser la bibliothèque cliente pour Secret Manager, consultez la section Bibliothèques clientes Secret Manager.

Pour vous authentifier auprès de Secret Manager, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour savoir comment installer et utiliser la bibliothèque cliente pour Secret Manager, consultez la section Bibliothèques clientes Secret Manager.

Pour vous authentifier auprès de Secret Manager, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

/**
 * 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

Pour savoir comment installer et utiliser la bibliothèque cliente pour Secret Manager, consultez la section Bibliothèques clientes Secret Manager.

Pour vous authentifier auprès de Secret Manager, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

// 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

Pour savoir comment installer et utiliser la bibliothèque cliente pour Secret Manager, consultez la section Bibliothèques clientes Secret Manager.

Pour vous authentifier auprès de Secret Manager, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour savoir comment installer et utiliser la bibliothèque cliente pour Secret Manager, consultez la section Bibliothèques clientes Secret Manager.

Pour vous authentifier auprès de Secret Manager, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

# 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

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'exemple de navigateur Google Cloud.