使用来自 git 存储库的标签标记 docker 图像

Tagging docker image with tag from git repository

我正在使用 Gitlab 作为存储库和 ci/cd。 目前正在尝试设置从构建阶段创建 docker 图像的管道。 我见过的所有例子都有一个简单的图像命名,例如分支被使用(master)

我的问题是,如果我想根据存储库中的当前标签来标记图像,我该怎么做? 我假设我可以使用 Gitlab runner 变量但没有看到我们

作为 shell command is not possible yet with variables inside .gitlab-ci.yml, you may edit a build script that get the current tag 并在该脚本中构建图像

两个文件都位于项目的根目录中:

build.sh :

#!/bin/sh

IMAGE="$CI_REGISTRY/$CI_PROJECT_PATH:$CI_BUILD_REF_NAME-$(git describe --abbrev=0 --tags)"

docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY
docker build --pull -t $IMAGE .
docker push $IMAGE

.gitlab-ci.yml :

image: docker:latest
services:
  - docker:dind

stages:
  - release

release:
  stage: release
  script:
    - apk update && apk add git
    - ./build.sh

Gitlab CI中有很多预定义变量。我认为您正在寻找 CI_COMMIT_TAG.

所以你可以这样使用它:

docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG

所以图像看起来像 registry.example.com/group/project:tag