Créer un secret

Cette page explique comment créer un secret. Un secret contient une ou plusieurs versions de secret, ainsi que des métadonnées telles que des étiquettes et des stratégies de réplication. Le contenu réel d'un secret est stocké dans une version de secret.

Avant de commencer

  1. Activez l'API Secret Manager.

  2. Configurez l'authentification.

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

    REST

    Pour utiliser les exemples d'API REST de cette page dans un environnement de développement local, vous devez utiliser les identifiants que vous fournissez à gcloud CLI.

      Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init

    Pour en savoir plus, consultez la section S'authentifier pour utiliser REST dans la documentation sur l'authentification Google Cloud.

Rôles requis

Pour obtenir les autorisations nécessaires pour créer un secret, demandez à votre administrateur de vous accorder le rôle IAM Administrateur de Secret Manager (roles/secretmanager.admin) sur le projet, le dossier ou l'organisation. Pour en savoir plus sur l'attribution de rôles, consultez la page Gérer l'accès aux projets, aux dossiers et aux organisations.

Vous pouvez également obtenir les autorisations requises via des rôles personnalisés ou d'autres rôles prédéfinis.

Créer un secret

Vous pouvez créer des secrets à l'aide de la console Google Cloud, de la Google Cloud CLI, de l'API Secret Manager ou des bibliothèques clientes Secret Manager.

Console

  1. Dans la console Google Cloud, accédez à la page Secret Manager.

    Accéder à Secret Manager

  2. Sur la page Secret Manager, cliquez sur Créer un secret.

  3. Sur la page Créer un secret, saisissez un nom pour le secret dans le champ Nom. Un nom de secret peut contenir des lettres majuscules et minuscules, des chiffres, des traits d'union et des traits de soulignement. La longueur maximale autorisée pour un nom est de 255 caractères.

  4. Saisissez une valeur pour le secret (par exemple, abcd1234). La valeur du secret peut être indiquée dans n'importe quel format, mais elle ne doit pas dépasser 64 Kio. Vous pouvez également importer un fichier texte contenant la valeur du secret à l'aide de l'option Importer un fichier. Cette action crée automatiquement la version du secret.

  5. Cliquez sur Créer un secret.

gcloud

Avant d'utiliser les données de la commande ci-dessous, effectuez les remplacements suivants :

  • SECRET_ID: ID du secret ou identifiant complet du secret

Exécutez la commande suivante :

Linux, macOS ou Cloud Shell

gcloud secrets create SECRET_ID \
    --replication-policy="automatic"

Windows (PowerShell)

gcloud secrets create SECRET_ID `
    --replication-policy="automatic"

Windows (cmd.exe)

gcloud secrets create SECRET_ID ^
    --replication-policy="automatic"

REST

Avant d'utiliser les données de requête ci-dessous, effectuez les remplacements suivants :

  • PROJECT_ID: ID du Google Cloud projet
  • SECRET_ID: ID du secret ou identifiant complet du secret

Méthode HTTP et URL :

POST https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID

Corps JSON de la requête :

{}

Pour envoyer votre requête, choisissez l'une des options suivantes :

curl

Enregistrez le corps de la requête dans un fichier nommé request.json, puis exécutez la commande suivante :

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID"

PowerShell

Enregistrez le corps de la requête dans un fichier nommé request.json, puis exécutez la commande suivante :

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID" | Select-Object -Expand Content

Vous devriez recevoir une réponse JSON de ce type :

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
  "createTime": "2024-03-25T08:24:13.153705Z",
  "etag": "\"161477e6071da9\""
}

C#

Pour exécuter ce code, commencez par configurer un environnement de développement C# et installez le SDK Secret Manager pour C#. Sur Compute Engine ou GKE, vous devez vous authentifier avec le champ d'application cloud-platform.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;

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

        // Build the parent resource name.
        ProjectName projectName = new ProjectName(projectId);

        // Build the secret.
        Secret secret = new Secret
        {
            Replication = new Replication
            {
                Automatic = new Replication.Types.Automatic(),
            },
        };

        // Call the API.
        Secret createdSecret = client.CreateSecret(projectName, secretId, secret);
        return createdSecret;
    }
}

Go

Pour exécuter ce code, commencez par configurer un environnement de développement Go et installez le SDK Secret Manager pour Go. Sur Compute Engine ou GKE, vous devez vous authentifier avec le champ d'application cloud-platform.

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
)

// createSecret creates a new secret with the given name. A secret is a logical
// wrapper around a collection of secret versions. Secret versions hold the
// actual secret material.
func createSecret(w io.Writer, parent, id string) error {
	// parent := "projects/my-project"
	// id := "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.CreateSecretRequest{
		Parent:   parent,
		SecretId: id,
		Secret: &secretmanagerpb.Secret{
			Replication: &secretmanagerpb.Replication{
				Replication: &secretmanagerpb.Replication_Automatic_{
					Automatic: &secretmanagerpb.Replication_Automatic{},
				},
			},
		},
	}

	// Call the API.
	result, err := client.CreateSecret(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to create secret: %w", err)
	}
	fmt.Fprintf(w, "Created secret: %s\n", result.Name)
	return nil
}

Java

Pour exécuter ce code, commencez par configurer un environnement de développement Java et installez le SDK Secret Manager pour Java. Sur Compute Engine ou GKE, vous devez vous authentifier avec le champ d'application cloud-platform.

import com.google.cloud.secretmanager.v1.ProjectName;
import com.google.cloud.secretmanager.v1.Replication;
import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.protobuf.Duration;
import java.io.IOException;

public class CreateSecret {

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

  // Create a new secret with automatic replication.
  public static void createSecret(String projectId, String secretId) throws IOException {
    // 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. 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 from the project.
      ProjectName projectName = ProjectName.of(projectId);

      // Optionally set a TTL for the secret. This demonstrates how to configure
      // a secret to be automatically deleted after a certain period. The TTL is
      // specified in seconds (e.g., 900 for 15 minutes). This can be useful
      // for managing sensitive data and reducing storage costs.
      Duration ttl = Duration.newBuilder().setSeconds(900).build();

      // Build the secret to create.
      Secret secret =
          Secret.newBuilder()
              .setReplication(
                  Replication.newBuilder()
                      .setAutomatic(Replication.Automatic.newBuilder().build())
                      .build())
              .setTtl(ttl)
              .build();

      // Create the secret.
      Secret createdSecret = client.createSecret(projectName, secretId, secret);
      System.out.printf("Created secret %s\n", createdSecret.getName());
    }
  }
}

Node.js

Pour exécuter ce code, commencez par configurer un environnement de développement Node.js, puis installez le SDK Secret Manager pour Node.js. Sur Compute Engine ou GKE, vous devez vous authentifier avec le champ d'application cloud-platform.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const parent = 'projects/my-project';
// const secretId = 'my-secret';

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

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

async function createSecret() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: {
      replication: {
        automatic: {},
      },
    },
  });

  console.log(`Created secret ${secret.name}`);
}

createSecret();

PHP

Pour exécuter ce code, commencez par apprendre à utiliser PHP sur Google Cloud et à installer le SDK Secret Manager pour PHP. Sur Compute Engine ou GKE, vous devez vous authentifier avec le champ d'application cloud-platform.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\CreateSecretRequest;
use Google\Cloud\SecretManager\V1\Replication;
use Google\Cloud\SecretManager\V1\Replication\Automatic;
use Google\Cloud\SecretManager\V1\Secret;
use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient;

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

    // Build the resource name of the parent project.
    $parent = $client->projectName($projectId);

    $secret = new Secret([
        'replication' => new Replication([
            'automatic' => new Automatic(),
        ]),
    ]);

    // Build the request.
    $request = CreateSecretRequest::build($parent, $secretId, $secret);

    // Create the secret.
    $newSecret = $client->createSecret($request);

    // Print the new secret name.
    printf('Created secret: %s', $newSecret->getName());
}

Python

Pour exécuter ce code, commencez par configurer un environnement de développement Python et installez le SDK Secret Manager pour Python. Sur Compute Engine ou GKE, vous devez vous authentifier avec le champ d'application cloud-platform.

def create_secret(
    project_id: str, secret_id: str, ttl: Optional[str] = None
) -> secretmanager.Secret:
    """
    Create a new secret with the given name. A secret is a logical wrapper
    around a collection of secret versions. Secret versions hold the actual
    secret material.

     Args:
        project_id (str): The project ID where the secret is to be created.
        secret_id (str): The ID to assign to the new secret. This ID must be unique within the project.
        ttl (Optional[str]): An optional string that specifies the secret's time-to-live in seconds with
                             format (e.g., "900s" for 15 minutes). If specified, the secret
                             versions will be automatically deleted upon reaching the end of the TTL period.

    Returns:
        secretmanager.Secret: An object representing the newly created secret, containing details like the
                              secret's name, replication settings, and optionally its TTL.

    Example:
        # Create a secret with automatic replication and no TTL
        new_secret = create_secret("my-project", "my-new-secret")

        # Create a secret with a TTL of 30 days
        new_secret_with_ttl = create_secret("my-project", "my-timed-secret", "7776000s")
    """

    # 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}"

    # Create the secret.
    response = client.create_secret(
        request={
            "parent": parent,
            "secret_id": secret_id,
            "secret": {"replication": {"automatic": {}}, "ttl": ttl},
        }
    )

    # Print the new secret name.
    print(f"Created secret: {response.name}")

Ruby

Pour exécuter ce code, commencez par configurer un environnement de développement Ruby et installez le SDK Secret Manager pour Ruby. Sur Compute Engine ou GKE, vous devez vous authentifier avec le champ d'application cloud-platform.

# 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 parent project.
parent = client.project_path project: project_id

# Create the secret.
secret = client.create_secret(
  parent:    parent,
  secret_id: secret_id,
  secret:    {
    replication: {
      automatic: {}
    }
  }
)

# Print the new secret name.
puts "Created secret: #{secret.name}"

Pour sélectionner la règle de réplication adaptée à votre secret, consultez la section Choisir une règle de réplication.

Ajouter une version de secret

Secret Manager effectue automatiquement des versions des données de secret à l'aide de versions de secret. Les opérations de clé, telles que l'accès, la destruction, la désactivation et l'activation, sont appliquées à des versions de secret spécifiques. Avec Secret Manager, vous pouvez associer des secrets à des versions spécifiques telles que 42 ou à des alias dynamiques tels que latest. Pour en savoir plus, consultez la section Ajouter une version de secret.

Accéder à une version de secret

Pour accéder aux données secrètes d'une version de secret spécifique afin d'effectuer une authentification réussie, consultez la section Accéder à une version de secret.

Étape suivante