Stamping the commit SHA into the ENV vars of a running Docker-based app

By Orta Therox

For what feels like the last 3-6 months, I’ve been trying to figure out how to know what the commit is for the Docker runtime in Peril. Roughly: every master commit on Peril triggers a Docker image on Docker Hub for the environment in which JavaScript is running. There’s a lag between creating the commit, having the image ready on Docker Hub, and Peril using the new image. There’s also space for these automated systems to go wrong, so I’d like to be able to be certain in logging.

I’ve thrown a lot of commits and time every few weeks at this, so now that I’ve figured it out, I’ll give you an idea of what I needed to do to make it work in a micro-post.

Step 1: You need a custom build step, to do this, you need to create a file hooks/build in your repo:

#!/usr/bin/env sh

# This is so we can get the commit into the build log of a Dangerfile runner
# These come from

# For debugging all env vars
# printenv

#  Convert the location "/Dockerfile" to "Dockerfile"
FILE=$(echo -n $BUILD_PATH | tail -c +2)

if [ -z "${DOCKER_TAG}" ]; then
  docker build --build-arg=COMMIT=$(git rev-parse --short HEAD) --build-arg=BRANCH=$SOURCE_BRANCH -t $IMAGE_NAME -f $FILE .
  docker build --build-arg=COMMIT=$(git rev-parse --short HEAD) --build-arg=BRANCH=$DOCKER_TAG -t $IMAGE_NAME -f $FILE .

There’s a list of examples in this repo - though the build one is too simple for our needs here. If you need something that’s not there, then remove the comment marker before printenv to the script to see what env vars are available (here’s an example build).

Step 2: Edit your Dockerfile to take the additional arguments COMMIT and BRANCH from ARG.

+ ARG BRANCH="master"
+ LABEL branch=${BRANCH}
+ LABEL commit=${COMMIT}

ADD . /app

+ # Now set it as an env var

Err, that should be everything. I mean, I did call it a micro-post. Trying to implement this has broken the Peril runner a bunch of times on staging, so I’m mainly just helping out other docker newbies.

Some links that helped me get there:

Remember folks, Ash says you should write as you learn, so write up those small wins.