创建 Secret

本页面介绍了如何创建 Secret。Secret 包含一个或多个 Secret 版本,以及标签和复制政策等元数据。Secret 的实际内容存储在 Secret 版本中。

准备工作

  1. 启用 Secret Manager API

  2. 设置身份验证。

    选择标签页以了解您打算如何使用本页面上的示例:

    控制台

    当您使用 Google Cloud 控制台访问 Google Cloud 服务和 API 时,无需设置身份验证。

    gcloud

    在 Google Cloud 控制台中,激活 Cloud Shell。

    激活 Cloud Shell

    Cloud Shell 会话随即会在控制台的底部启动,并显示命令行提示符。 Google Cloud Cloud Shell 是一个已安装 Google Cloud CLI 且已为当前项目设置值的 Shell 环境。该会话可能需要几秒钟来完成初始化。

    REST

    如需在本地开发环境中使用本页面上的 REST API 示例,请使用您提供给 gcloud CLI 的 凭证。

      安装 Google Cloud CLI。

      如果您使用的是外部身份提供方 (IdP),则必须先 使用联合身份登录 gcloud CLI

    如需了解详情,请参阅 身份验证文档 中的 Google Cloud 使用 REST 时进行身份验证。

所需的角色

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

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

创建 Secret

您可以使用 Google Cloud 控制台、Google Cloud CLI、Secret Manager API 或 Secret Manager 客户端库创建 Secret。

控制台

  1. 在 Google Cloud 控制台中,前往 Secret Manager 页面。

    前往 Secret Manager

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

  3. 创建 Secret 页面的名称 字段中,输入 Secret 的名称。 Secret 名称可以包含大写和小写字母、数字、连字符和下划线。允许的名称长度上限为 255 个字符。

  4. (预览版) 选择 Secret 类型 。您可以使用 Secret 类型对 Secret 进行分类。

  5. 输入 Secret 的值(例如 abcd1234)。Secret 值可以采用任何格式 但不得超过 64 KiB。您还可以使用 上传文件 选项上传包含 Secret 值的文本文件。此操作会自动创建 Secret 版本。

  6. 点击创建 Secret

gcloud

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

  • SECRET_ID:Secret 的 ID。
  • REPLICATION_POLICY:Secret 的复制政策,可以是自动或用户管理的。

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets create SECRET_ID \
    --replication-policy="REPLICATION_POLICY"

Windows (PowerShell)

gcloud secrets create SECRET_ID `
    --replication-policy="REPLICATION_POLICY"

Windows (cmd.exe)

gcloud secrets create SECRET_ID ^
    --replication-policy="REPLICATION_POLICY"

REST

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

  • PROJECT_ID:项目 ID。 Google Cloud
  • SECRET_ID:Secret 的 ID。
  • REPLICATION_POLICY:Secret 的复制政策,可以是自动或用户管理的。

HTTP 方法和网址:

POST https://secretmanager.googleapis.com/v1/projects/PROJECT_ID/secrets?secretId=SECRET_ID

请求 JSON 正文:

{
  "replication": {
    "REPLICATION_POLICY": {}
  }
}

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

curl

将请求正文保存在名为 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?secretId=SECRET_ID"

PowerShell

将请求正文保存在名为 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?secretId=SECRET_ID" | Select-Object -Expand Content

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

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

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

	secretmanager "cloud.google.com/go/secretmanager/apiv1"
	"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
	"google.golang.org/protobuf/types/known/durationpb"
)

// createSecretWithTTL creates a new secret with the given name and ttl.
func createSecretWithTTL(w io.Writer, parent, id string, d time.Duration) error {
	// parent := "projects/my-project"
	// id := "my-secret"

	expiration := &secretmanagerpb.Secret_Ttl{Ttl: durationpb.New(d)}

	// 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{},
				},
			},
			Expiration: expiration,
		},
	}

	// 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 with ttl: %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 com.google.protobuf.Duration;
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);

      // Optionally set a TTL for the secret. This demonstrates how to configure
      // a secret to be automatically deleted after a certain period. The TTL is
      // specified in seconds (e.g., 900 for 15 minutes). This can be useful
      // for managing sensitive data and reducing storage costs.
      Duration ttl = Duration.newBuilder().setSeconds(900).build();

      // Build the secret to create.
      Secret secret =
          Secret.newBuilder()
              .setReplication(
                  Replication.newBuilder()
                      .setAutomatic(Replication.Automatic.newBuilder().build())
                      .build())
              .setTtl(ttl)
              .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';
// const ttl = undefined // Optional: Specify TTL in seconds (e.g., '900s' for 15 minutes).

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

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

async function createSecret() {
  const secretConfig = {
    replication: {
      automatic: {},
    },
  };

  // Add TTL to the secret configuration if provided
  if (ttl) {
    secretConfig.ttl = {
      seconds: parseInt(ttl.replace('s', ''), 10),
    };
    console.log(`Secret TTL set to ${ttl}`);
  }

  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
    secret: secretConfig,
  });

  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 范围进行身份验证

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


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

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

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

添加 Secret 版本

Secret Manager 会使用 Secret 版本自动对 Secret 数据进行版本控制。密钥操作(例如访问、销毁、停用和启用)会应用于特定的 Secret 版本。借助 Secret Manager,您可以将 Secret 与特定版本(例如 42)或动态别名(例如 latest)相关联。如需了解详情,请参阅添加 Secret 版本

访问 Secret 版本

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

后续步骤