添加 Secret 版本

Secret 数据不可修改,大多数操作都在 Secret 版本上进行。密文版本包含实际的密文数据,以及有关密文的状态和元数据。本页介绍了如何添加密文版本。

如需详细了解版本控制,请观看有关版本控制的视频

所需的角色

如需获得添加 Secret 版本所需的权限,请让管理员向您授予 Secret 的以下 IAM 角色:

如需详细了解如何授予角色,请参阅管理对项目、文件夹和组织的访问权限

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

不能对密文版本授予 IAM 角色。

添加 Secret 版本

如需添加 Secret 版本,请使用以下方法之一:

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

    前往 Secret Manager

  2. Secret Manager 页面上,找到要为其添加新版本的 Secret。

  3. 点击与该密钥关联的 操作菜单,然后点击添加新版本。系统随即会显示添加新版本对话框。

  4. Secret 值字段中,输入 Secret 的值,例如 abcd1234。 或者,您也可以上传包含 Secret 值的文件。

  5. 点击添加新版本

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

  • SECRET_ID:Secret 的 ID 或 Secret 的完全限定标识符
  • FILE_PATH:包含版本详细信息的文件的完整路径(包括文件名)

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets versions add SECRET_ID --data-file="FILE_PATH"
gcloud secrets versions add SECRET_ID --data-file="FILE_PATH"
gcloud secrets versions add SECRET_ID --data-file="FILE_PATH"

响应中包含新创建的 Secret 版本。

您也可以直接在命令行中添加密文版本,但我们不建议这样做,因为它会以明文形式显示在进程列表中,并且可能会被其他系统用户捕获。请注意,包含明文的命令也会显示在您的 shell 历史记录中。

  echo -n "SECRET_DATA" | \
      gcloud secrets versions add SECRET_ID --data-file=-

请替换以下内容:

  • SECRET_DATA:您要存储在 Secret 版本中的数据
  • SECRET_ID:Secret 的 ID 或 Secret 的完全限定标识符

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

  • SECRET_ID:Secret 的 ID 或 Secret 的完全限定标识符
  • FILE_PATH:包含版本详细信息的文件的完整路径(包括文件名)

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets create SECRET_ID --data-file="FILE_PATH"
gcloud secrets create SECRET_ID --data-file="FILE_PATH"
gcloud secrets create SECRET_ID --data-file="FILE_PATH"

响应中包含新创建的 Secret 版本。

对密文数据进行 Base64 编码并将其另存为 shell 变量。

$ SECRET_DATA=$(echo "seCr3t" | base64)

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

  • PROJECT_ID: Google Cloud 项目 ID
  • SECRET_ID:Secret 的 ID 或 Secret 的完全限定标识符

HTTP 方法和网址:

POST https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets/SECRET_ID:addVersion

请求 JSON 正文:

{"payload": {"data": "${SECRET_DATA}"}}

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

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

curl -X POST \
-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:addVersion"

将请求正文保存在名为 request.json 的文件中,然后执行以下命令:

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

您应该收到类似以下内容的 JSON 响应:

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

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


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

public class AddSecretVersionSample
{
    public SecretVersion AddSecretVersion(
      string projectId = "my-project", string secretId = "my-secret",
      string data = "my secret data")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the resource name.
        SecretName secretName = new SecretName(projectId, secretId);

        // Convert the payload to bytes.
        SecretPayload payload = new SecretPayload
        {
            Data = ByteString.CopyFrom(data, Encoding.UTF8),
        };

        // Call the API.
        SecretVersion version = client.AddSecretVersion(secretName, payload);
        return version;
    }
}

如需运行此代码,请先设置 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"
)

// addSecretVersion adds a new secret version to the given secret with the
// provided payload.
func addSecretVersion(w io.Writer, parent string) error {
	// parent := "projects/my-project/secrets/my-secret"

	// Declare the payload to store.
	payload := []byte("my super secret data")
	// Compute checksum, use Castagnoli polynomial. Providing a checksum
	// is optional.
	crc32c := crc32.MakeTable(crc32.Castagnoli)
	checksum := int64(crc32.Checksum(payload, crc32c))

	// 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.AddSecretVersionRequest{
		Parent: parent,
		Payload: &secretmanagerpb.SecretPayload{
			Data:       payload,
			DataCrc32C: &checksum,
		},
	}

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

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

import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretName;
import com.google.cloud.secretmanager.v1.SecretPayload;
import com.google.cloud.secretmanager.v1.SecretVersion;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.util.zip.CRC32C;
import java.util.zip.Checksum;

public class AddSecretVersion {

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

  // Add a new version to the existing secret.
  public static void addSecretVersion(String projectId, String secretId) 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()) {
      SecretName secretName = SecretName.of(projectId, secretId);
      byte[] data = "my super secret data".getBytes();
      // Calculate data checksum. The library is available in Java 9+.
      // If using Java 8, the following library may be used:
      // https://cloud.google.com/appengine/docs/standard/java/javadoc/com/google/appengine/api/files/Crc32c
      Checksum checksum = new CRC32C();
      checksum.update(data, 0, data.length);

      // Create the secret payload.
      SecretPayload payload =
          SecretPayload.newBuilder()
              .setData(ByteString.copyFrom(data))
              // Providing data checksum is optional.
              .setDataCrc32C(checksum.getValue())
              .build();

      // Add the secret version.
      SecretVersion version = client.addSecretVersion(secretName, payload);
      System.out.printf("Added secret version %s\n", version.getName());
    }
  }
}

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

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

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

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

// Payload is the plaintext data to store in the secret
const payload = Buffer.from('my super secret data', 'utf8');

async function addSecretVersion() {
  const [version] = await client.addSecretVersion({
    parent: parent,
    payload: {
      data: payload,
    },
  });

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

addSecretVersion();

如需运行此代码,请先了解如何在 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\AddSecretVersionRequest;
use Google\Cloud\SecretManager\V1\SecretPayload;

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

    // Build the resource name of the parent secret and the payload.
    $parent = $client->secretName($projectId, $secretId);
    $secretPayload = new SecretPayload([
        'data' => 'my super secret data',
    ]);

    // Build the request.
    $request = AddSecretVersionRequest::build($parent, $secretPayload);

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

    // Print the new secret version name.
    printf('Added secret version: %s', $response->getName());
}

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

from google.cloud import secretmanager
import google_crc32c  # type: ignore


def add_secret_version(
    project_id: str, secret_id: str, payload: str
) -> secretmanager.SecretVersion:
    """
    Add a new secret version to the given secret with the provided payload.
    """

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

    # Build the resource name of the parent secret.
    parent = client.secret_path(project_id, secret_id)

    # Convert the string payload into a bytes. This step can be omitted if you
    # pass in bytes instead of a str for the payload argument.
    payload_bytes = payload.encode("UTF-8")

    # Calculate payload checksum. Passing a checksum in add-version request
    # is optional.
    crc32c = google_crc32c.Checksum()
    crc32c.update(payload_bytes)

    # Add the secret version.
    response = client.add_secret_version(
        request={
            "parent": parent,
            "payload": {
                "data": payload_bytes,
                "data_crc32c": int(crc32c.hexdigest(), 16),
            },
        }
    )

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

如需运行此代码,请先设置 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")

# 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_path project: project_id, secret: secret_id

# Add the secret version.
version = client.add_secret_version(
  parent:  name,
  payload: {
    data: "my super secret data"
  }
)

# Print the new secret version name.
puts "Added secret version: #{version.name}"

密文版本状态

在任何给定时间,密文版本可能处于以下某种状态:

  • 已启用 - 处于此状态时,可以访问和描述密文版本。 这是新密文版本的默认状态。

  • 已停用 - 处于此状态时,密文版本无法访问,但密文的内容仍然存在。您可以重新启用密文版本以恢复访问权限。

  • 已销毁 - 在此状态下,密文版本的内容将被舍弃。密文版本不能更改为其他状态。

您需要为已启用和已停用的 Secret 版本付费。您无需为处于已销毁状态的密文版本付费。

后续步骤