Using environment secrets as build arguments in Google Cloud Build

December 27, 2018

Google Cloud Build is a pretty nice tool for building your docker images continually, and cloud-build-local is pretty great for working on your images in dev. All around, a nice piece of kit to have in a Kubernetes shop.

The docs are pretty good, but one thing that I’ve recently dealt with did not show up in my searching; how to use an environment secret as a build argument to Docker. So here’s how I found to do it.

First, we will follow the encrypted secrets guide to get a secret wrapped up by KMS.

Next, we will create a super simple Dockerfile to show how it is used.

Last, we set up the cloudbuild.yaml. In the documentation demo files they use a shell entrypoint to access the environment variable.

However, it would be nicer to not have to stringify our whole Docker build command.

Luckily, using --build-arg without a value falls through to the environment variable of the same name.

So, we can just use it directly:

Testing locally, it happily runs:

It is worth noting that using build args for secrets is not recommended. Anyone with the image can see what the argument passed in was.

Docker 18.09, added build secrets for a better solution, but GCB is still running Docker 17.12, so we will have to wait for that update.

A gist of the code is available at:


  1. Joao says:

    How can this be achieved for a file instead of a single variable?

  2. John Hobbs says:

    I’m not sure Joao. Do you mean as a file in the docker workspace you can reference in the build, or a file filled with environment variables?

    For the file in the workspace you can use the gcloud builder to grab and decrypt the file from KMS and place it into the workspace.

    Not sure how you would use a single KMS file for multiple environment variables.

Leave A Comment

Your email will not be published.