如何在构建时获取最后一个 git 提交哈希?



在 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保存提交信息。

如果这是原因 -有没有办法检索用于构建的当前提交的哈希?这是在作业开始时可见的一个(即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}

PROJECT在传递给 CI/CD 的变量中定义

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

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

以下是 GitLab 预定义变量的列表。

附言我用 gitlab.com 和它的自由跑步者。

最新更新