0

I'm using a dockerfile to build go code, and I'm trying to pass 3 options in -ldflags option. Two of these flags comes from ENV variables, and I have to inject them in -ldflags content, thru string interpolation or concatenation, but I don't know how.

The objective is to inject git revision hash and current timestamp in two variables in main.go

It can be done by creating a file from dockerfile with "echo" command, but I want to be sure it's not possible with simple variables interpolation/concatenating

ENV GIT_REVISION $( git rev-parse --short HEAD )

ENV COMPILATION_TIMESTAMP $( date +%Y%m%dT%H:%M:%S )

RUN go get -d -v

// This one works:
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o myprogram .

// This one, with those variables, fails:
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags "-extldflags '-static' -X main.compiledOn=${COMPILATION_TIMESTAMP} -X main.gitRevisionHash=${GIT_REVISION}" -o myprogram .
Miguel Pragier
  • 135
  • 2
  • 13
  • 1
    Maybe this is because `RUN` is not one of the Dockerfile commands that supports environment replacement: https://docs.docker.com/engine/reference/builder/#environment-replacement – orirawlings Jan 24 '19 at 15:25

2 Answers2

1

Unfortunately none of the current Docker builder command support environment variable replacement. Your best bet would be to write a shell script, where environment variable replacement is a first class citizen. Then, when you call RUN ./script you'll be able to catch the ENV values from the previous layers.

Sienna
  • 1,570
  • 3
  • 24
  • 48
0

I couln't mark as solution, but want to share how I solved the underlying problem with an alternative approach:

# Handle source-code-file extvars.go to inject GIT_REVISION and COMPILATION_TIMESTAMP
# File extvars.go exists and compiles normally already, and I'm just providing a new/updated one:
RUN echo "package main" > $APPDIR/extvars.go
RUN echo "" >> $APPDIR/extvars.go && \
    echo "var gitRevision = \"$( git rev-parse --short HEAD )\"" >> $APPDIR/extvars.go && \
    echo "" >> $APPDIR/extvars.go && \
    echo "var compilationTimestamp = \"$( date +%Y.%m.%dT%H:%M:%S)\"" >> $APPDIR/extvars.go


Miguel Pragier
  • 135
  • 2
  • 13