创建密文和版本

本主题介绍了如何创建密文添加密文版本以及访问密文版本。如需了解如何管理密文,请参阅管理密文

准备工作

为每个项目配置一次 Secret Manager 和本地环境

创建密文

密文包含一个或多个密文版本,以及标签和复制信息等元数据。密文的实际内容存储在密文版本中。

如果您不确定哪种密文政策适合您的密文,请参阅选择复制政策

创建密文需要具有项目、文件夹或组织的 Secret Manager 管理员角色 (roles/secretmanager.admin)。

网页界面

  1. 转到 Cloud Console 中的 Secret Manager 页面。

    转到 Secret Manager 页面

  2. Secret Manager 页面上,点击创建密钥

  3. 创建密钥页面的名称下,输入 my-secret

  4. (可选)在密文值字段中,输入 abcd1234 还可以在创建初始密文时添加密文版本。

  5. 保持区域部分不变。

  6. 点击创建密钥按钮。

命令行

要在命令行上使用 Secret Manager,请先安装或升级到 Cloud SDK 版本 305.0.0 或更高版本

$ gcloud secrets create secret-id \
    --replication-policy="automatic"

C#

要运行此代码,请先设置 C# 开发环境安装 Secret Manager C# SDK


using Google.Api.Gax.ResourceNames;
using Google.Cloud.SecretManager.V1;

public class CreateSecretSample
{
    public Secret CreateSecret(
      string projectId = "my-project", string secretId = "my-secret")
    {
        // Create the client.
        SecretManagerServiceClient client = SecretManagerServiceClient.Create();

        // Build the parent resource name.
        ProjectName projectName = new ProjectName(projectId);

        // Build the secret.
        Secret secret = new Secret
        {
            Replication = new Replication
            {
                Automatic = new Replication.Types.Automatic(),
            },
        };

        // Call the API.
        Secret createdSecret = client.CreateSecret(projectName, secretId, secret);
        return createdSecret;
    }
}

Go

要运行此代码,请先设置 Go 开发环境安装 Secret Manager Go SDK

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"
)

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

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %v", err)
	}

	// Build the request.
	req := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: id,
		Secret: &secretmanagerpb.Secret{
			Replication: &secretmanagerpb.Replication{
				Replication: &secretmanagerpb.Replication_Automatic_{
					Automatic: &secretmanagerpb.Replication_Automatic{},
				},
			},
		},
	}

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

Java

要运行此代码,请先设置 Java 开发环境安装 Secret Manager Java SDK

import com.google.cloud.secretmanager.v1.ProjectName;
import com.google.cloud.secretmanager.v1.Replication;
import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import java.io.IOException;

public class CreateSecret {

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

  // Add a new version to the existing secret.
  public void createSecret(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()) {
      // Build the parent name from the project.
      ProjectName projectName = ProjectName.of(projectId);

      // Build the secret to create.
      Secret secret =
          Secret.newBuilder()
              .setReplication(
                  Replication.newBuilder()
                      .setAutomatic(Replication.Automatic.newBuilder().build())
                      .build())
              .build();

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

Node.js

要运行此代码,请先设置 Node.js 开发环境安装 Secret Manager Node.js SDK

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

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

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

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

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

createSecret();

PHP

如需运行此代码,请先了解如何在 Google Cloud 上使用 PHP安装 Secret Manager PHP SDK

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

/** Uncomment and populate these variables in your code */
// $projectId = 'YOUR_GOOGLE_CLOUD_PROJECT' (e.g. 'my-project');
// $secretId = 'YOUR_SECRET_ID' (e.g. 'my-secret');

// Create the Secret Manager client.
$client = new SecretManagerServiceClient();

// Build the resource name of the parent project.
$parent = $client->projectName($projectId);

// Create the secret.
$secret = $client->createSecret($parent, $secretId,
    new Secret([
        'replication' => new Replication([
            'automatic' => new Automatic(),
        ]),
    ])
);

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

Python

要运行此代码,请先设置 Python 开发环境安装 Secret Manager Python SDK

def create_secret(project_id, secret_id):
    """
    Create 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.
    """

    # Import the Secret Manager client library.
    from google.cloud import secretmanager

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

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

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

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

Ruby

要运行此代码,请先设置 Ruby 开发环境安装 Secret Manager Ruby SDK

# 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 parent project.
parent = client.project_path project: project_id

# Create the secret.
secret = client.create_secret(
  parent:    parent,
  secret_id: secret_id,
  secret:    {
    replication: {
      automatic: {}
    }
  }
)

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

API

这些示例使用 curl 来使用 API 演示。

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets?secretId=secret-id" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id" \
    --data "{\"replication\": {\"automatic\": {}}}"

添加密文版本

密文版本包含密文的实际内容。密文版本可以启用、停用或销毁。如需更改密文的内容,您需要创建一个新版本。

添加密文需要具有密文、项目、文件夹或组织的 Secret Manager 管理员角色 (roles/secretmanager.admin)。不能对密文版本授予角色。

网页界面

  1. 转到 Cloud Console 中的 Secret Manager 页面。

    转到 Secret Manager 页面

  2. Secret Manager 页面上,点击查看更多 ,然后选择添加新版本

  3. 添加新版本对话框的密文值字段中,输入 abcd1234

  4. 点击添加新版本按钮。

命令行

要在命令行上使用 Secret Manager,请先安装或升级到 Cloud SDK 版本 305.0.0 或更高版本

从磁盘上文件的内容添加密文版本:

$ gcloud secrets versions add secret-id --data-file="/path/to/file.txt"

您也可以直接在命令行中添加密文版本,但我们不建议这样做,因为明文会显示在 shell 历史记录中:

$ echo -n "this is my super secret data" | \
    gcloud secrets versions add secret-id --data-file=-

可选:首次创建密文时,从文件的内容添加版本:

$ gcloud secrets create secret-id --data-file="/path/to/file.txt"

C#

要运行此代码,请先设置 C# 开发环境安装 Secret Manager C# SDK


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

要运行此代码,请先设置 Go 开发环境安装 Secret Manager Go SDK

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"
)

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

	// Create the client.
	ctx := context.Background()
	client, err := secretmanager.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("failed to create secretmanager client: %v", err)
	}

	// Build the request.
	req := &secretmanagerpb.AddSecretVersionRequest{
		Parent: parent,
		Payload: &secretmanagerpb.SecretPayload{
			Data: payload,
		},
	}

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

Java

要运行此代码,请先设置 Java 开发环境安装 Secret Manager Java SDK

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;

public class AddSecretVersion {

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

      // Create the secret payload.
      SecretPayload payload =
          SecretPayload.newBuilder()
              .setData(ByteString.copyFromUtf8("my super secret data"))
              .build();

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

Node.js

要运行此代码,请先设置 Node.js 开发环境安装 Secret Manager Node.js SDK

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

PHP

如需运行此代码,请先了解如何在 Google Cloud 上使用 PHP安装 Secret Manager PHP SDK

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

/** Uncomment and populate these variables in your code */
// $projectId = 'YOUR_GOOGLE_CLOUD_PROJECT' (e.g. 'my-project');
// $secretId = 'YOUR_SECRET_ID' (e.g. 'my-secret');

// Create the Secret Manager client.
$client = new SecretManagerServiceClient();

// Build the resource name of the parent secret.
$parent = $client->secretName($projectId, $secretId);

// Access the secret version.
$response = $client->addSecretVersion($parent, new SecretPayload([
    'data' => 'my super secret data',
]));

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

Python

要运行此代码,请先设置 Python 开发环境安装 Secret Manager Python SDK

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

    # Import the Secret Manager client library.
    from google.cloud import secretmanager

    # 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 = payload.encode("UTF-8")

    # Add the secret version.
    response = client.add_secret_version(
        request={"parent": parent, "payload": {"data": payload}}
    )

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

Ruby

要运行此代码,请先设置 Ruby 开发环境安装 Secret Manager Ruby SDK

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

API

这些示例使用 curl 来使用 API 演示。

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

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

使用 curl 调用 API。

$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/secret-id:addVersion" \
    --request "POST" \
    --header "authorization: Bearer $(gcloud auth print-access-token)" \
    --header "content-type: application/json" \
    --header "x-goog-user-project: project-id" \
    --data "{\"payload\": {\"data\": \"${SECRET_DATA}\"}}"

访问密文版本

访问密文版本会返回密文内容以及有关密文版本的其他元数据。访问密文版本时,您需要指定其 version-id。您还可以通过指定 "latest" 版本来访问密文的最新版本。

访问密文版本需要 Secret Manager Secret Accessor 角色 (roles/secretmanager.secretAccessor),才能对密文、项目、文件夹或组织进行访问。不能对密文版本授予 IAM 角色。

有关资源一致性的说明

在 Secret Manager 中,添加密文版本,然后立即访问该密文版本是一项具有高度一致性的操作。Secret Manager 中的其他操作具有最终一致性。最终一致性操作通常会在几分钟内完成收敛,但可能需要几个小时。

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

网页界面

  1. 转到 Cloud Console 中的 Secret Manager 页面。

    转到 Secret Manager 页面

  2. Secret Manager 页面上,点击密文的名称

  3. 密文详情页面的版本表中,找到要访问的密文版本。

  4. 操作列中,点击查看更多

  5. 从菜单中点击查看密文值

  6. 您将看到显示密文版本值的对话框。点击完成即可完成。

命令行

要在命令行上使用 Secret Manager,请先安装或升级到 Cloud SDK 版本 305.0.0 或更高版本

访问密文版本:

$ gcloud secrets versions access version-id --secret="secret-id"

访问二进制密文版本:

$ gcloud secrets versions access version-id --secret="secret-id" --format='get(payload.data)' | tr '_-' '/+' | base64 -d

C#

要运行此代码,请先设置 C# 开发环境安装 Secret Manager C# SDK


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

import (
	"context"
	"fmt"
	"io"

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"
)

// 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: %v", err)
	}

	// 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: %v", err)
	}

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

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;

public class AccessSecretVersion {

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

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

/**
 * 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

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

/** Uncomment and populate these variables in your code */
// $projectId = 'YOUR_GOOGLE_CLOUD_PROJECT' (e.g. 'my-project');
// $secretId = 'YOUR_SECRET_ID' (e.g. 'my-secret');
// $versionId = 'YOUR_VERSION_ID' (e.g. 'latest' or '5');

// Create the Secret Manager client.
$client = new SecretManagerServiceClient();

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

// Access the secret version.
$response = $client->accessSecretVersion($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 = $response->getPayload()->getData();
printf('Plaintext: %s', $payload);

Python

要运行此代码,请先设置 Python 开发环境安装 Secret Manager Python SDK

def access_secret_version(project_id, secret_id, version_id):
    """
    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").
    """

    # Import the Secret Manager client library.
    from google.cloud import secretmanager

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

    # 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("Plaintext: {}".format(payload))

Ruby

要运行此代码,请先设置 Ruby 开发环境安装 Secret Manager Ruby SDK

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

API

这些示例使用 curl 来使用 API 演示。

$ 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" \
    --header "x-goog-user-project: project-id"

响应 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" \
    --header "x-goog-user-project: project-id" \
    | jq -r ".payload.data" | base64 --decode

后续步骤