Sostituzione dei valori delle variabili

Utilizza substitutions nel file di configurazione della build per sostituire variabili specifiche in tempo di compilazione.

Le sostituzioni sono utili per le variabili il cui valore non è noto fino al tempo di compilazione o per riutilizzare una richiesta di build esistente con valori di variabile diversi.

Cloud Build fornisce sostituzioni integrate oppure puoi definire le tue sostituzioni. Utilizza substitutions in steps e images della build per risolvere i relativi valori in tempo di compilazione.

Questa pagina spiega come utilizzare sostituzioni predefinite o personalizzate substitutions.

Utilizzo delle sostituzioni predefinite

Cloud Build fornisce le seguenti sostituzioni predefinite per tutte le build:

  • $PROJECT_ID: l'ID del tuo progetto Cloud
  • $BUILD_ID: l'ID della build
  • $PROJECT_NUMBER: il numero di progetto
  • $LOCATION: la regione associata alla build

Cloud Build fornisce le seguenti sostituzioni predefinite per le build richiamate dai trigger:

  • $TRIGGER_NAME: il nome associato all'attivatore
  • $COMMIT_SHA: l'ID commit associato alla build
  • $REVISION_ID: l'ID commit associato alla build
  • $SHORT_SHA : i primi sette caratteri di COMMIT_SHA
  • $REPO_NAME: il nome del repository
  • $REPO_FULL_NAME: il nome completo del repository, incluso l'utente o l'organizzazione
  • $BRANCH_NAME: il nome del ramo
  • $TAG_NAME: il nome del tag
  • $REF_NAME: il nome del ramo o del tag
  • $TRIGGER_BUILD_CONFIG_PATH: il percorso del file di configurazione della build utilizzato durante l'esecuzione della build; in caso contrario, una stringa vuota se la build è configurata inline sul trigger o utilizza un Dockerfile o Buildpack.
  • $SERVICE_ACCOUNT_EMAIL: l'email del account di servizio che utilizzi per la build. Si tratta di un account di servizio predefinito o specificato dall'utente.
  • $SERVICE_ACCOUNT: il nome della risorsa del account di servizio, nel formato projects/PROJECT_ID/serviceAccounts/SERVICE_ACCOUNT_EMAIL

Cloud Build fornisce le seguenti sostituzioni predefinite specifiche di GitHub disponibili per i trigger per richieste di pull:

  • $_HEAD_BRANCH : il ramo principale della richiesta di pull
  • $_BASE_BRANCH : il ramo di base della richiesta di pull
  • $_HEAD_REPO_URL : URL del repository head della richiesta di pull
  • $_PR_NUMBER : numero della richiesta di pull

Se non è disponibile una sostituzione predefinita (ad esempio con build senza origine o con build che utilizzano l'origine di archiviazione), le occorrenze della variabile mancante vengono sostituite con una stringa vuota.

Quando avvii una build utilizzando gcloud builds submit, puoi specificare variabili che normalmente provengono da build attivate con l'argomento --substitutions. Nello specifico, puoi fornire manualmente i valori per:

  • $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

Ad esempio, il seguente comando utilizza la sostituzione TAG_NAME:

gcloud builds submit --config=cloudbuild.yaml \
    --substitutions=TAG_NAME="test"

L'esempio seguente utilizza le sostituzioni predefinite $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"
  ]
}

L'esempio seguente mostra una richiesta di build che utilizza il passaggio di build docker per creare un'immagine, quindi esegue il push dell'immagine ad Artifact Registry utilizzando la sostituzione $PROJECT_ID predefinita:

In questo esempio:

  • La richiesta di build ha un passaggio di build, che utilizza il passaggio di build docker in gcr.io/cloud-builders per creare l'immagine Docker.
    • Il campo args nel passaggio specifica gli argomenti da passare al comando docker, in questo caso verrà richiamato build -t gcr.io/my-project/cb-demo-img . (dopo che $PROJECT_ID è stato sostituito con l'ID progetto).
  • Il campo images contiene il nome dell'immagine. Se la build ha esito positivo, l'immagine risultante viene inviata ad Artifact Registry. Se l'immagine non viene creata correttamente dalla build, la build non andrà a buon fine.

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"
  ]
}

Utilizzo di sostituzioni definite dall'utente

Puoi anche definire le tue sostituzioni. Le sostituzioni definite dall'utente devono rispettare le seguenti regole:

  • Le sostituzioni devono iniziare con un trattino basso (_) e utilizzare solo lettere maiuscole e numeri (rispettando l'espressione regolare _[A-Z0-9_]+). In questo modo si evitano conflitti con le sostituzioni integrate. Per utilizzare un'espressione che inizia con $, devi utilizzare $$. For example:
    • $FOO is invalid since it is not a built-in substitution.
    • $$FOO che restituisce la stringa letterale $FOO.
  • Il numero di parametri è limitato a 200. La lunghezza di una chiave parametro è limitata a 100 byte e la lunghezza di un valore parametro è limitata a 4000 byte.
  • Puoi specificare le variabili in due modi: $_FOO o ${_FOO}:

    • Sia $_FOO che ${_FOO} restituiscono il valore di _FOO. Tuttavia, ${} consente la sostituzione senza spazi circostanti, il che consente sostituzioni come ${_FOO}BAR.
    • $$ lets you include a literal $ in the template. For example:
      • $_FOO evaluates to the value of _FOO.
      • $$_FOO restituisce la stringa letterale $_FOO.
      • $$$_FOO evaluates to the literal string $ followed by the value of _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:

    • $REPO_NAME
    • $REPO_FULL_NAME
    • $BRANCH_NAME
    • $TAG_NAME
    • $COMMIT_SHA
    • $SHORT_SHA

    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"
      }
    }
    
    
    

    Per saperne di più sui secret in Cloud Build, consulta Utilizzare i secret di Secret Manager nella documentazione di Cloud Build.

    Mappatura delle sostituzioni alle variabili di ambiente

    Gli script non supportano direttamente le sostituzioni, ma supportano le variabili di ambiente. Puoi mappare le sostituzioni alle variabili di ambiente, in modo automatico tutte in una volta o manualmente definendo ogni variabile di ambiente personalmente.

    Mappare automaticamente le sostituzioni

    • A livello di build. Per mappare automaticamente tutte le sostituzioni alle variabili di ambiente, che saranno disponibili durante l'intera build, imposta automapSubstitutions su true come opzione a livello di build. Ad esempio, il seguente file di configurazione della build mostra la sostituzione $_USER definita dall'utente e la sostituzione $PROJECT_ID predefinita mappate alle variabili di 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"
        }
      }
      
    • A livello di passaggio. Per mappare automaticamente tutte le sostituzioni e renderle disponibili come variabili di ambiente in un unico passaggio, imposta il campo automapSubstitutions su true in questo passaggio. Nell'esempio seguente, solo il secondo passaggio mostrerà le sostituzioni correttamente, perché è l'unico con la mappatura delle sostituzioni automatiche attivata:

      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"
        }
      

      Inoltre, puoi rendere disponibili le sostituzioni come variabili di ambiente nell'intera build, quindi ignorarle in un unico passaggio. Imposta automapSubstitutions su true a livello di build, quindi imposta lo stesso campo su false nel passaggio in cui vuoi ignorare le sostituzioni. Nell'esempio seguente, anche se le sostituzioni del mapping sono abilitate a livello di build, l'ID progetto non verrà stampato nel secondo passaggio, perché automapSubstitutions è impostato su false in questo passaggio:

      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"
        }
      

    Mappare manualmente le sostituzioni

    Puoi mappare manualmente le sostituzioni alle variabili di ambiente. Ogni variabile di ambiente è definita a livello di passaggio utilizzando il campo env e l'ambito delle variabili è limitato al passaggio in cui sono definite. Questo campo accetta un elenco di chiavi e valori.

    L'esempio seguente mostra come mappare la sostituzione $PROJECT_ID alla variabile di ambiente BAR:

    YAML

    steps:
    - name: 'ubuntu'
      env:
      - 'BAR=$PROJECT_ID'
      script: 'echo $BAR'
    

    JSON

    {
      "steps": [
        {
          "name": "ubuntu",
          "env": [
            "BAR=$PROJECT_ID"
          ],
          "script": "echo $BAR"
        }
      ]
    }
    

    Passaggi successivi