Mencantumkan secret regional dan melihat detail secret

Di Secret Manager, secret berfungsi sebagai container untuk beberapa versi secret. File ini menyimpan informasi penting seperti label dan setelan rotasi, tetapi bukan nilai secret itu sendiri. Halaman ini menjelaskan cara mengambil daftar semua secret dalam project dan melihat metadata yang terkait dengan setiap secret.

Peran yang diperlukan

Untuk mendapatkan izin akses, Anda perlu membuat daftar secret dan melihat {i>metadata<i} rahasia, minta administrator untuk memberi Anda Peran IAM Secret Manager Viewer (roles/secretmanager.viewer) 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.

Mencantumkan rahasia

Untuk mengambil daftar semua secret dalam project, gunakan salah satu metode berikut:

Konsol

  1. Buka halaman Secret Manager di Konsol Google Cloud.

    Buka Secret Manager

  2. Di halaman Secret Manager, klik tab Regional secrets.

    Halaman ini menampilkan daftar secret dalam project.

gcloud

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

  • LOCATION: lokasi Google Cloud rahasia

Jalankan mengikuti berikut:

Linux, macOS, atau Cloud Shell

gcloud secrets list --location=LOCATION

Windows (PowerShell)

gcloud secrets list --location=LOCATION

Windows (cmd.exe)

gcloud secrets list --location=LOCATION

Respons menampilkan daftar secret dan versi secret-nya.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • LOCATION: lokasi Google Cloud rahasia
  • PROJECT_ID: project ID Google Cloud

Metode HTTP dan URL:

GET https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets

Isi JSON permintaan:

{}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

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

curl -X GET \
-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"

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 GET `
-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" | Select-Object -Expand Content

Anda akan melihat respons JSON seperti berikut:

{
  "secrets": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
      "createTime": "2024-09-02T07:14:00.281541Z",
      "etag": "\"16211daf5f29c5\""
    },
  ],
  "totalSize": 1
}

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/iterator"
	"google.golang.org/api/option"
)

// listSecrets lists all secrets in the given project.
func ListRegionalSecrets(w io.Writer, projectId, locationId string) error {
	// parent := "projects/my-project/locations/my-location"

	// 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 regional secretmanager client: %w", err)
	}
	defer client.Close()

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

	// Build the request.
	req := &secretmanagerpb.ListSecretsRequest{
		Parent: parent,
	}

	// Call the API.
	it := client.ListSecrets(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}

		if err != nil {
			return fmt.Errorf("failed to list regional secrets: %w", err)
		}

		fmt.Fprintf(w, "Found regional secret %s\n", resp.Name)
	}

	return nil
}

Java

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Java terlebih dahulu, lalu instal Java SDK Secret Manager. 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.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient.ListSecretsPagedResponse;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import java.io.IOException;

public class ListRegionalSecrets {

  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";
    listRegionalSecrets(projectId, locationId);
  }

  // List all secrets for a project
  public static ListSecretsPagedResponse listRegionalSecrets(
      String projectId, String locationId)
      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.
      LocationName parent = LocationName.of(projectId, locationId);

      // Get all secrets.
      ListSecretsPagedResponse pagedResponse = client.listSecrets(parent.toString());

      // List all secrets.
      pagedResponse
          .iterateAll()
          .forEach(
              secret -> {
                System.out.printf("Regional secret %s\n", secret.getName());
              });

      return pagedResponse;
    }
  }
}

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 = 'my-location';

const parent = `projects/${projectId}/locations/${locationId}`;

// Imports the Secret Manager library
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 listRegionalSecrets() {
  const [secrets] = await client.listSecrets({
    parent: parent,
  });

  secrets.forEach(secret => {
    console.log(`${secret.name}`);
  });
}

listRegionalSecrets();

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_v1


def list_regional_secrets(project_id: str, location_id: str) -> None:
    """
    Lists all regional secrets in the given project.
    """

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

    # List all secrets.
    for secret in client.list_secrets(request={"parent": parent}):
        print(f"Found secret: {secret.name}")

Lihat detail rahasia

Untuk melihat metadata rahasia, gunakan salah satu metode berikut:

Konsol

  1. Buka halaman Secret Manager di Konsol Google Cloud.

    Buka Secret Manager

  2. Di halaman Secret Manager, klik tab Regional secrets.

  3. Klik secret yang detailnya ingin Anda lihat.

  4. Di halaman detail secret, klik tab Overview. Tab ini menampilkan detail umum dan metadata yang terkait dengan secret.

gcloud

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

  • SECRET_ID: ID rahasia atau ID yang sepenuhnya memenuhi syarat untuk rahasia
  • LOCATION: lokasi Google Cloud rahasia

Jalankan mengikuti berikut:

Linux, macOS, atau Cloud Shell

gcloud secrets describe SECRET_ID --location=LOCATION

Windows (PowerShell)

gcloud secrets describe SECRET_ID --location=LOCATION

Windows (cmd.exe)

gcloud secrets describe SECRET_ID --location=LOCATION

Respons akan menampilkan secret.

REST

Sebelum menggunakan salah satu data permintaan, lakukan penggantian berikut:

  • LOCATION: Lokasi secret Google Cloud
  • PROJECT_ID: project ID Google Cloud
  • SECRET_ID: ID secret atau ID yang memenuhi syarat sepenuhnya untuk secret

Metode HTTP dan URL:

GET https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID

Isi JSON permintaan:

{}

Untuk mengirim permintaan Anda, pilih salah satu opsi berikut:

curl

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

curl -X GET \
-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/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 GET `
-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/SECRET_ID" | Select-Object -Expand Content

Anda akan melihat respons JSON seperti berikut:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID",
  "createTime": "2024-09-02T07:14:00.281541Z",
  "etag": "\"16211daf5f29c5\""
}

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

// getSecret gets information about the given secret. This only returns metadata
// about the secret container, not any secret material.
func GetRegionalSecret(w io.Writer, projectId, locationId, secretId string) error {
	// name := "projects/my-project/locations/my-location/secrets/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 regional secretmanager client: %w", err)
	}
	defer client.Close()

	name := fmt.Sprintf("projects/%s/locations/%s/secrets/%s", projectId, locationId, secretId)
	// 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)
	}

	fmt.Fprintf(w, "Found regional secret %s \n", result.Name)
	return nil
}

Java

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

import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretName;
import java.io.IOException;

public class GetRegionalSecret {

  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 you want to retrieve.
    String secretId = "your-secret-id";
    getRegionalSecret(projectId, locationId, secretId);
  }

  // Get an existing secret.
  public static Secret getRegionalSecret(
      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 name.
      SecretName secretName = 
          SecretName.ofProjectLocationSecretName(projectId, locationId, secretId);

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

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

      return secret;
    }
  }
}

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 = 'my-location';
// const secretId = 'my-secret';

const name = `projects/${projectId}/locations/${locationId}/secrets/${secretId}`;

// Imports the Secret Manager library
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 getRegionalSecret() {
  const [secret] = await client.getSecret({
    name: name,
  });

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

getRegionalSecret();

Python

Untuk menjalankan kode ini, siapkan lingkungan pengembangan Python terlebih dahulu dan 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_v1


def get_regional_secret(
    project_id: str, location_id: str, secret_id: str
) -> secretmanager_v1.GetSecretRequest:
    """
    Gets information about the given secret. This only returns metadata about
    the secret container, not any secret material.
    """

    # Endpoint to call the regional Secret Manager API
    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 secret.
    name = f"projects/{project_id}/locations/{location_id}/secrets/{secret_id}"

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

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

    return response

Langkah selanjutnya