访问区域性 Secret 版本

本页介绍了如何访问密文版本。访问密文版本会返回密文内容以及有关密文版本的其他元数据。如需使用 Google Cloud CLI 或 Secret Manager API 访问 Secret 版本,您必须指定其版本 ID别名(如果已分配)。您还可以通过指定 latest 作为版本 ID 来访问 Secret 的最新版本。

所需的角色

如需获得访问密钥版本所需的权限,请让您的管理员为您授予密钥的 Secret Manager Secret Accessor (roles/secretmanager.secretAccessor) IAM 角色。 如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

您也可以通过自定义角色或其他预定义角色来获取所需的权限。

访问 Secret 版本

如需修改 Secret,请使用以下方法之一:

  1. 转到 Google Cloud 控制台中的 Secret Manager 页面。

    前往 Secret Manager

  2. Secret Manager 页面上,点击区域性 Secret 标签页,然后点击某个 Secret 以访问其版本。

  3. 在密文详情页面的版本标签页中,选择要访问的密文版本。

  4. 点击与密钥版本关联的 操作菜单,然后点击查看密钥值

  5. 系统随即会显示一个对话框,其中显示了 Secret 版本的值。点击完成以退出对话框。

在使用下面的命令数据之前,请先进行以下替换:

  • VERSION_ID:Secret 版本的资源名称
  • SECRET_ID:Secret 的 ID 或 Secret 的完全限定标识符
  • LOCATION:Secret 的 Google Cloud 位置

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets versions access VERSION_ID --secret=SECRET_ID --location=LOCATION
gcloud secrets versions access VERSION_ID --secret=SECRET_ID --location=LOCATION
gcloud secrets versions access VERSION_ID --secret=SECRET_ID --location=LOCATION

如需将原始字节写入文件,请使用 --out-file 标志:

在使用下面的命令数据之前,请先进行以下替换:

  • VERSION_ID:Secret 版本的 ID
  • SECRET_ID:Secret 的 ID 或 Secret 的完全限定标识符
  • LOCATION:Secret 的 Google Cloud 位置
  • PATH_TO_SECRET:您要保存检索到的 Secret 值的完整路径(包括文件名)

执行以下命令:

Linux、macOS 或 Cloud Shell

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

如需获取原始字节,请让 Cloud SDK 以 base64 编码和解码形式输出响应:

在使用下面的命令数据之前,请先进行以下替换:

  • VERSION_ID:Secret 版本的 ID
  • SECRET_ID:Secret 的 ID 或 Secret 的完全限定标识符
  • LOCATION:Secret 的 Google Cloud 位置

执行以下命令:

Linux、macOS 或 Cloud Shell

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

响应包含密文版本。

在使用任何请求数据之前,请先进行以下替换:

  • LOCATION:Secret 的 Google Cloud 位置
  • PROJECT_ID: Google Cloud 项目 ID
  • SECRET_ID:Secret 的 ID 或 Secret 的完全限定标识符
  • VERSION_ID:Secret 版本的 ID

HTTP 方法和网址:

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

请求 JSON 正文:

{}

如需发送请求,请选择以下方式之一:

将请求正文保存在名为 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.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets/SECRET_ID/versions/VERSION_ID:access"

将请求正文保存在名为 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.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/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"
  }
}

响应 payload.data 是密文版本的 base64 编码内容。以下命令是使用 jq 工具提取密文的示例。

  $ curl "https://secretmanager.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/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
  

如需运行此代码,请先设置 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"
	"google.golang.org/api/option"
)

// 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 AccessRegionalSecretVersion(w io.Writer, projectId, locationId, secretId, versionId string) error {
	// name := "projects/my-project/locations/my-location/secrets/my-secret/versions/5"
	// name := "projects/my-project/locations/my-location/secrets/my-secret/versions/latest"

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

	// Endpoint to call the regional secret manager sever
	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()

	name := fmt.Sprintf("projects/%s/locations/%s/secrets/%s/versions/%s", projectId, locationId, secretId, versionId)

	// 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 regional 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 开发环境安装 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.SecretManagerServiceSettings;
import com.google.cloud.secretmanager.v1.SecretPayload;
import com.google.cloud.secretmanager.v1.SecretVersionName;
import java.util.zip.CRC32C;
import java.util.zip.Checksum;

public class AccessRegionalSecretVersion {

  public static void main(String[] args)throws Exception {
    // 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.
    String secretId = "your-secret-id";
    // Version of the Secret ID you want to access.
    String versionId = "your-version-id";
    accessRegionalSecretVersion(projectId, locationId, 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 SecretPayload accessRegionalSecretVersion(
      String projectId, String locationId, String secretId, String versionId)
      throws Exception {

    // 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 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)) {
      SecretVersionName secretVersionName = 
          SecretVersionName.ofProjectLocationSecretSecretVersionName(
              projectId, locationId, secretId, versionId);
      // Access the secret version.
      AccessSecretVersionResponse response = client.accessSecretVersion(secretVersionName);

      // Verify checksum. The used library is available in Java 9+.
      // For Java 8, use:
      // 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.");
        throw new Exception("Data corruption detected.");
      }

      // 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);

      return response.getPayload();
    }
  }
}

如需运行此代码,请先设置 Node.js 开发环境安装 Secret Manager Node.js SDK。 在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'my-project';
// const locationId = 'location-id';
// const secretId = 'my-secret'
// const version = 'secret-version';

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

// 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 accessRegionalSecretVersion() {
  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}`);
}

accessRegionalSecretVersion();

如需运行此代码,请先设置 Python 开发环境安装 Secret Manager Python SDK。在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

from google.cloud import secretmanager_v1
import google_crc32c


def access_regional_secret_version(
    project_id: str,
    location_id: str,
    secret_id: str,
    version_id: str,
) -> secretmanager_v1.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").
    """

    # 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 secret version.
    name = f"projects/{project_id}/locations/{location_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}")

    return response

资源一致性

在 Secret Manager 中,添加密文版本,然后立即按版本号访问该密文版本是一项具有高度一致性的操作。

Secret Manager 中的其他操作具有最终一致性。最终一致性操作通常会在几分钟内完成收敛,但可能需要几个小时。

应用 IAM 权限会实现最终一致性。这意味着授予或撤销对密文的访问权限可能不会立即生效。如需了解详情,请参阅访问权限更改传播

后续步骤