Obtenir le code secret

Récupère un secret.

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.Cloud.SecretManager.V1;

public class GetSecretSample
{
    public Secret GetSecret(string projectId = "my-project", string secretId = "my-secret")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretName secretName = new SecretName(projectId, secretId);

        // Call the API.
        Secret secret = client.GetSecret(secretName);
        return secret;
    }
}

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"
)

// getSecret gets information about the given secret. This only returns metadata
// about the secret container, not any secret material.
func getSecret(w io.Writer, name string) error {
	// name := "projects/my-project/secrets/my-secret"

	// 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.GetSecretRequest{
		Name: name,
	}

	// Call the API.
	result, err := client.GetSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to get secret: %w", err)
	}

	replication := result.Replication.Replication
	fmt.Fprintf(w, "Found secret %s with replication policy %s\n", result.Name, replication)
	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.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretName;
import java.io.IOException;

public class GetSecret {

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

  // Get an existing secret.
  public static void getSecret(String projectId, String secretId) 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 name.
      SecretName secretName = SecretName.of(projectId, secretId);

      // Create the secret.
      Secret secret = client.getSecret(secretName);

      // Get the replication policy.
      String replication = "";
      if (secret.getReplication().getAutomatic() != null) {
        replication = "AUTOMATIC";
      } else if (secret.getReplication().getUserManaged() != null) {
        replication = "MANAGED";
      } else {
        throw new IllegalStateException("Unknown replication type");
      }

      System.out.printf("Secret %s, replication %s\n", secret.getName(), replication);
    }
  }
}

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 name = 'projects/my-project/secrets/my-secret';

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

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

async function getSecret() {
  const [secret] = await client.getSecret({
    name: name,
  });

  const policy = secret.replication.replication;

  console.info(`Found secret ${secret.name} (${policy})`);
}

getSecret();

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

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

    // Build the resource name of the secret.
    $name = $client->secretName($projectId, $secretId);

    // Build the request.
    $request = GetSecretRequest::build($name);

    // Get the secret.
    $secret = $client->getSecret($request);

    // Get the replication policy.
    $replication = strtoupper($secret->getReplication()->getReplication());

    // Print data about the secret.
    printf('Got secret %s with replication policy %s', $secret->getName(), $replication);
}

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 get_secret(project_id: str, secret_id: str) -> secretmanager.GetSecretRequest:
    """
    Get information about the given secret. This only returns metadata about
    the secret container, not any secret material.
    """

    # 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 secret.
    name = client.secret_path(project_id, secret_id)

    # Get the secret.
    response = client.get_secret(request={"name": name})

    # Get the replication policy.
    if "automatic" in response.replication:
        replication = "AUTOMATIC"
    elif "user_managed" in response.replication:
        replication = "MANAGED"
    else:
        raise Exception(f"Unknown replication {response.replication}")

    # Print data about the secret.
    print(f"Got secret {response.name} with replication policy {replication}")

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")
# secret_id  = "YOUR-SECRET-ID"             # (e.g. "my-secret")

# 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 secret.
name = client.secret_path project: project_id, secret: secret_id

# Get the secret.
secret = client.get_secret name: name

# Get the replication policy.
if !secret.replication.automatic.nil?
  replication = "automatic"
elsif !secret.replication.user_managed.nil?
  replication = "user managed"
else
  raise "Unknown replication #{secret.replication}"
end

# Print a success message.
puts "Got secret #{secret.name} with replication policy #{replication}"

Étapes suivantes

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