Search code examples
dockergoogle-cloud-platformdockerfilegoogle-container-registry

How to properly get/set env vars during the build via cloudbuild.yaml?


I'm using Google Cloud Container Builder to build my images. I connected it to my GitHub repository so it is triggered by push to specific branch. I provide some env variables to my build step explicitly and using prepositions.

cloudbuild.yaml

steps:
...
- name: gcr.io/cloud-builders/docker
  args: ['build', '-t', 'eu.gcr.io/${PROJECT_ID}/project-name:${SHORT_SHA}', '.']
  env:
    - 'TEST_ENV=test123'
    - 'TEST=${_TEST}'
...

Dockerfile

FROM alpine:latest

RUN printenv

...

I can see my env variables in build details at Env. Vars section of this build step when build is triggered: TEST_ENV=test123 TEST=test_prepositon

But when RUN printenv is executed I see only HOSTNAME, SHLVL, HOME, PATH, PWD env vars.

Where is my mistake? Thank you in advance.


Solution

  • Your example is passing your environment variables to the docker command but not to the docker build context.

    When you set environment variables via env, these envvars are set in the running container. But when docker executes a docker build it does not by default pass the environment though to the build context.

    To set environment variables such that they are accessible in the build context via a RUN directive, pass your docker build a --build-arg.

    Here is Docker's documentation on setting build-time variables.