Skip to content

Instantly share code, notes, and snippets.

@bodhi
Created May 22, 2019 00:18
Show Gist options
  • Save bodhi/2c2152bb69dd2ef769002bf175a3d509 to your computer and use it in GitHub Desktop.
Save bodhi/2c2152bb69dd2ef769002bf175a3d509 to your computer and use it in GitHub Desktop.
Burn git commit SHA into docker image
FROM golang:1.12 AS build
COPY ./main.go .
# ARG here is to make the sha available for use in -ldflags
ARG GIT_SHA
# -ldflags "-X main.sha=${GIT_SHA}" allows main.sha to be set at build time
RUN go build -ldflags "-X main.sha=${GIT_SHA}" -o /app
FROM scratch
COPY --from=build /app .
# ARG here is to make the sha available for use by ENV
ARG GIT_SHA
# ENV here makes the sha available via os.Getenv
ENV GIT_SHA=${GIT_SHA}
CMD ["/app"]
package main
import (
"fmt"
"os"
)
// This gets set at build time via `-ldflags "-X main.sha=<value>"`
var sha string = "local"
func main() {
fmt.Println("sha:", os.Getenv("GIT_SHA"))
fmt.Println("sha var:", sha)
}
# Latest commit hash
GIT_SHA=$(shell git rev-parse HEAD)
# If working copy has changes, append `-local` to hash
GIT_DIFF=$(shell git diff -s --exit-code || echo "-local")
GIT_REV=$(GIT_SHA)$(GIT_DIFF)
# To flag when the working copy had changes, use GIT_REV. To just use
# the latest commit hash, use GIT_SHA.
build:
docker build -t sha_test --build-arg GIT_SHA=$(GIT_REV) .
run:
docker run --rm sha_test
test: build run
bodhi$ make test
docker build -t sha_test --build-arg GIT_SHA=92088a0701642d55909a7a3d9a48302bc7c474a5-local .
Sending build context to Docker daemon  67.58kB
Step 1/9 : FROM golang:1.12 AS build
 ---> 7ced090ee82e
Step 2/9 : COPY ./main.go .
 ---> 0093f8e7b1e1
Step 3/9 : ARG GIT_SHA
 ---> Running in 01453ef056c6
Removing intermediate container 01453ef056c6
 ---> 7f6db7047180
Step 4/9 : RUN go build -ldflags "-X main.sha=${GIT_SHA}" -o /app
 ---> Running in 9a7b07d19dd4
Removing intermediate container 9a7b07d19dd4
 ---> f9f0e4e293cc
Step 5/9 : FROM scratch
 --->
Step 6/9 : COPY --from=build /app .
 ---> 0ad9195abc5a
Step 7/9 : ARG GIT_SHA
 ---> Running in db4f19505376
Removing intermediate container db4f19505376
 ---> 1fd145bd1b2e
Step 8/9 : ENV GIT_SHA=${GIT_SHA}
 ---> Running in 9aba2985ead3
Removing intermediate container 9aba2985ead3
 ---> d0db9c895fb3
Step 9/9 : CMD ["/app"]
 ---> Running in 1d2657da6eec
Removing intermediate container 1d2657da6eec
 ---> 9944ccbaf007
Successfully built 9944ccbaf007
Successfully tagged sha_test:latest
docker run --rm sha_test
sha: 92088a0701642d55909a7a3d9a48302bc7c474a5-local
sha var: 92088a0701642d55909a7a3d9a48302bc7c474a5-local
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment