Search code examples
google-cloud-buildcloudbuild.yaml

Cloudbuild - build docker image with custom variable from a different step


I want to achieve the following build process:

  • decide the value of environment var depending on the build branch
  • persist this value through diff build steps
  • use this var to pass it as build-arg to docker build

Here is some of the cloudbuild config I've got:

  - id: 'Get env from branch'
    name: bash
    args:
      - '-c'
      - |-
        environment="dev"
        if [[ "${BRANCH_NAME}" == "staging" ]]; then
          environment="stg"
        elif [[ "${BRANCH_NAME}" == "master" ]]; then
          environment="prd"
        fi
        echo $environment > /workspace/environment.txt

  - id: 'Build Docker image'
    name: bash
    dir: $_SERVICE_DIR
    args:
      - '-c'
      - |-
        environment=$(cat /workspace/environment.txt)
        echo "===== ENV: $environment"
        docker build --build-arg ENVIRONMENT=$environment -t gcr.io/${_GCR_PROJECT_ID}/${_SERVICE_NAME}/${COMMIT_SHA} .

The problem lies in the 2nd step. If I use bash step image, then I've got no docker executable in order to build my custom image.

And if I use gcr.io/cloud-builders/docker step image, then I can't execute bash scripts. In the args field I can only pass arguments for the docker executable. And this way I cannot extract the value of environment that I've persisted through the steps of the build.

The way I managed to accomplish both is to use my own, custom, pre-built image, which contains both bash and docker executables. I have that image in the container registry and I use it as the build step image. But this requires some custom work from my side. I was wondering if there is a better, more standardized way with built-in tools from cloudbuild.

Sources:


Solution

  • You can change the default entrypoint by adding entrypoint: parameter

      - name: 'gcr.io/cloud-builders/docker'
        entrypoint: 'bash'
        args:
          - -c
          - |
            echo $PROJECT_ID
            environment=$(cat /workspace/environment.txt)
            echo "===== ENV: $environment"
            docker build --build-arg ENVIRONMENT=$environment -t gcr.io/${_GCR_PROJECT_ID}/${_SERVICE_NAME}/${COMMIT_SHA} .