Membuat secret regional

Halaman ini menjelaskan cara membuat secret regional. Secret berisi satu atau beberapa versi secret, beserta metadata seperti label dan anotasi. Konten sebenarnya dari secret disimpan dalam secret version.

Sebelum memulai

  1. Aktifkan Secret Manager API.

  2. Konfigurasi Secret Manager untuk menggunakan endpoint regional.

  3. Menyiapkan autentikasi.

    Pilih tab untuk melihat bagaimana Anda berencana menggunakan contoh di halaman ini:

    Konsol

    Saat menggunakan konsol Google Cloud untuk mengakses layanan Google Cloud dan API, Anda tidak perlu menyiapkan autentikasi.

    gcloud

    Di konsol Google Cloud , aktifkan Cloud Shell.

    Aktifkan Cloud Shell

    Di bagian bawah konsol Google Cloud , sesi Cloud Shell akan dimulai dan menampilkan perintah command line. Cloud Shell adalah lingkungan shell dengan Google Cloud CLI yang sudah terinstal, dan dengan nilai yang sudah ditetapkan untuk project Anda saat ini. Diperlukan waktu beberapa detik untuk melakukan inisialisasi pada sesi.

    REST

    Untuk menggunakan contoh REST API di halaman ini dalam lingkungan pengembangan lokal, gunakan kredensial yang Anda berikan ke gcloud CLI.

      Instal Google Cloud CLI.

      Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

    Untuk mengetahui informasi selengkapnya, lihat Melakukan autentikasi untuk menggunakan REST dalam dokumentasi autentikasi Google Cloud .

Peran yang diperlukan

Untuk mendapatkan izin yang diperlukan guna membuat secret, minta administrator untuk memberi Anda peran IAM Secret Manager Admin (roles/secretmanager.admin) di project, folder, atau organisasi. Untuk mengetahui informasi selengkapnya tentang cara memberikan peran, lihat Mengelola akses ke project, folder, dan organisasi.

Anda mungkin juga bisa mendapatkan izin yang diperlukan melalui peran khusus atau peran bawaan lainnya.

Membuat secret regional

Anda dapat membuat secret menggunakan konsol Google Cloud , Google Cloud CLI, Secret Manager API, atau library klien Secret Manager.

Konsol

  1. Di konsol Google Cloud , buka halaman Secret Manager.

    Buka Secret Manager

  2. Di halaman Secret Manager, klik tab Regional secrets, lalu klik Create regional secret.

  3. Di halaman Create regional secret, masukkan nama untuk secret di kolom Name. Nama secret dapat berisi huruf besar dan kecil, angka, tanda hubung, dan garis bawah. Panjang maksimum yang diizinkan untuk nama adalah 255 karakter.

  4. Masukkan nilai untuk secret (misalnya, abcd1234). Nilai secret dapat dalam format apa pun, tetapi tidak boleh lebih besar dari 64 KiB. Anda juga dapat mengupload file teks yang berisi nilai rahasia menggunakan opsi Upload file. Tindakan ini akan otomatis membuat versi secret.

  5. Pilih lokasi tempat Anda ingin menyimpan secret regional dari daftar Region.

  6. Klik Create secret.

gcloud

Sebelum menggunakan salah satu data perintah di bawah, lakukan penggantian berikut:

  • SECRET_ID: ID secret.
  • LOCATION: Google Cloud lokasi secret.

Jalankan perintah berikut:

Linux, macOS, atau Cloud Shell

gcloud secrets create SECRET_ID \
    --location=LOCATION

Windows (PowerShell)

gcloud secrets create SECRET_ID `
    --location=LOCATION

Windows (cmd.exe)

gcloud secrets create SECRET_ID ^
    --location=LOCATION

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • LOCATION: Google Cloud lokasi secret.
  • PROJECT_ID: Google Cloud Project ID
  • SECRET_ID: ID secret.

Metode HTTP dan URL:

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

Meminta isi JSON:

{}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

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

PowerShell

Simpan isi permintaan dalam file bernama request.json, dan jalankan perintah berikut:

$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.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?secretId=SECRET_ID" | Select-Object -Expand Content

Anda akan melihat respons JSON seperti berikut:

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

Go

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

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
	"google.golang.org/api/option"
)

// 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 CreateRegionalSecret(w io.Writer, projectId, locationId, id string) error {
	// parent := "projects/my-project/locations/my-location"
	// id := "my-secret"

	// Create the client.
	ctx := context.Background()

	//Endpoint to send the request to regional server
	endpoint := fmt.Sprintf("secretmanager.%s.rep.googleapis.com:443", locationId)
	client, err := secretmanager.NewClient(ctx, option.WithEndpoint(endpoint))
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %w", err)
	}
	defer client.Close()

	parent := fmt.Sprintf("projects/%s/locations/%s", projectId, locationId)

	// Build the request.
	req := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: id,
	}

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

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.LocationName;
import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import java.io.IOException;

public class CreateRegionalSecret {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    // Your GCP project ID.
    String projectId = "your-project-id";
    // Location of the secret.
    String locationId = "your-location-id";
    // Resource ID of the secret to create.
    String secretId = "your-secret-id";
    createRegionalSecret(projectId, locationId, secretId);
  }

  // Create a new regional secret 
  public static Secret createRegionalSecret(
      String projectId, String locationId, String secretId) 
      throws IOException {

    // Endpoint to call the regional secret manager sever
    String apiEndpoint = String.format("secretmanager.%s.rep.googleapis.com:443", locationId);
    SecretManagerServiceSettings secretManagerServiceSettings =
        SecretManagerServiceSettings.newBuilder().setEndpoint(apiEndpoint).build();

    // 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.
    try (SecretManagerServiceClient client = 
        SecretManagerServiceClient.create(secretManagerServiceSettings)) {
      // Build the parent name from the project.
      LocationName location = LocationName.of(projectId, locationId);

      // Build the regional secret to create.
      Secret secret =
          Secret.newBuilder().build();

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

      return createdSecret;
    }
  }
}

Node.js

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project'
// const locationId = 'locationId';
// const secretId = 'my-secret';
const parent = `projects/${projectId}/locations/${locationId}`;

// Imports the Secret Manager libray

const {SecretManagerServiceClient} = require('@google-cloud/secret-manager');

// Adding the endpoint to call the regional secret manager sever
const options = {};
options.apiEndpoint = `secretmanager.${locationId}.rep.googleapis.com`;
// Instantiates a client
const client = new SecretManagerServiceClient(options);

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

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

createRegionalSecret();

Python

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

from google.cloud import secretmanager_v1


def create_regional_secret(
    project_id: str,
    location_id: str,
    secret_id: str,
    ttl: Optional[str] = None,
) -> secretmanager_v1.Secret:
    """
    Creates a new regional secret with the given name.
    """

    # Endpoint to call the regional secret manager sever
    api_endpoint = f"secretmanager.{location_id}.rep.googleapis.com"

    # Create the Secret Manager client.
    client = secretmanager_v1.SecretManagerServiceClient(
        client_options={"api_endpoint": api_endpoint},
    )

    # Build the resource name of the parent project.
    parent = f"projects/{project_id}/locations/{location_id}"

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

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

    return response

Menambahkan versi secret

Secret Manager otomatis membuat versi data rahasia menggunakan versi rahasia. Operasi kunci, seperti akses, penghancuran, penonaktifan, dan pengaktifan, diterapkan ke versi secret tertentu. Dengan Secret Manager, Anda dapat mengaitkan secret dengan versi tertentu seperti 42 atau dengan alias dinamis seperti latest. Untuk mempelajari lebih lanjut, lihat Menambahkan versi secret.

Mengakses versi secret

Untuk mengakses data secret dari versi secret tertentu agar autentikasi berhasil, lihat Mengakses versi secret regional.

Langkah berikutnya