使用 Secret Manager 建立及存取密鑰
瞭解如何在 Google Cloud上使用 Secret Manager 建立及存取密鑰。
如要直接在 Google Cloud 控制台按照逐步指南操作,請按一下「Guide me」(逐步引導):
事前準備
- 為每個專案啟用 Secret Manager API。
- 在專案、資料夾或機構中指派 Secret Manager 管理員角色 (
roles/secretmanager.admin
)。 使用下列其中一種方式向 Secret Manager API 進行驗證:
- 如果您使用用戶端程式庫存取 Secret Manager API,請設定應用程式預設憑證。
- 如果您使用 Google Cloud CLI 存取 Secret Manager API,請使用 Google Cloud CLI 憑證進行驗證。
- 如要驗證 REST 呼叫,請使用 Google Cloud CLI 憑證或應用程式預設憑證。
建立密鑰及存取密鑰版本
下列範例說明如何建立密鑰,以及存取密鑰版本的內容。
控制台
如要建立密鑰和密鑰版本,請按照下列步驟操作:
-
前往 Google Cloud 控制台的「Secret Manager」頁面。
-
在「Secret Manager」(密鑰管理工具) 頁面中,按一下「Create Secret」(建立密鑰)。
-
在「建立密鑰」頁面的「名稱」下方,輸入
my-secret
。 -
在「Secret value」(密鑰值) 欄位中輸入
my super secret data
。 -
按一下「Create secret」(建立密鑰) 按鈕。
如要存取密鑰版本的內容,請按照下列步驟操作:
gcloud
如要在指令列上使用 Secret Manager,請先安裝或升級至 Google Cloud CLI 378.0.0 以上版本。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證。
如要建立密鑰,並將字串儲存為第一個密鑰版本的內容,請執行下列操作:
$ echo -n "my super secret data" | gcloud secrets create my-secret \
--replication-policy="replication-policy" \
--data-file=-
其中 replication-policy 是 automatic
或 user-managed
。
如要存取特定密鑰版本的內容,請按照下列步驟操作:
$ gcloud secrets versions access 1 --secret="my-secret"
如要存取最新密鑰版本的內容,請按照下列步驟操作:
$ gcloud secrets versions access latest --secret="my-secret"
C#
如要執行這段程式碼,請先設定 C# 開發環境,然後安裝 Secret Manager C# SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證。
Go
如要執行這段程式碼,請先設定 Go 開發環境,並安裝 Secret Manager Go SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證。
Java
如要執行這段程式碼,請先設定 Java 開發環境,並安裝 Secret Manager Java SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證。
Node.js
如要執行這段程式碼,請先設定 Node.js 開發環境,並安裝 Secret Manager Node.js SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證。
PHP
如要執行這段程式碼,請先瞭解如何在 Google Cloud 上使用 PHP,並安裝 Secret Manager PHP SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證。
Python
如要執行這段程式碼,請先設定 Python 開發環境,然後安裝 Secret Manager Python SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證。
Ruby
如要執行這段程式碼,請先設定 Ruby 開發環境,然後安裝 Secret Manager Ruby SDK。在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證。
API
這些範例使用 curl 示範如何使用 API。您可以使用 gcloud auth print-access-token 產生存取權杖。 在 Compute Engine 或 GKE 上,您必須使用 cloud-platform 範圍進行驗證。
如要建立密鑰並將字串儲存為密鑰版本的內容,請按照下列步驟操作:
$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets?secretId=my-secret" \
--request "POST" \
--header "authorization: Bearer $(gcloud auth print-access-token)" \
--header "content-type: application/json" \
--data "{\"replication\": {\"automatic\": {}}}"
如要存取密鑰版本的內容,請按照下列步驟操作:
$ curl "https://secretmanager.googleapis.com/v1/projects/project-id/secrets/my-secret/versions/1:access" \
--request "GET" \
--header "authorization: Bearer $(gcloud auth print-access-token)" \
--header "content-type: application/json"