建立密鑰

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

事前準備

  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 的憑證。

      安裝 Google Cloud CLI。 安裝完成後,執行下列指令初始化 Google Cloud CLI:

      gcloud init

      如果您使用外部識別資訊提供者 (IdP),請先 使用聯合身分登入 gcloud CLI

    詳情請參閱 Google Cloud 驗證說明文件中的「Authenticate for using REST」。

    必要的角色

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

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

    建立密鑰

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

    控制台

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

      前往 Secret Manager

    2. 在「Secret Manager」(密鑰管理工具) 頁面中,按一下「Create secret」(建立密鑰)

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

    4. 輸入密鑰的值 (例如 abcd1234)。密鑰值可採用任何格式,但不得超過 64 KiB。您也可以使用「上傳檔案」選項,上傳含有密鑰值的文字檔。這項動作會自動建立密鑰版本。

    5. 按一下「建立密鑰」

    gcloud

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

    • SECRET_ID:密鑰的 ID 或密鑰的完整 ID
    • REPLICATION_POLICY:密鑰的複製政策,可以是自動或使用者管理。

    執行下列指令:

    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:密鑰的 ID 或密鑰的完整 ID
    • REPLICATION_POLICY:密鑰的複製政策,可以是自動或使用者管理。

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

    存取密鑰版本

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

    後續步驟