Use substitutions no arquivo de configuração da build para substituir variáveis específicas no tempo de build.
As substituições são úteis para variáveis cujo valor não é conhecido até o momento da criação ou para reutilizar uma solicitação de versão existente com diferentes valores variáveis.
O Cloud Build fornece substituições integradas ou você pode definir as próprias substituições. Use substitutions no steps e no images do build para resolver os valores no tempo da compilação.
Nesta página, explicamos como usar substituições padrão ou definir sua própria substitutions.
Como usar substituições padrão
O Cloud Build fornece as seguintes substituições padrão para todas as versões:
$PROJECT_ID: ID do projeto do Cloud$BUILD_ID: ID da sua versão$PROJECT_NUMBER: o ID do seu projeto$LOCATION: a região associada ao build
O Cloud Build fornece as seguintes substituições padrão para versões invocadas por gatilhos:
$TRIGGER_NAME: o nome associado ao gatilho$COMMIT_SHA: o ID de confirmação associado à sua versão$REVISION_ID: o ID de confirmação associado à sua versão$SHORT_SHA: os primeiros sete caracteres deCOMMIT_SHA$REPO_NAME: o nome do seu repositório$REPO_FULL_NAME: o nome completo do repositório, incluindo o usuário ou a organização$BRANCH_NAME: o nome da sua ramificação$TAG_NAME: o nome da sua tag$REF_NAME: o nome da sua ramificação ou tag$TRIGGER_BUILD_CONFIG_PATH: o caminho para o arquivo de configuração do build usado durante a execução. Caso contrário, uma string vazia se o build estiver configurado inline no gatilho ou usar umDockerfileouBuildpack.$SERVICE_ACCOUNT_EMAIL: e-mail da conta de serviço que você está usando para o build. Pode ser uma conta de serviço padrão ou especificada pelo usuário.$SERVICE_ACCOUNT: o nome do recurso da conta de serviço, no formatoprojects/PROJECT_ID/serviceAccounts/SERVICE_ACCOUNT_EMAIL
O Cloud Build fornece as seguintes substituições padrão específicas do GitHub disponíveis para acionadores de solicitação de envio:
$_HEAD_BRANCH: ramificação principal da solicitação de envio$_BASE_BRANCH: ramificação base da solicitação de envio$_HEAD_REPO_URL: URL do repositório principal da solicitação de envio$_PR_NUMBER: número da solicitação de envio
Se uma substituição padrão não estiver disponível, como versões sem código-fonte ou versões que usam um código-fonte do armazenamento, as ocorrências em que as variáveis estão ausentes serão substituídas por uma string vazia.
Ao iniciar uma versão usando gcloud builds submit, é possível especificar variáveis que normalmente viriam de versões acionadas com o --substitutionsargumento. Mais especificamente, você pode fornecer manualmente valores para:
$TRIGGER_NAME$COMMIT_SHA$REVISION_ID$SHORT_SHA$REPO_NAME$REPO_FULL_NAME$BRANCH_NAME$TAG_NAME$REF_NAME$TRIGGER_BUILD_CONFIG_PATH$SERVICE_ACCOUNT_EMAIL$SERVICE_ACCOUNT
Por exemplo, o seguinte comando usa a substituição TAG_NAME:
gcloud builds submit --config=cloudbuild.yaml \
--substitutions=TAG_NAME="test"
No exemplo a seguir, são usadas as substituições padrão $BUILD_ID, $PROJECT_ID, $PROJECT_NUMBER e $REVISION_ID.
YAML
steps:
# Uses the ubuntu build step:
# to run a shell script; and
# set env variables for its execution
- name: 'ubuntu'
args: ['bash', './myscript.sh']
env:
- 'BUILD=$BUILD_ID'
- 'PROJECT_ID=$PROJECT_ID'
- 'PROJECT_NUMBER=$PROJECT_NUMBER'
- 'REV=$REVISION_ID'
# Uses the docker build step to build an image called my-image
- name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t', '${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/my-image', '.']
# my-image is pushed to Artifact Registry
images:
- '${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/my-image'
JSON
{
"steps": [{
"name": "ubuntu",
"args": [
"bash",
"./myscript.sh"
],
"env": [
"BUILD=$BUILD_ID",
"PROJECT_ID=$PROJECT_ID",
"PROJECT_NUMBER=$PROJECT_NUMBER",
"REV=$REVISION_ID"
]
}, {
"name": "gcr.io/cloud-builders/docker",
"args": ["build", "-t", "gcr.io/$PROJECT_ID/my-image", "."]
}],
"images": [
"gcr.io/$PROJECT_ID/my-image"
]
}
No exemplo abaixo, mostramos o uso da etapa de build docker por uma solicitação de build para
criar uma imagem e transmiti-la para o Artifact Registry usando a substituição padrão
$PROJECT_ID:
Neste exemplo:
- A solicitação de build tem uma etapa de build que usa
dockeremgcr.io/cloud-builderspara criar a imagem Docker.- Os argumentos que serão passados para o comando
dockersão especificados pelo campoargs. Neste caso,build -t gcr.io/my-project/cb-demo-img .será invocado depois da substituição de$PROJECT_IDpelo ID do projeto.
- Os argumentos que serão passados para o comando
O campo
imagescontém o nome da imagem. Se a build for bem-sucedida, a imagem resultante será transmitida para o Artifact Registry. Se a versão não criar a imagem corretamente, ela falhará.
YAML
steps:
- name: gcr.io/cloud-builders/docker
args: ["build", "-t", "${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/cb-demo-img", "."]
images:
- '${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/cb-demo-img'
JSON
{
"steps": [{
"name": "gcr.io/cloud-builders/docker",
"args": ["build", "-t", "${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/cb-demo-img", "."]
}],
"images": [
"${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/cb-demo-img"
]
}
Como usar substituições definidas pelo usuário
Você também pode definir suas próprias substituições. As substituições definidas pelo usuário precisam obedecer às seguintes regras:
- É obrigatório que as substituições comecem com um sublinhado (
_) e que sejam usadas somente letras maiúsculas e números (respeitando a expressão regular_[A-Z0-9_]+). Isso evita conflitos com substituições integradas. Para usar uma expressão que comece com$, use$$. For example:$FOOis invalid since it is not a built-in substitution.$$FOO, que avalia de acordo com a string literal$FOO.
- O número de parâmetros é limitado a 200. O comprimento de uma chave de parâmetro é limitado a 100 bytes e o comprimento de um valor de parâmetro é limitado a 4000 bytes.
- Tanto
$_FOOquanto${_FOO}avaliam o valor de_FOO. No entanto,${}permite que a substituição funcione sem espaços ao redor, o que permite substituições como${_FOO}BAR. $$lets you include a literal$in the template. For example:$_FOOevaluates to the value of_FOO.$$_FOOavalia de acordo com a string literal$_FOO.$$$_FOOevaluates to the literal string$followed by the value of_FOO.
$REPO_NAME$REPO_FULL_NAME$BRANCH_NAME$TAG_NAME$COMMIT_SHA$SHORT_SHANo nível do build. Para mapear automaticamente todas as substituições para variáveis de ambiente, que estarão disponíveis em todo o build, defina
automapSubstitutionscomotruecomo uma opção no nível do build. Por exemplo, o arquivo de configuração de build a seguir mostra a substituição$_USERdefinida pelo usuário e a substituição padrão$PROJECT_IDmapeadas para variáveis de ambiente:YAML
steps: - name: 'ubuntu' script: | #!/usr/bin/env bash echo "Hello $_USER" - name: 'ubuntu' script: | #!/usr/bin/env bash echo "Your project ID is $PROJECT_ID" options: automapSubstitutions: true substitutions: _USER: "Google Cloud"JSON
{ "steps": [ { "name": "ubuntu", "script": "#!/usr/bin/env bash echo 'Hello $_USER'" }, { "name": "ubuntu", "script": "#!/usr/bin/env bash echo 'Your project ID is $PROJECT_ID'" } ], "options": { "automap_substitutions": true }, "substitutions": { "_USER": "Google Cloud" } }No nível da etapa. Para mapear automaticamente todas as substituições e disponibilizá-las como variáveis de ambiente em uma única etapa, defina o campo
automapSubstitutionscomotruenessa etapa. No exemplo a seguir, apenas a segunda etapa vai mostrar as substituições corretamente, porque é a única com o mapeamento de substituições automáticas ativado:YAML
steps: - name: 'ubuntu' script: | #!/usr/bin/env bash echo "Hello $_USER" - name: 'ubuntu' script: | #!/usr/bin/env bash echo "Your project ID is $PROJECT_ID" automapSubstitutions: true substitutions: _USER: "Google Cloud"JSON
{ "steps": [ { "name": "ubuntu", "script": "#!/usr/bin/env bash echo 'Hello $_USER'" }, { "name": "ubuntu", "script": "#!/usr/bin/env bash echo 'Your project ID is $PROJECT_ID'", "automap_substitutions": true } ], }, "substitutions": { "_USER": "Google Cloud" }Além disso, é possível disponibilizar as substituições como variáveis de ambiente em todo o build e ignorá-las em uma etapa. Defina
automapSubstitutionscomotrueno nível da build e defina o mesmo campo comofalsena etapa em que você quer ignorar as substituições. No exemplo a seguir, mesmo que as substituições de mapeamento estejam ativadas no nível da build, o ID do projeto não será impresso na segunda etapa porqueautomapSubstitutionsestá definido comofalsenessa etapa:YAML
steps: - name: 'ubuntu' script: | #!/usr/bin/env bash echo "Hello $_USER" - name: 'ubuntu' script: | #!/usr/bin/env bash echo "Your project ID is $PROJECT_ID" automapSubstitutions: false options: automapSubstitutions: true substitutions: _USER: "Google Cloud"JSON
{ "steps": [ { "name": "ubuntu", "script": "#!/usr/bin/env bash echo 'Hello $_USER'" }, { "name": "ubuntu", "script": "#!/usr/bin/env bash echo 'Your project ID is $PROJECT_ID'", "automap_substitutions": false } ], "options": { "automap_substitutions": true }, }, "substitutions": { "_USER": "Google Cloud" }- Saiba como usar vinculações de payload e expansões de parâmetros bash em substituições.
- Saiba como criar um arquivo de configuração do build básico.
- Saiba como criar e gerenciar gatilhos de compilação.
- Saiba como executar builds manualmente no Cloud Build.
É possível especificar variáveis de duas maneiras: $_FOO ou ${_FOO}:
To use the substitutions, use the --substitutions
argument in the gcloud command
or specify them in the config file.
The following example shows a build config with two user-defined substitutions
called _NODE_VERSION_1 and _NODE_VERSION_2:
YAML
steps:
- name: 'gcr.io/cloud-builders/docker'
args: ['build',
'--build-arg',
'node_version=${_NODE_VERSION_1}',
'-t',
'${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/build-substitutions-nodejs-${_NODE_VERSION_1}',
'.']
- name: 'gcr.io/cloud-builders/docker'
args: ['build',
'--build-arg',
'node_version=${_NODE_VERSION_2}',
'-t',
'${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/build-substitutions-nodejs-${_NODE_VERSION_2}',
'.']
substitutions:
_NODE_VERSION_1: v6.9.1 # default value
_NODE_VERSION_2: v6.9.2 # default value
images: [
'${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/build-substitutions-nodejs-${_NODE_VERSION_1}',
'${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/build-substitutions-nodejs-${_NODE_VERSION_2}'
]
JSON
{
"steps": [{
"name": "gcr.io/cloud-builders/docker",
"args": [
"build",
"--build-arg",
"node_version=${_NODE_VERSION_1}",
"-t",
"${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/build-substitutions-nodejs-${_NODE_VERSION_1}",
"."
]
}, {
"name": "gcr.io/cloud-builders/docker",
"args": [
"build",
"--build-arg",
"node_version=${_NODE_VERSION_2}",
"-t",
"${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/build-substitutions-nodejs-${_NODE_VERSION_2}",
"."
]
}],
"substitutions": {
"_NODE_VERSION_1": "v6.9.1",
"_NODE_VERSION_2": "v6.9.2",
},
"images": [
"${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/build-substitutions-nodejs-${_NODE_VERSION_1}",
"${_LOCATION}-docker.pkg.dev/$PROJECT_ID/${_REPOSITORY}/build-substitutions-nodejs-${_NODE_VERSION_2}"
]
}
To override the substitution value you specified in the build config file,
use the --substitutions flag in the gcloud builds submit command. Note
that substitutions are a mapping of variables to values rather than arrays or
sequences. You can override default substitution variable
values except for $PROJECT_ID and $BUILD_ID. The following command overrides
the default value for _NODE_VERSION_1 specified in the previous build config
file:
gcloud builds submit --config=cloudbuild.yaml \
--substitutions=_NODE_VERSION_1="v6.9.4",_NODE_VERSION_2="v6.9.5" .
By default, the build returns an error if there's a
missing substitution variable or a missing substitution. However, you can set
the ALLOW_LOOSE option to skip this check.
The following snippet prints "hello world" and defines an unused substitution.
Because the ALLOW_LOOSE substitution option is set, the build will be
successful despite the missing substitution.
YAML
steps:
- name: 'ubuntu'
args: ['echo', 'hello world']
substitutions:
_SUB_VALUE: unused
options:
substitutionOption: 'ALLOW_LOOSE'
JSON
{
"steps": [
{
"name": "ubuntu",
"args": [
"echo",
"hello world"
]
}
],
"substitutions": {
"_SUB_VALUE": "unused"
},
"options": {
"substitution_option": "ALLOW_LOOSE"
}
}
If your build is invoked by a trigger, the ALLOW_LOOSE option is set by
default. In this case, your build won't return an error if there is a
missing substitution variable or a missing substitution. You cannot override
the ALLOW_LOOSE option for builds invoked by triggers.
If the ALLOW_LOOSE option is not specified, unmatched keys in your substitutions
mapping or build request will result in error. For example, if your build request
includes $_FOO and the substitutions mapping doesn't define _FOO, you
will receive an error after running your build or invoking a trigger if your
trigger includes substitution variables.
The following substitution variables always contain a default empty-string
value even if you don't set the ALLOW_LOOSE option:
When defining a substitution variable, you aren't limited to static strings. You also have access to the event payload that invoked your trigger. These are available as payload bindings. You can also apply bash parameter expansions on substitution variables and store the resulting string as a new substitution variable. To learn more, see Using payload bindings and bash parameter expansions in substitutions.
Dynamic substitutions
You can reference the value of another variable within a user-defined
substitution by setting the dynamicSubstitutions option to true in
your build config file. If your build is invoked by a trigger, the
dynamicSubstitutions field is always set to true and does not need to
be specified in your build config file. If your build is invoked manually,
you must set the dynamicSubstitutions field to true for bash parameter
expansions to be interpreted when running your build.
The following build config file shows the substitution variable ${_IMAGE_NAME} referencing the variable, ${PROJECT_ID}. The
dynamicSubstitutions field is set to true so the reference
is applied when invoking a build manually:
YAML
steps:
- name: 'gcr.io/cloud-builders/docker'
args: ['build', '-t', '${_IMAGE_NAME}', '.']
substitutions:
_IMAGE_NAME: '${_LOCATION}-docker.pkg.dev/${PROJECT_ID}/${_REPOSITORY}/test-image'
options:
dynamicSubstitutions: true
JSON
{
"steps": [
{
"name": "gcr.io/cloud-builders/docker",
"args": [
"build",
"-t",
"${_IMAGE_NAME}",
"."
]
}
],
"substitutions": {
"_IMAGE_NAME": "${_LOCATION}-docker.pkg.dev/${PROJECT_ID}/${_REPOSITORY}/test-image"
},
"options": {
"dynamic_substitutions": true
}
}
For more information, see Applying bash parameter expansions.
Secret substitutions
You can substitute secrets from Secret Manager
in Cloud Build. To do so, include your substitution variable in
the value of the versionName field in your build config file.
The following example shows how to define a substitution for a secret version.
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/my-docker-password/versions/$_SECRET_VERSION
env: 'PASSWORD'
- versionName: projects/$PROJECT_ID/secrets/my-docker-username/versions/latest
env: 'USERNAME'
substitutions:
_SECRET_VERSION: '1' #Default value for the secret version
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/my-docker-password/versions/$_SECRET_VERSION", "env": "PASSWORD" }, { "versionName": "projects/$PROJECT_ID/secrets/my-docker-username/versions/latest", "env": "USERNAME" } ] }, "substitutions": { "_SECRET_VERSION": "1" } }Para mais informações sobre secrets no Cloud Build, consulte Usar secrets do Secret Manager na documentação do Cloud Build.
Como mapear substituições para variáveis de ambiente
Os scripts não oferecem suporte direto a substituições, mas são compatíveis com variáveis de ambiente. É possível mapear substituições para variáveis de ambiente, seja automaticamente de uma só vez ou manualmente definindo cada variável de ambiente por conta própria.
Mapear substituições automaticamente
Mapear substituições manualmente
É possível mapear manualmente as substituições para variáveis de ambiente. Cada
variável de ambiente é definida no nível da etapa usando o campo env, e o escopo das variáveis é restrito à etapa
em que elas são definidas. Esse campo usa uma lista de chaves e valores.
O exemplo a seguir mostra como mapear a substituição $PROJECT_ID para a variável de ambiente BAR:
YAML
steps:
- name: 'ubuntu'
env:
- 'BAR=$PROJECT_ID'
script: 'echo $BAR'
JSON
{
"steps": [
{
"name": "ubuntu",
"env": [
"BAR=$PROJECT_ID"
],
"script": "echo $BAR"
}
]
}
A seguir
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
Última atualização 2026-07-13 UTC.