在dockerfile中的go build命令中注入或内插多个ENV变量
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 .
我正在使用dockerfile生成go代码,并且尝试在中传递3个选项 -ldflags em>选项。
其中两个标志来自 ENV strong>变量,我必须通过字符串插值或串联将它们注入 -ldflags em>内容中,但是 我不知道如何。 p>
目标是将git版本哈希和当前时间戳注入main.go中的两个变量中 p>
通过使用“ echo”命令从dockerfile创建文件来完成,但我想确保它是 使用简单变量插值/并置 p>
ENV GIT_REVISION $(git rev-parse --short HEAD)
ENV COMPILATION_TIMESTAMP $(date +%Y%m%dT %H:%M:%S)
RUN go get -d -v
//这个可行:
RUN CGO_ENABLED = 0 GOOS = linux go build -a -installsuffix cgo -ldflags'-extldflags“ -static“'-o myprogram。
//这与 ose变量失败:
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。
code> pre>
div>
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.
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