Tagging docker image with tag from git repository
Asked Answered
D

3

14

I am using Gitlab for repository and ci/cd. Currently trying to set up pipeline that creates a docker image from a build stage. All examples I have seen have a simple naming of image where e.g. the branch is used(master)

My question is if I want to tag the image based on the current tag in the repository how do I do this? I am presuming I can use a Gitlab runner variable but do not see one to us

Diez answered 19/7, 2018 at 21:5 Comment(0)
P
17

There are a lot of predefined variables in Gitlab CI. I think you are looking for CI_COMMIT_TAG.

So you could use it this way:

docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG

So the image would look like registry.example.com/group/project:tag

Pruitt answered 20/7, 2018 at 0:20 Comment(2)
note that it will only work if you push a tag, the variable will be empty for subsequent commitPledgee
You can use the "only" checker with variables to skip the build task if it is empty: ``` only: refs: - master variables: - $CI_COMMIT_TAG ``` Formatting doesn't appear to work in comments. Use your imagination I guess.Arapaima
P
5

As shell command is not possible yet with variables inside .gitlab-ci.yml, you may edit a build script that get the current tag and build the image inside that script

Both file at the root of your project :

build.sh :

#!/bin/sh

IMAGE="$CI_REGISTRY/$CI_PROJECT_PATH:$CI_COMMIT_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
Pledgee answered 20/7, 2018 at 0:18 Comment(0)
U
0

I recommend you to use this syntax:

script:
 - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_TAG
rules:
 - if: $CI_COMMIT_TAG`
Uncivilized answered 25/7, 2023 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.