创建 Secret

本主题介绍了如何创建密文。密文包含一个或多个密文版本,以及标签和复制信息等元数据。通过 Secret 的实际内容存储在 Secret 版本中。

准备工作

  1. 为每个项目启用一次 Secret Manager API
  2. 针对项目、文件夹或组织分配 Secret Manager Admin 角色 (roles/secretmanager.admin)。
  3. 使用以下任一方法向 Secret Manager API 进行身份验证:

    • 如果您使用客户端库访问 Secret Manager API,请设置应用默认凭据
    • 如果您使用 Google Cloud CLI 访问 Secret Manager API,请使用您的 Google Cloud CLI 凭据进行身份验证。
    • 如需对 REST 调用进行身份验证,请使用 Google Cloud CLI 凭据或应用默认凭据。

创建 Secret

控制台

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

    转到 Secret Manager 页面

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

  3. 创建密钥页面的名称下,输入密钥的名称(例如 my-secret)。 Secret 名称可以包含大写和小写字母、数字、连字符和下划线。允许的名称长度上限为 255 个字符。

  4. 可选:如需在创建初始 Secret 时也添加 Secret 版本,请在 Secret 值字段中输入 Secret 值(例如 abcd1234)。Secret 值可以采用任何格式,但不得超过 64 KiB。您还可以使用上传文件选项上传包含 Secret 值的文本文件。

  5. 点击创建密钥按钮。

gcloud

如需在命令行上使用 Secret Manager,请先安装或升级到 Google Cloud CLI 378.0.0 或更高版本。在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

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

C#

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


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。 在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

import (
	"context"
	"fmt"
	"io"

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

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

	// 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: %w", err)
	}
	fmt.Fprintf(w, "Created secret: %s\n", result.Name)
	return nil
}

Java

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

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 static 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);
  }

  // Create a new secret with automatic replication.
  public static void createSecret(String projectId, String secretId) throws IOException {
    // 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. 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。 在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

/**
 * 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。 在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

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

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

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

    $secret = new Secret([
        'replication' => new Replication([
            'automatic' => new Automatic(),
        ]),
    ]);

    // Build the request.
    $request = CreateSecretRequest::build($parent, $secretId, $secret);

    // Create the secret.
    $newSecret = $client->createSecret($request);

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

Python

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

def create_secret(
    project_id: str, secret_id: str, ttl: Optional[str] = None
) -> secretmanager.Secret:
    """
    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.

     Args:
        project_id (str): The project ID where the secret is to be created.
        secret_id (str): The ID to assign to the new secret. This ID must be unique within the project.
        ttl (Optional[str]): An optional string that specifies the secret's time-to-live in seconds with
                             format (e.g., "900s" for 15 minutes). If specified, the secret
                             versions will be automatically deleted upon reaching the end of the TTL period.

    Returns:
        secretmanager.Secret: An object representing the newly created secret, containing details like the
                              secret's name, replication settings, and optionally its TTL.

    Example:
        # Create a secret with automatic replication and no TTL
        new_secret = create_secret("my-project", "my-new-secret")

        # Create a secret with a TTL of 30 days
        new_secret_with_ttl = create_secret("my-project", "my-timed-secret", "7776000s")
    """

    # 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": {}}, "ttl": ttl},
        }
    )

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

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

# 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 演示。 您可以使用 gcloud auth print-access-token 生成访问令牌。在 Compute Engine 或 GKE 上,您必须使用 cloud-platform 范围进行身份验证

$ 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" \
    --data "{\"replication\": {\"automatic\": {}}}"

如需为您的 Secret 选择合适的复制政策,请参阅选择复制政策

添加 Secret 版本

Secret Manager 会使用 Secret 版本自动对 Secret 数据进行版本控制,大多数情况 对密钥版本执行访问、销毁、停用和启用等操作。 借助 Secret Manager,您可以将 Secret 固定到 42 或浮动式等特定版本 类似于 latest 的别名。了解如何添加 Secret 版本

访问 Secret 版本

如需访问特定 Secret 版本中的 Secret 数据以便成功进行身份验证, 请参阅访问密钥版本

后续步骤