存取密鑰版本

本頁說明如何存取密鑰版本。存取密鑰版本會傳回密鑰內容,以及密鑰版本的其他中繼資料。如要使用 Google Cloud CLI 或 Secret Manager API 存取密鑰版本,您必須指定版本 ID別名 (如有指派)。您也可以指定 latest 做為版本 ID,存取密鑰的最新版本。

必要的角色

如要取得存取密鑰版本的權限,請要求管理員授予您密鑰的 Secret Manager 密鑰存取者 (roles/secretmanager.secretAccessor) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和機構的存取權」。

您或許還可透過自訂角色或其他預先定義的角色取得必要權限。

存取密鑰版本

如要存取密鑰,請使用下列其中一種方法:

控制台

  1. 前往 Google Cloud 控制台的「Secret Manager」頁面。

    前往 Secret Manager

  2. 在「Secret Manager」頁面中,按一下密鑰即可存取其版本。

  3. 在密鑰詳細資料頁面的「版本」分頁中,選取要存取的密鑰版本。

  4. 按一下與密鑰版本相關聯的 「Actions」(動作) 選單,然後按一下「View secret value」(查看密鑰值)

  5. 畫面上會出現一個顯示密鑰版本值的對話方塊。按一下「完成」即可關閉對話方塊。

gcloud

存取密鑰版本

使用下列任何指令資料之前,請先替換以下項目:

  • VERSION_ID:密鑰版本的資源名稱
  • SECRET_ID:密鑰的 ID

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud secrets versions access VERSION_ID --secret=SECRET_ID

Windows (PowerShell)

gcloud secrets versions access VERSION_ID --secret=SECRET_ID

Windows (cmd.exe)

gcloud secrets versions access VERSION_ID --secret=SECRET_ID

存取二進位密鑰版本

如要將原始位元組寫入檔案,請使用 --out-file 標記:

使用下列任何指令資料之前,請先替換以下項目:

  • VERSION_ID:密鑰版本的 ID
  • SECRET_ID:密鑰的 ID
  • PATH_TO_SECRET:您要儲存擷取密值的完整路徑 (包括檔案名稱)

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud secrets versions access VERSION_ID --secret=SECRET_ID --out-file="PATH_TO_SECRET"

Windows (PowerShell)

gcloud secrets versions access VERSION_ID --secret=SECRET_ID --out-file="PATH_TO_SECRET"

Windows (cmd.exe)

gcloud secrets versions access VERSION_ID --secret=SECRET_ID --out-file="PATH_TO_SECRET"

取得原始位元組

如要取得原始位元組,請讓 Cloud SDK 以 base64 編碼格式列印回應,然後解碼:

使用下列任何指令資料之前,請先替換以下項目:

  • VERSION_ID:密鑰版本的 ID
  • SECRET_ID:密鑰的 ID

執行下列指令:

Linux、macOS 或 Cloud Shell

gcloud secrets versions access VERSION_ID --secret=SECRET_ID --format='get(payload.data)' | tr '_-' '/+' | base64 -d

Windows (PowerShell)

gcloud secrets versions access VERSION_ID --secret=SECRET_ID --format='get(payload.data)' | tr '_-' '/+' | base64 -d

Windows (cmd.exe)

gcloud secrets versions access VERSION_ID --secret=SECRET_ID --format='get(payload.data)' | tr '_-' '/+' | base64 -d

回應包含密鑰版本。

REST

存取密鑰版本

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:專案 ID Google Cloud
  • SECRET_ID:密鑰的 ID
  • VERSION_ID:密鑰版本的 ID

HTTP 方法和網址:

GET https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID/versions/VERSION_ID:access

JSON 要求主體:

{}

如要傳送要求,請選擇以下其中一個選項:

curl

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X GET \
-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/SECRET_ID/versions/VERSION_ID:access"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

$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.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID/versions/VERSION_ID:access" | Select-Object -Expand Content

您應該會收到如下的 JSON 回應:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/VERSION_ID",
  "payload": {
    "data": "c2VDcjN0Cg==",
    "dataCrc32c": "3131222104"
  }
}

使用 jq 工具擷取密鑰

回應 payload.data 是以 base64 編碼的密鑰版本內容。 以下指令是使用 jq 工具擷取密鑰的範例。

    $ curl "https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID/versions/VERSION_ID:access" \
       --request "GET" \
       --header "authorization: Bearer $(gcloud auth print-access-token)" \
       --header "content-type: application/json" \
       | jq -r ".payload.data" | base64 --decode
  

C#

如要執行這段程式碼,請先設定 C# 開發環境,並安裝 Secret Manager C# SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證


using System;
using Google.Cloud.SecretManager.V1;

public class AccessSecretVersionSample
{
    public String AccessSecretVersion(
      string projectId = "my-project", string secretId = "my-secret", string secretVersionId = "123")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretVersionName secretVersionName = new SecretVersionName(projectId, secretId, secretVersionId);

        // Call the API.
        AccessSecretVersionResponse result = client.AccessSecretVersion(secretVersionName);

        // Convert the payload to a string. Payloads are bytes by default.
        String payload = result.Payload.Data.ToStringUtf8();
        return payload;
    }
}

Go

如要執行這段程式碼,請先設定 Go 開發環境,並安裝 Secret Manager Go SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

import (
	"context"
	"fmt"
	"hash/crc32"
	"io"

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

// accessSecretVersion accesses the payload for the given secret version if one
// exists. The version can be a version number as a string (e.g. "5") or an
// alias (e.g. "latest").
func accessSecretVersion(w io.Writer, name string) error {
	// name := "projects/my-project/secrets/my-secret/versions/5"
	// name := "projects/my-project/secrets/my-secret/versions/latest"

	// 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.AccessSecretVersionRequest{
		Name: name,
	}

	// Call the API.
	result, err := client.AccessSecretVersion(ctx, req)
	if err != nil {
		return fmt.Errorf("failed to access secret version: %w", err)
	}

	// Verify the data checksum.
	crc32c := crc32.MakeTable(crc32.Castagnoli)
	checksum := int64(crc32.Checksum(result.Payload.Data, crc32c))
	if checksum != *result.Payload.DataCrc32C {
		return fmt.Errorf("Data corruption detected.")
	}

	// WARNING: Do not print the secret in a production environment - this snippet
	// is showing how to access the secret material.
	fmt.Fprintf(w, "Plaintext: %s\n", string(result.Payload.Data))
	return nil
}

Java

如要執行這段程式碼,請先設定 Java 開發環境,並安裝 Secret Manager Java SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

import com.google.cloud.secretmanager.v1.AccessSecretVersionResponse;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretVersionName;
import java.io.IOException;
import java.util.zip.CRC32C;
import java.util.zip.Checksum;

public class AccessSecretVersion {

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

  // Access the payload for the given secret version if one exists. The version
  // can be a version number as a string (e.g. "5") or an alias (e.g. "latest").
  public static void accessSecretVersion(String projectId, String secretId, String versionId)
      throws IOException {
    // 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()) {
      SecretVersionName secretVersionName = SecretVersionName.of(projectId, secretId, versionId);

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

      // Verify checksum. The used library is available in Java 9+.
      // If using Java 8, you may use the following:
      // https://github.com/google/guava/blob/e62d6a0456420d295089a9c319b7593a3eae4a83/guava/src/com/google/common/hash/Hashing.java#L395
      byte[] data = response.getPayload().getData().toByteArray();
      Checksum checksum = new CRC32C();
      checksum.update(data, 0, data.length);
      if (response.getPayload().getDataCrc32C() != checksum.getValue()) {
        System.out.printf("Data corruption detected.");
        return;
      }

      // 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 payload = response.getPayload().getData().toStringUtf8();
      System.out.printf("Plaintext: %s\n", payload);
    }
  }
}

Node.js

如要執行這段程式碼,請先設定 Node.js 開發環境,並安裝 Secret Manager Node.js SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const name = 'projects/my-project/secrets/my-secret/versions/5';
// const name = 'projects/my-project/secrets/my-secret/versions/latest';

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

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

async function accessSecretVersion() {
  const [version] = await client.accessSecretVersion({
    name: name,
  });

  // Extract the payload as a string.
  const payload = version.payload.data.toString();

  // WARNING: Do not print the secret in a production environment - this
  // snippet is showing how to access the secret material.
  console.info(`Payload: ${payload}`);
}

accessSecretVersion();

PHP

如要執行這段程式碼,請先瞭解如何在 Google Cloud 上使用 PHP,並安裝 Secret Manager PHP SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

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

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

    // Build the resource name of the secret version.
    $name = $client->secretVersionName($projectId, $secretId, $versionId);

    // Build the request.
    $request = AccessSecretVersionRequest::build($name);

    // Access the secret version.
    $response = $client->accessSecretVersion($request);

    // 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', $payload);
}

Python

如要執行這段程式碼,請先設定 Python 開發環境,然後安裝 Secret Manager Python SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

from google.cloud import secretmanager
import google_crc32c


def access_secret_version(
    project_id: str, secret_id: str, version_id: str
) -> secretmanager.AccessSecretVersionResponse:
    """
    Access the payload for the given secret version if one exists. The version
    can be a version number as a string (e.g. "5") or an alias (e.g. "latest").
    """

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

    # Build the resource name of the secret version.
    name = f"projects/{project_id}/secrets/{secret_id}/versions/{version_id}"

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

    # Verify payload checksum.
    crc32c = google_crc32c.Checksum()
    crc32c.update(response.payload.data)
    if response.payload.data_crc32c != int(crc32c.hexdigest(), 16):
        print("Data corruption detected.")
        return response

    # 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

如要執行這段程式碼,請先設定 Ruby 開發環境,然後安裝 Secret Manager Ruby SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證

# project_id = "YOUR-GOOGLE-CLOUD-PROJECT"  # (e.g. "my-project")
# secret_id  = "YOUR-SECRET-ID"             # (e.g. "my-secret")
# version_id = "YOUR-VERSION"               # (e.g. "5" or "latest")

# 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 secret version.
name = client.secret_version_path(
  project:        project_id,
  secret:         secret_id,
  secret_version: version_id
)

# Access the secret version.
version = client.access_secret_version name: 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 = version.payload.data
puts "Plaintext: #{payload}"

資源一致性

在 Secret Manager 中,新增密鑰版本,然後立即依版本號碼存取該密鑰版本,是強烈一致性作業。

Secret Manager 中的其他作業則具有最終一致性。最終一致性作業通常會在幾分鐘內完成,但也可能需要等待數小時。

傳播 IAM 權限最終會保持一致。這表示授予或撤銷密鑰存取權可能不會立即生效。詳情請參閱「存取權變更傳播」。

後續步驟