Membuat dan mengakses secret menggunakan Secret Manager

Pelajari cara membuat dan mengakses secret menggunakan Secret Manager di Google Cloud.


Jika ingin mengikuti panduan langkah demi langkah untuk tugas ini langsung di Konsol Google Cloud, klik Pandu saya:

Pandu saya


Sebelum memulai

  1. Aktifkan Secret Manager API, sekali per project.
  2. Tetapkan peran Secret Manager Admin (roles/secretmanager.admin) di project, folder, atau organisasi.
  3. Lakukan autentikasi ke Secret Manager API menggunakan salah satu cara berikut:

    • Jika Anda menggunakan library klien untuk mengakses Secret Manager API, siapkan Kredensial Default Aplikasi.
    • Jika Anda menggunakan Google Cloud CLI untuk mengakses Secret Manager API, gunakan kredensial Google Cloud CLI untuk melakukan autentikasi.
    • Untuk mengautentikasi panggilan REST, gunakan kredensial Google Cloud CLI atau Kredensial Default Aplikasi.

Membuat secret dan mengakses versi secret

Contoh berikut menunjukkan pembuatan secret dan akses konten versi secret.

Konsol

Untuk membuat secret dan versi secret:

  1. Buka halaman Secret Manager di Konsol Google Cloud.

    Buka halaman Secret Manager

  2. Di halaman Secret Manager, klik Create Secret.

  3. Di halaman Create secret, di bagian Name, masukkan my-secret.

  4. Di kolom Secret value, masukkan my super secret data.

  5. Klik tombol Buat secret.

Untuk mengakses konten versi rahasia:

  1. Buka halaman Secret Manager di Konsol Google Cloud.

    Buka halaman Secret Manager

  2. Di halaman Secret Manager, klik my-secret.

  3. Di halaman Secret details, di tabel Versions, temukan versi 1.

  4. Di kolom Tindakan, klik Lihat lainnya.

  5. Klik View secret value dari menu.

  6. Dialog yang menunjukkan nilai secret akan muncul. Klik Done untuk menutup dialog.

gcloud

Untuk menggunakan Secret Manager di command line, Instal atau upgrade Google Cloud CLI ke versi 378.0.0 atau yang lebih baru terlebih dahulu. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan cloud-platform.

Untuk membuat secret dan menyimpan string sebagai konten versi secret pertama:

$ echo -n "my super secret data" | gcloud secrets create my-secret \
    --replication-policy="replication-policy" \
    --data-file=-

Dengan replication-policy adalah salah satu dari automatic atau user-managed.

Untuk mengakses konten versi secret tertentu:

$ gcloud secrets versions access 1 --secret="my-secret"

Untuk mengakses konten versi secret terbaru:

$ gcloud secrets versions access latest --secret="my-secret"

C#

Untuk menjalankan kode ini, siapkan lingkungan pengembangan C# terlebih dahulu, lalu instal Secret Manager C# SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan cloud-platform.


using System;
using System.Text;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;
using Google.Protobuf;

public class QuickstartSample
{
    public void Quickstart(string projectId = "my-project", string secretId = "my-secret")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

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

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

        Secret createdSecret = client.CreateSecret(projectName, secretId, secret);

        // Build a payload.
        SecretPayload payload = new SecretPayload
        {
            Data = ByteString.CopyFrom("my super secret data", Encoding.UTF8),
        };

        // Add a secret version.
        SecretVersion createdVersion = client.AddSecretVersion(createdSecret.SecretName, payload);

        // Access the secret version.
        AccessSecretVersionResponse result = client.AccessSecretVersion(createdVersion.SecretVersionName);

        // Print the results
        //
        // WARNING: Do not print secrets in production environments. This
        // snippet is for demonstration purposes only.
        string data = result.Payload.Data.ToStringUtf8();
        Console.WriteLine($"Plaintext: {data}");
    }
}

Go

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Go terlebih dahulu, lalu instal Secret Manager Go SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan cloud-platform.


// Sample quickstart is a basic program that uses Secret Manager.
package main

import (
	"context"
	"fmt"
	"log"

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

func main() {
	// GCP project in which to store secrets in Secret Manager.
	projectID := "your-project-id"

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		log.Fatalf("failed to setup client: %v", err)
	}
	defer client.Close()

	// Create the request to create the secret.
	createSecretReq := &secretmanagerpb.CreateSecretRequest{
		Parent:   fmt.Sprintf("projects/%s", projectID),
		SecretId: "my-secret",
		Secret: &secretmanagerpb.Secret{
			Replication: &secretmanagerpb.Replication{
				Replication: &secretmanagerpb.Replication_Automatic_{
					Automatic: &secretmanagerpb.Replication_Automatic{},
				},
			},
		},
	}

	secret, err := client.CreateSecret(ctx, createSecretReq)
	if err != nil {
		log.Fatalf("failed to create secret: %v", err)
	}

	// Declare the payload to store.
	payload := []byte("my super secret data")

	// Build the request.
	addSecretVersionReq := &secretmanagerpb.AddSecretVersionRequest{
		Parent: secret.Name,
		Payload: &secretmanagerpb.SecretPayload{
			Data: payload,
		},
	}

	// Call the API.
	version, err := client.AddSecretVersion(ctx, addSecretVersionReq)
	if err != nil {
		log.Fatalf("failed to add secret version: %v", err)
	}

	// Build the request.
	accessRequest := &secretmanagerpb.AccessSecretVersionRequest{
		Name: version.Name,
	}

	// Call the API.
	result, err := client.AccessSecretVersion(ctx, accessRequest)
	if err != nil {
		log.Fatalf("failed to access secret version: %v", err)
	}

	// Print the secret payload.
	//
	// WARNING: Do not print the secret in a production environment - this
	// snippet is showing how to access the secret material.
	log.Printf("Plaintext: %s", result.Payload.Data)
}

Java

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Java terlebih dahulu dan instal Secret Manager Java SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan cloud-platform.

import com.google.cloud.secretmanager.v1.AccessSecretVersionResponse;
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.cloud.secretmanager.v1.SecretPayload;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.protobuf.ByteString;

public class Quickstart {

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

  public void quickstart(String projectId, String secretId) throws Exception {
    // 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 from the project.
      ProjectName projectName = ProjectName.of(projectId);

      // Create the parent secret.
      Secret secret =
          Secret.newBuilder()
              .setReplication(
                  Replication.newBuilder()
                      .setAutomatic(Replication.Automatic.newBuilder().build())
                      .build())
              .build();

      Secret createdSecret = client.createSecret(projectName, secretId, secret);

      // Add a secret version.
      SecretPayload payload =
          SecretPayload.newBuilder().setData(ByteString.copyFromUtf8("hello world!")).build();
      SecretVersion addedVersion = client.addSecretVersion(createdSecret.getName(), payload);

      // Access the secret version.
      AccessSecretVersionResponse response = client.accessSecretVersion(addedVersion.getName());

      // Print the secret payload.
      //
      // WARNING: Do not print the secret in a production environment - this
      // snippet is showing how to access the secret material.
      String data = response.getPayload().getData().toStringUtf8();
      System.out.printf("Plaintext: %s\n", data);
    }
  }
}

Node.js

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Node.js terlebih dahulu, lalu instal Secret Manager Node.js SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan cloud-platform.

// Import the Secret Manager client and instantiate it:
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');
const client = new SecretManagerServiceClient();

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// parent = 'projects/my-project', // Project for which to manage secrets.
// secretId = 'foo', // Secret ID.
// payload = 'hello world!' // String source data.

async function createAndAccessSecret() {
  // Create the secret with automation replication.
  const [secret] = await client.createSecret({
    parent: parent,
    secret: {
      name: secretId,
      replication: {
        automatic: {},
      },
    },
    secretId,
  });

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

  // Add a version with a payload onto the secret.
  const [version] = await client.addSecretVersion({
    parent: secret.name,
    payload: {
      data: Buffer.from(payload, 'utf8'),
    },
  });

  console.info(`Added secret version ${version.name}`);

  // Access the secret.
  const [accessResponse] = await client.accessSecretVersion({
    name: version.name,
  });

  const responsePayload = accessResponse.payload.data.toString('utf8');
  console.info(`Payload: ${responsePayload}`);
}
createAndAccessSecret();

PHP

Untuk menjalankan kode ini, pelajari cara menggunakan PHP di Google Cloud terlebih dahulu dan instal Secret Manager PHP SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan cloud-platform.

// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\AccessSecretVersionRequest;
use Google\Cloud\SecretManager\V1\AddSecretVersionRequest;
use Google\Cloud\SecretManager\V1\Client\SecretManagerServiceClient;
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\SecretPayload;

/** Uncomment and populate these variables in your code */
// $projectId = 'YOUR_GOOGLE_CLOUD_PROJECT' (e.g. 'my-project');
// $secretId = 'YOUR_SECRET_ID' (e.g. 'my-secret');

// Create the Secret Manager client.
$client = new SecretManagerServiceClient();

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

// Create the parent secret.
$createSecretRequest = (new CreateSecretRequest())
    ->setParent($parent)
    ->setSecretId($secretId)
    ->setSecret(new Secret([
        'replication' => new Replication([
            'automatic' => new Automatic(),
        ]),
    ]));
$secret = $client->createSecret($createSecretRequest);

// Add the secret version.
$addSecretVersionRequest = (new AddSecretVersionRequest())
    ->setParent($secret->getName())
    ->setPayload(new SecretPayload([
    'data' => 'hello world',
]));
$version = $client->addSecretVersion($addSecretVersionRequest);

// Access the secret version.
$accessSecretVersionRequest = (new AccessSecretVersionRequest())
    ->setName($version->getName());
$response = $client->accessSecretVersion($accessSecretVersionRequest);

// Print the secret payload.
//
// WARNING: Do not print the secret in a production environment - this
// snippet is showing how to access the secret material.
$payload = $response->getPayload()->getData();
printf('Plaintext: %s' . PHP_EOL, $payload);

Python

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Python terlebih dahulu, lalu instal Secret Manager Python SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan cloud-platform.

# Import the Secret Manager client library.
from google.cloud import secretmanager

# GCP project in which to store secrets in Secret Manager.
project_id = "YOUR_PROJECT_ID"

# ID of the secret to create.
secret_id = "YOUR_SECRET_ID"

# Create the Secret Manager client.
client = secretmanager.SecretManagerServiceClient()

# Build the parent name from the project.
parent = f"projects/{project_id}"

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

# Add the secret version.
version = client.add_secret_version(
    request={"parent": secret.name, "payload": {"data": b"hello world!"}}
)

# Access the secret version.
response = client.access_secret_version(request={"name": version.name})

# Print the secret payload.
#
# WARNING: Do not print the secret in a production environment - this
# snippet is showing how to access the secret material.
payload = response.payload.data.decode("UTF-8")
print(f"Plaintext: {payload}")

Ruby

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Ruby terlebih dahulu, lalu instal Secret Manager Ruby SDK. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan cloud-platform.

require "google/cloud/secret_manager"

##
# Secret manager quickstart
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param secret_id [String] Your secret name (e.g. "my-secret")
#
def quickstart project_id:, secret_id:
  # Create the Secret Manager client.
  client = Google::Cloud::SecretManager.secret_manager_service

  # Build the parent name from the project.
  parent = "projects/#{project_id}"

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

  # Add a secret version.
  version = client.add_secret_version(
    parent:  secret.name,
    payload: {
      data: "hello world!"
    }
  )

  # Access the secret version.
  response = client.access_secret_version name: version.name

  # Print the secret payload.
  #
  # WARNING: Do not print the secret in a production environment - this
  # snippet is showing how to access the secret material.
  payload = response.payload.data
  puts "Plaintext: #{payload}"
end

API

Contoh ini menggunakan curl untuk menunjukkan cara menggunakan API. Anda dapat membuat token akses dengan gcloud auth print-access-token. Di Compute Engine atau GKE, Anda harus melakukan autentikasi dengan cakupan cloud-platform.

Untuk membuat secret dan menyimpan string sebagai konten versi secret:

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

Untuk mengakses konten versi secret:

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/my-secret/versions/1:access" \
    --request "GET" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json"

Langkah selanjutnya