建立區域性密鑰

本頁說明如何建立區域密鑰。一個 Secret 包含一或多個 Secret 版本,以及標籤和註解等中繼資料。密鑰的實際內容會儲存在密鑰版本中。

事前準備

  1. 啟用 Secret Manager API。

  2. 在環境中存取區域性密鑰。

  3. 設定驗證方法。

    選取這個頁面上您打算如何使用範例的分頁:

    控制台

    使用 Cloud de Confiance 控制台存取 Cloud de Confiance by S3NS 服務和 API 時,無須設定驗證。

    gcloud

    安裝 Google Cloud CLI,然後 使用聯合身分登入 gcloud CLI。登入後,執行下列指令來初始化 Google Cloud CLI:

    gcloud init

    REST

    如要在本機開發環境中使用本頁的 REST API 範例,請使用您提供給 gcloud CLI 的憑證。

      安裝 Google Cloud CLI,然後 使用聯合身分登入 gcloud CLI。

    詳情請參閱 Cloud de Confiance 驗證說明文件中的「使用 REST 進行驗證」。

必要的角色

如要取得建立密鑰所需的權限,請要求管理員在專案、資料夾或組織中,授予您「Secret Manager 管理員 」(roles/secretmanager.admin) IAM 角色。如要進一步瞭解如何授予角色,請參閱「管理專案、資料夾和組織的存取權」。

您或許也能透過自訂角色或其他預先定義的角色,取得必要權限。

建立區域性密鑰

您可以使用 Cloud de Confiance 控制台、Google Cloud CLI、Secret Manager API 或 Secret Manager 用戶端程式庫建立密鑰。

控制台

  1. 前往 Cloud de Confiance 控制台的「Secret Manager」頁面。

    前往 Secret Manager

  2. 在「Secret Manager」頁面中,按一下「Regional secrets」分頁標籤,然後按一下「Create regional secret」。

  3. 在「建立區域密鑰」頁面的「名稱」欄位中,輸入密鑰名稱。 密鑰名稱可以包含大小寫英文字母、數字、連字號和底線,名稱長度上限為 255 個字元。

  4. (選用) (預覽) 選取「密鑰類型」。您可以透過密鑰類型分類密鑰。

    可用的區域性密鑰類型如下:

    • Cloud SQL 資料庫憑證:用於 Cloud SQL 的代管輪替功能。
    • 其他資料庫憑證:適用於含有資料庫憑證的密鑰。
    • 存取金鑰:適用於含有存取金鑰的密鑰。
    • 憑證:適用於含有憑證的密鑰。
    • 其他:不屬於其他類別的密鑰。
  5. 輸入密鑰值 (例如 abcd1234)。密鑰值可以是任何格式,但不得超過 64 KiB。您也可以使用「上傳檔案」選項,上傳含有密鑰值的文字檔。這項動作會自動建立密鑰版本。

  6. 選擇要儲存區域密鑰的位置。 選取下列選項之一:

    • 區域:將 Secret 儲存在單一區域,盡量縮短延遲時間。
    • 多區域:在多個位置複製密鑰,確保高可用性。詳情請參閱「可用的多區域」。
  7. 點選「建立密鑰」。

gcloud

使用下方的任何指令資料之前,請先替換以下項目:

  • SECRET_ID:密鑰 ID。
  • LOCATION:密鑰的 Cloud de Confiance by S3NS 位置。

執行下列指令:

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:密鑰的 Cloud de Confiance by S3NS 位置。
  • PROJECT_ID: Cloud de Confiance by S3NS 專案 ID。
  • SECRET_ID:密鑰 ID。

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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

如要執行這段程式碼,請先設定 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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

如要執行這段程式碼,請先設定 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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

如要執行這段程式碼,請先設定 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

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

如要執行這段程式碼,請先設定 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 Manager 會使用密鑰版本,自動為密鑰資料建立版本。存取、刪除、停用和啟用等金鑰作業,適用於特定密鑰版本。透過 Secret Manager,您可以將密鑰與特定版本 (例如 42) 或動態別名 (例如 latest) 建立關聯。詳情請參閱「新增密鑰版本」。

存取密鑰版本

如要存取特定密鑰版本的私密資料,請參閱「存取區域性密鑰版本」。

後續步驟