本頁面說明如何在 Cloud Build 中加入密碼及 API 金鑰等機密資訊。
Secret Manager 是一項 Google Cloud 服務,可安全地儲存 API 金鑰、密碼和其他機密資料。如要在建構作業中加入機密資訊,可以將資訊儲存在 Secret Manager 中,然後設定建構作業,從 Secret Manager 存取資訊。
事前準備
-
啟用 Cloud Build 和 Secret Manager API。
啟用 API 時所需的角色
如要啟用 API,您必須具備
serviceusage.services.enable權限。如果您建立了專案,可能已透過「擁有者」角色 (roles/owner) 取得這項權限。否則,您可以透過「服務使用情形管理員」角色 (roles/serviceusage.serviceUsageAdmin) 取得這項權限。瞭解如何授予角色。 如要使用本指南提供的指令列範例,請安裝及設定 Google Cloud CLI。
請務必將密鑰儲存在 Secret Manager。如需操作說明,請參閱「建立 Secret」。
- 記下密鑰名稱和密鑰版本。您需要這些資訊,才能設定 Cloud Build 存取密鑰。
必要 IAM 權限
將「Secret Manager 密鑰存取者」
(roles/secretmanager.secretAccessor) IAM 角色
授予您用於建構作業的服務帳戶:
在 Google Cloud 控制台中開啟「Secret Manager」頁面:
選取要在建構作業中使用的密鑰核取方塊。
若面板尚未開啟,請按一下「Show info panel」(顯示資訊面板) 以開啟面板。
在面板的「權限」下方,按一下「新增主體」。
在「New principals」(新增主體) 欄位中,輸入服務帳戶的電子郵件地址。
在「Select a role」(請選擇角色) 下拉式選單方塊中,選取「Secret Manager Secret Accessor」(Secret Manager 密鑰存取者)。
按一下 [儲存]。
設定建構作業,從 Secret Manager 存取 UTF-8 密鑰
在專案根目錄中,建立名為
cloudbuild.yaml或cloudbuild.json的 Cloud Build 設定檔。在建構設定檔中:
- 完成所有建構作業
steps後,請新增availableSecrets欄位,指定要用於密鑰的 密鑰版本和環境變數。您可以在secretVersion欄位的值中加入替換變數。您可以在建構作業中指定多個密鑰。 - 在要指定密鑰的建構步驟中:
- 新增指向
bash的entrypoint欄位,即可在建構步驟中使用 bash 工具。這是必要步驟,才能參照密鑰的環境變數。 - 新增
secretEnv欄位,指定環境變數。 - 在
args欄位中,新增-c標記做為第一個引數。-c後方傳遞的任何字串都會視為指令。如要進一步瞭解如何使用-c執行 bash 指令,請參閱 bash 說明文件。 - 在
args欄位中指定密鑰時,請使用以$$.
- 新增指向
The following example build config file shows how to login to Docker using the Docker username and password stored in Secret Manager.
YAML
steps: - name: 'gcr.io/cloud-builders/docker' entrypoint: 'bash' args: ['-c', 'docker login --username=$$USERNAME --password=$$PASSWORD'] secretEnv: ['USERNAME', 'PASSWORD'] availableSecrets: secretManager: - versionName: projects/PROJECT_ID/secrets/DOCKER_PASSWORD_SECRET_NAME/versions/DOCKER_PASSWORD_SECRET_VERSION env: 'PASSWORD' - versionName: projects/PROJECT_ID/secrets/DOCKER_USERNAME_SECRET_NAME/versions/DOCKER_USERNAME_SECRET_VERSION env: 'USERNAME'JSON
{ "steps": [ { "name": "gcr.io/cloud-builders/docker", "entrypoint": "bash", "args": [ "-c", "docker login --username=$$USERNAME --password=$$PASSWORD" ], "secretEnv": [ "USERNAME", "PASSWORD" ] } ], "availableSecrets": { "secretManager": [{ "versionName": "projects/PROJECT_ID/secrets/DOCKER_PASSWORD_SECRET_NAME/versions/DOCKER_PASSWORD_SECRET_VERSION", "env": "PASSWORD" }, { "versionName": "projects/PROJECT_ID/secrets/DOCKER_USERNAME_SECRET_NAME/versions/DOCKER_USERNAME_SECRET_VERSION", "env": "USERNAME" }] } }Replace the placeholder values in the preceding commands with the following:
PROJECT_ID: The project ID or project number of the Google Cloud project where you've stored your secrets.DOCKER_USERNAME_SECRET_NAME: The secret name corresponding to your Docker username. You can get the secret name from the Secret Manager page in the Google Cloud console.DOCKER_USERNAME_SECRET_VERSION: The secret version of your Docker username. You can get the secret version by clicking on a secret name on the Secret Manager page in the Google Cloud console.DOCKER_PASSWORD_SECRET_NAME: The secret name corresponding to your Docker password. You can get the secret name from the Secret Manager page in the Google Cloud console.DOCKER_PASSWORD_SECRET_VERSION: The secret version of your Docker password. You can get the secret version by clicking on a secret name on the Secret Manager page in the Google Cloud console.
- 完成所有建構作業
Use the build config file to start a build using the command line or to automate builds using triggers.
Example: Accessing secrets from scripts and processes
secretEnv field adds the value of the secret to the environment and you can
access this value via environment variable from scripts or processes:
YAML
steps:
- name: python:slim
entrypoint: python
args: ['main.py']
secretEnv: ['MYSECRET']
availableSecrets:
secretManager:
- versionName: projects/$PROJECT_ID/secrets/mySecret/versions/latest
env: 'MYSECRET'
JSON
{
"steps": [
{
"name": "python:slim",
"entrypoint": "python",
"args": [
"main.py"
],
"secretEnv": [
"MYSECRET"
]
}
],
"availableSecrets": {
"secretManager": [
{
"versionName": "projects/$PROJECT_ID/secrets/mySecret/versions/latest",
"env": "MYSECRET"
}
]
}
}
The following contents of main.py prints the first five characters of the secret:
import os
print(os.environ.get("MYSECRET", "Not Found")[:5], "...")
Example: authenticating to Docker
In some situations, before interacting with Docker images, your build would need to authenticate to Docker. For example, Docker authentication is required for builds to pull private images and push private or public images to Docker Hub. In these cases, you can store your Docker username and password in Secret Manager and then configure Cloud Build to access the username and password from Secret Manager. For instructions on doing this see Interacting with Docker Hub images.
Example: GitHub pull request creation
Another example where you might want to configure your build to access a sensitive information from Secret Manager is for creating a GitHub pull request in response to builds. To do this:
- Create a GitHub token.
- Store the GitHub token in Secret Manager.
- In your build config file:
- After all the build
steps, add anavailableSecretsfield to specify the secret version and the environment variable to use for the GitHub token. - Add a build step to invoke the command to create a GitHub pull request.
- After all the build
- Create a GitHub app trigger and use the build config file to invoke the trigger.
The following example config file shows how to create a GitHub pull request using the GitHub token:
YAML
steps: - name: 'launcher.gcr.io/google/ubuntu1604' id: Create GitHub pull request entrypoint: bash args: - -c - curl -X POST -H "Authorization:Bearer $$GH_TOKEN" -H 'Accept:application/vnd.github.v3+json' https://api.github.com/repos/GITHUB_USERNAME/REPO_NAME/pulls -d '{"head":"HEAD_BRANCH","base":"BASE_BRANCH", "title":"NEW_PR"}' secretEnv: ['GH_TOKEN'] availableSecrets: secretManager: - versionName: projects/PROJECT_ID/secrets/GH_TOKEN_SECRET_NAME/versions/latest env: GH_TOKEN為前置字元的環境變數指定密鑰。JSON
{ "steps": [ { "name": "launcher.gcr.io/google/ubuntu1604", "id": "Create GitHub pull request", "entrypoint": "bash", "args": [ "-c", "curl -X POST -H \"Authorization:Bearer $$GH_TOKEN\" -H 'Accept:application/vnd.github.v3+json' https://api.github.com/repos/GITHUB_USERNAME/REPO_NAME -d '{\"head\":\"HEAD_BRANCH\",\"base\":\"BASE_BRANCH\", \"title\":\"NEW_PR\"}' ], "secretEnv": ['GH_TOKEN'] } ], "availableSecrets": { "secretManager": [ { "versionName": "projects/PROJECT_ID/secrets/GH_TOKEN_SECRET_NAME/versions/latest", "env": "GH_TOKEN" } ] } }
Replace the placeholder values in the preceding commands with the following:
PROJECT_ID: The project ID or project number of the Google Cloud project where you've stored your secrets.GITHUB_USERNAME: The GitHub username of the repository owner.REPO_NAME: The name of the GitHub repository.HEAD_BRANCH: The name of the branch where the changes are implemented. For cross-repository pull requests in the same network, namespaceheadwith a user like this:username:branch.BASE_BRANCH: The name of the branch you want the changes pulled into. This should be an existing branch on the current repository. You cannot submit a pull request to one repository that requests a merge to a base of another repository.GH_TOKEN_SECRET_NAME: The secret name corresponding to your GitHub token.NEW_PR: The new pull request you want to create.
Configuring builds to access non-UTF-8 secrets from Secret Manager
In your build config file, add a build step to access the secret version in Secret Manager and store it in a file. The following build step accesses secret-name and stores it in a file named decrypted-data.txt:
YAML
steps: - name: gcr.io/cloud-builders/gcloud entrypoint: 'bash' args: [ '-c', "gcloud secrets versions access latest --secret=secret-name --format='get(payload.data)' | tr '_-' '/+' | base64 -d > decrypted-data.txt" ]JSON
{ "steps": [ { "name": "gcr.io/cloud-builders/gcloud", "entrypoint": "bash", "args": [ "-c", "gcloud secrets versions access latest --secret=secret-name --format='get(payload.data)' | tr '_-' '/+' | base64 -d > decrypted-data.txt" ] } ] }Use the file with the decrypted data in a build step. The following code snippet uses decrypted-data.txt to login to a private Docker registry:
YAML
steps: - name: gcr.io/cloud-builders/gcloud entrypoint: 'bash' args: [ '-c', "gcloud secrets versions access latest --secret=secret-name --format='get(payload.data)' | tr '_-' '/+' | base64 -d > decrypted-data.txt" ] - name: gcr.io/cloud-builders/docker entrypoint: 'bash' args: [ '-c', 'docker login --username=my-user --password-stdin < decrypted-data.txt']JSON
{ "steps": [ { "name": "gcr.io/cloud-builders/gcloud", "entrypoint": "bash", "args": [ "-c", "gcloud secrets versions access latest --secret=secret-name --format='get(payload.data)' | tr '_-' '/+' | base64 -d > password.txt" ] }, { "name": "gcr.io/cloud-builders/docker", "entrypoint": "bash", "args": [ "-c", "docker login --username=my-user --password-stdin < decrypted-data.txt" ] } ] }使用建構設定檔透過指令列啟動建構作業,或使用觸發條件自動執行建構作業。
後續步驟
- 瞭解如何在建構中使用加密憑證。
- 瞭解如何存取私人的 GitHub 存放區。