如何在构建时获取最后的git commit哈希?

时间:2019-12-11 19:34:09

标签: gitlab gitlab-ci gitlab-ci-runner

在CI / CD管道中构建映像时,我想检索当前用于构建的提交的哈希值。我希望以下Dockerfile可以工作:

FROM alpine:latest
RUN apk -X http://nl.alpinelinux.org/alpine/edge/testing add gcc musl-dev python3-dev libffi-dev openssl-dev make jo git
RUN pip3 install pyyaml logbook multiping dnspython requests paho-mqtt arrow paramiko click
WORKDIR /app
COPY config-prod.yaml ./config.yaml
COPY homemonitor.py .
RUN jo date=$(date -Iseconds) git=$(git rev-parse HEAD) > docker-build.json
CMD python3 homemonitor.py

检索在最后RUN行中,但出现错误:

Step 9/10 : RUN jo date=$(date -Iseconds) git=$(git rev-parse HEAD) > docker-build.json
168  ---> Running in 96b09729f8b6
169 fatal: not a git repository (or any of the parent directories): .git
170 Removing intermediate container 96b09729f8b6
171  ---> 2aff5909f75d

我对这个错误的理解是,我从事的工作实际上不是git存储库,而是HEAD的导出,因此没有.git forlder持有提交信息

如果这是原因-是否有一种方法可以检索用于构建的当前提交的哈希?这是作业开始时就可以看到的一个名称(即{{ 1}}):

d4c8af29

编辑:每个请求我的Running with gitlab-runner 12.5.0 (577f813d) on srv zN2MsS9q (...) Fetching changes... Reinitialized existing Git repository in /home/gitlab-runner/builds/zN2MsS9q/0/wsw70-docker/homemonitor/.git/ From https://gitlab.com/wsw70-docker/homemonitor * [new ref] refs/pipelines/102404788 -> refs/pipelines/102404788 a1b4313..d4c8af2 master -> origin/master Checking out d4c8af29 as master... Skipping Git submodules setup

.gitlab-ci.yaml

all: script: - docker build -t ${PROJECT} -f Dockerfile . - docker tag ${PROJECT} registry.mydomain/${PROJECT} - docker push registry.mydomain/${PROJECT} 在传递给CI / CD的变量中定义

1 个答案:

答案 0 :(得分:0)

在我的 .gitlab-ci.yml 文件中,我使用了 CI_COMMIT_SHORT_SHA,它返回最后一次提交的 SHA 的前 8 个字符。按预期为我工作。

如果您需要 SHA 的所有数字,请使用 CI_COMMIT_SHA

这是 GitLab 预定义变量的 list

附言我使用 gitlab.com 及其免费跑步者。