Crea un secret

Questo argomento descrive come creare un secret. Un secret contiene una o più versioni del secret, insieme a metadati come etichette e informazioni di replica. I contenuti effettivi di un secret sono archiviati in una versione del secret.

Prima di iniziare

  1. Abilita l'API Secret Manager, una volta per progetto.
  2. Assegna il ruolo Amministratore di Secret Manager (roles/secretmanager.admin) a progetto, cartella o organizzazione.
  3. Esegui l'autenticazione nell'API Secret Manager utilizzando uno dei seguenti modi:

    • Se utilizzi librerie client per accedere all'API Secret Manager, configura le Credenziali predefinite dell'applicazione.
    • Se utilizzi Google Cloud CLI per accedere all'API Secret Manager, usa le tue credenziali di Google Cloud CLI per l'autenticazione.
    • Per autenticare una chiamata REST, utilizza le credenziali di Google Cloud CLI o le Credenziali predefinite dell'applicazione.

Crea un secret

Console

  1. Vai alla pagina Secret Manager nella console Google Cloud.

    Vai alla pagina di Secret Manager

  2. Nella pagina Secret Manager, fai clic su Create Secret (Crea secret).

  3. Nella pagina Crea secret, in Nome, inserisci un nome per il secret (ad esempio, my-secret). Il nome del secret può contenere lettere maiuscole e minuscole, numeri, trattini e trattini bassi. La lunghezza massima consentita per un nome è di 255 caratteri.

  4. (Facoltativo) Per aggiungere una versione del secret anche durante la creazione del secret iniziale, inserisci un valore per il secret nel campo Valore secret (ad esempio, abcd1234). Il valore del secret può essere in qualsiasi formato, ma non deve superare i 64 KiB.

  5. Lascia invariata la sezione Regioni.

  6. Fai clic sul pulsante Crea secret.

gcloud

Per utilizzare Secret Manager nella riga di comando, devi prima installare Google Cloud CLI o eseguirne l'upgrade alla versione 378.0.0 o successiva. In Compute Engine o GKE, devi eseguire l'autenticazione con l'ambito cloud-platform.

$ gcloud secrets create secret-id \
    --replication-policy="automatic"

C#

Per eseguire questo codice, prima configura un ambiente di sviluppo C# e installa l'SDK C# di Secret Manager. In Compute Engine o GKE, devi eseguire l'autenticazione con l'ambito 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

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Go e installare l'SDK Secret Manager Go. In Compute Engine o GKE, devi eseguire l'autenticazione con l'ambito 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

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Java e installare l'SDK Java di Secret Manager. In Compute Engine o GKE, devi eseguire l'autenticazione con l'ambito 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 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);

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

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

Node.js

Per eseguire questo codice, prima configura un ambiente di sviluppo Node.js e installa l'SDK Node.js di Secret Manager. In Compute Engine o GKE, devi eseguire l'autenticazione con l'ambito 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

Per eseguire questo codice, scopri prima di tutto come utilizzare PHP su Google Cloud e installare l'SDK PHP di Secret Manager. In Compute Engine o GKE, devi eseguire l'autenticazione con l'ambito 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

Per eseguire questo codice, prima configura un ambiente di sviluppo Python e installa l'SDK Python di Secret Manager. In Compute Engine o GKE, devi eseguire l'autenticazione con l'ambito cloud-platform.

def create_secret(project_id: str, secret_id: str) -> secretmanager.CreateSecretRequest:
    """
    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.
    """

    # 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": {}}},
        }
    )

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

Ruby

Per eseguire questo codice, devi prima configurare un ambiente di sviluppo Ruby e poi installare l'SDK Ruby di Secret Manager. In Compute Engine o GKE, devi eseguire l'autenticazione con l'ambito 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}"

API

In questi esempi viene utilizzato curl per dimostrare l'utilizzo dell'API. Puoi generare token di accesso con gcloud auth print-access-token. In Compute Engine o GKE, devi eseguire l'autenticazione con l'ambito cloud-platform.

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets?secretId=secret-id" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --data "{\"replication\": {\"automatic\": {}}}"

Per selezionare il criterio di replica corretto per il tuo secret, consulta Scegliere un criterio di replica.

Aggiungi una versione del secret

Secret Manager esegue automaticamente le versioni dei dati secret utilizzando le versioni dei secret e la maggior parte delle operazioni come l'accesso, l'eliminazione, la disattivazione e l'abilitazione avvengono su una versione del secret. Con Secret Manager, puoi aggiungere un secret a versioni specifiche come 42 o ad alias mobili come latest. Scopri come aggiungere una versione del secret.

Accedi a una versione del secret

Per accedere ai dati del secret da una determinata versione del secret per eseguire l'autenticazione correttamente, vedi Accedere a una versione del secret.

Passaggi successivi