Nesta página, explicamos como incluir informações confidenciais, como senhas e chaves de API, no Cloud Build.
O Secret Manager é um serviço do Google Cloud que armazena com segurança chaves de API, senhas e outros dados sensíveis. Para incluir informações sensíveis nos seus builds, armazene as informações no Secret Manager e configure o build para acessar as informações do Secret Manager.
Antes de começar
-
Ative as APIs Cloud Build e Secret Manager.
Funções necessárias para ativar APIs
Para ativar APIs, você precisa da permissão
serviceusage.services.enable. Se você criou o projeto, provavelmente já tem essa permissão com o papel de Proprietário (roles/owner). Caso contrário, é possível receber essa permissão com o papel de Administrador do Service Usage (roles/serviceusage.serviceUsageAdmin). Saiba como conceder papéis. Para usar os exemplos de linha de comando neste guia, instale e configure a Google Cloud CLI.
Verifique se você armazenou o secret no Gerenciador de secrets. Para instruções, consulte Como criar um secret.
- Anote o nome e a versão do secret. Você precisará dessas informações para configurar o Cloud Build para acessar o secret.
Permissões do IAM obrigatórias
Conceda o papel do IAM Acessador de secrets do Gerenciador de secrets
(roles/secretmanager.secretAccessor)
para o secret à conta de serviço que você está usando para o build:
Abra a página do Secret Manager no console Google Cloud :
Marque a caixa de seleção do secret que você quer usar no build.
Se ela ainda não estiver aberta, clique em Mostrar painel de informações para abrir o painel.
No painel, em Permissões, clique em Adicionar principal.
No campo Novos principais, insira o endereço de e-mail da sua conta de serviço.
Na caixa suspensa Selecionar um papel, escolha Acessador de secrets do Secret Manager.
Clique em Salvar.
Configurar builds para acessar secrets UTF-8 do Secret Manager
No diretório raiz do projeto, crie um arquivo de configuração do Cloud Build chamado
cloudbuild.yamloucloudbuild.json.No arquivo de configuração de build:
Depois de todos os builds
steps, adicione um campoavailableSecretsque contenha um camposecretManager. O camposecretManagercontém um ou mais pares dos camposversionNameeenv:versionName: o caminho para o secret no Secret Manager. É possível incluir variáveis de substituição no valor desse campo.env: um nome local (variável de ambiente) que as etapas de build podem usar para fazer referência ao secret.
Na etapa de criação, em que você quer especificar o secret:
- Adicione um campo
entrypointque aponte parabashpara usar a ferramenta bash na etapa de versão. Isso é necessário para fazer referência à variável de ambiente do secret. - Adicione um campo
secretEnv. Esse campo especifica quais variáveis de ambiente podem ser usadas nessa etapa. - No campo
args, adicione uma sinalização-ccomo primeiro argumento. Qualquer string que você passar depois de-cserá tratada como um comando. Para mais informações sobre como executar comandos bash com-c, consulte a documentação do bash. - Ao especificar o secret no campo
args, use a variável de ambiente prefixada com$$.
- Adicione um campo
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
In this example, a secret is defined in the build step so that it can be used later in a script:
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_TOKENJSON
{ "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" ] } ] }Use o arquivo de configuração do build para iniciar um build usando a linha de comando ou automatizar builds usando gatilhos.
A seguir
- Saiba como usar credenciais criptografadas em builds.
- Saiba como acessar repositórios GitHub particulares.