DEV Community

Justin Poehnelt
Justin Poehnelt

Posted on • Originally published at justin.poehnelt.com on

Environment Variables in GitHub Docker build-push-action

I recently ran into an issue where I was required to pass environment variables into a Docker container. I was using the docker/build-push-action to build and push the container and everything was working fine until I needed the SENTRY_AUTH_TOKEN environment variable as part of the build step for my NextJS application.

The solution has two parts.

  1. Pass the secret as a build argument in the docker/build-push-action step.
  2. Modify the multi-stage Dockerfile to use the build argument as an environment variable.

GitHub secret to build-args

This part was easy.

- name: Build and push
  uses: docker/build-push-action@v3
  with:
    context: .
    build-args: |
      "SENTRY_AUTH_TOKEN=${{ secrets.SENTRY_AUTH_TOKEN }}"
Enter fullscreen mode Exit fullscreen mode

Dockerfile

The Dockerfile change is also straightforward.

# The SENTRY_AUTH_TOKEN is used to upload the source maps to Sentry
ARG SENTRY_AUTH_TOKEN
ENV SENTRY_AUTH_TOKEN ${SENTRY_AUTH_TOKEN}
Enter fullscreen mode Exit fullscreen mode

The ARG and ENV lines must be in the same stage of the Dockerfile that requires it. If you have multiple stages, you’ll need to add the ARG and ENV lines to each stage.

❗ ❗ ❗ The ARG value will be accessible to anyone that has access to the Docker image. If you are using a private registry, this is not a problem. If you are using a public registry, you should be careful about what you pass as an ARG.

And it works! 🎉

Top comments (6)

Collapse
 
sarajohn130 profile image
sara john

You should clarify "must be in the same stage" meaning they are under the same image (FROM statement)

Collapse
 
rmontas profile image
Rafael Montás

Just what I needed, thanks!

Collapse
 
dileepamabulage profile image
Dileepa Mabulage

❤❤❤❤❤

Collapse
 
joaomarcos160 profile image
João Marcos

This was exactly what I was looking for, thanks 🙏

Collapse
 
downloadablefox profile image
Downloadable Fox

Really useful, thank you <3

Collapse
 
aissabouguern profile image
Aissa BOUGUERN • Edited

Thank you so much!
I was blocked by this issue 2 days.