创建区域级密钥

本页介绍了如何创建地区性 Secret。密文包含一个或多个密文版本,以及标签和注释等元数据。密文的实际内容存储在密文版本中。

准备工作

  1. 启用 Secret Manager API

  2. 设置身份验证。

    Select the tab for how you plan to use the samples on this page:

    Console

    When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.

    gcloud

    In the Google Cloud console, activate Cloud Shell.

    Activate Cloud Shell

    At the bottom of the Google Cloud console, a Cloud Shell session starts and displays a command-line prompt. Cloud Shell is a shell environment with the Google Cloud CLI already installed and with values already set for your current project. It can take a few seconds for the session to initialize.

    REST

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

      Install the Google Cloud CLI, then initialize it by running the following command:

      gcloud init

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

所需的角色

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

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

创建区域级密钥

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

控制台

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

    前往 Secret Manager

  2. Secret Manager 页面上,点击区域性 Secret 标签页,然后点击创建区域性 Secret

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

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

  5. 区域列表中选择要存储区域级密钥的位置。

  6. 点击创建密钥

gcloud

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

  • SECRET_ID:Secret 的 ID 或 Secret 的完全限定标识符
  • LOCATION:密钥的 Google Cloud 位置

执行以下命令:

Linux、macOS 或 Cloud Shell

gcloud secrets create SECRET_ID \
    --location=LOCATION

Windows (PowerShell)

gcloud secrets create SECRET_ID `
    --location=LOCATION

Windows (cmd.exe)

gcloud secrets create SECRET_ID ^
    --location=LOCATION

REST

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

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

HTTP 方法和网址:

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

请求 JSON 正文:

{}

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

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.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/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.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/secrets?secretId=SECRET_ID" | Select-Object -Expand Content

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

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

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"
	"google.golang.org/api/option"
)

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

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

	//Endpoint to send the request to regional server
	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()

	parent := fmt.Sprintf("projects/%s/locations/%s", projectId, locationId)

	// Build the request.
	req := &secretmanagerpb.CreateSecretRequest{
		Parent:   parent,
		SecretId: id,
	}

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

Java

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

import com.google.cloud.secretmanager.v1.LocationName;
import com.google.cloud.secretmanager.v1.Secret;
import com.google.cloud.secretmanager.v1.SecretManagerServiceClient;
import com.google.cloud.secretmanager.v1.SecretManagerServiceSettings;
import java.io.IOException;

public class CreateRegionalSecret {

  public static void main(String[] args) throws IOException {
    // 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 to create.
    String secretId = "your-secret-id";
    createRegionalSecret(projectId, locationId, secretId);
  }

  // Create a new regional secret 
  public static Secret createRegionalSecret(
      String projectId, String locationId, String secretId) 
      throws IOException {

    // 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 the 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)) {
      // Build the parent name from the project.
      LocationName location = LocationName.of(projectId, locationId);

      // Build the regional secret to create.
      Secret secret =
          Secret.newBuilder().build();

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

      return createdSecret;
    }
  }
}

Node.js

如需运行此代码,请先设置 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 = 'locationId';
// const secretId = 'my-secret';
const parent = `projects/${projectId}/locations/${locationId}`;

// Imports the Secret Manager libray

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 createRegionalSecret() {
  const [secret] = await client.createSecret({
    parent: parent,
    secretId: secretId,
  });

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

createRegionalSecret();

Python

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

from google.cloud import secretmanager_v1


def create_regional_secret(
    project_id: str,
    location_id: str,
    secret_id: str,
    ttl: Optional[str] = None,
) -> secretmanager_v1.Secret:
    """
    Creates a new regional secret with the given name.
    """

    # 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 parent project.
    parent = f"projects/{project_id}/locations/{location_id}"

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

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

    return response

添加 Secret 版本

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

访问 Secret 版本

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

后续步骤