Get latest tag in .gitlab-ci.yml for Docker build
Asked Answered
M

3

20

I want to add a tag when building a Docker image, I'm doing this so far but I do not know how to get the latest tag on the repository being deployed.

docker build -t company/app .

My goal

docker build -t company/app:$LATEST_TAG_IN_REPO? .
Mesonephros answered 13/6, 2019 at 16:25 Comment(2)
Can you clarify what you mean by 'latest tag on the repository' exactly? Is that a git tag? Would you then be looking for the first git tag that is an ancestor of the commit currently being deployed?Tiemannite
renefritze yes, the latest tag created with git tagand being saved in the origin repository (gitlab)Mesonephros
R
18

You can try using $CI_COMMIT_TAG or $CI_COMMIT_REF_NAME, this is part of the predefined variables accessible during builds.

If you want to see what are all the available environment variables during build step this should work as one of your jobs:

script:
    - env
Rhineland answered 13/6, 2019 at 20:21 Comment(2)
$CI_COMMIT_TAG is only non-empty if the build is for a tag. If the currently building commit is not tagged, it will be empty. $CI_COMMIT_REF_NAME is similarly only the the tag if it's a tagged build, otherwise that's the branch name.Tiemannite
renefritze yeah, I had to add only: - tagsMesonephros
T
22

Since you're looking for the "latest" git tag which is an ancestor of the currently building commit you probably want to use

git describe --tags --abbrev=0

to get it and use it like:

docker build -t company/app:$(git describe --tags --abbrev=0) .

Read here for the finer points on git describe

Tiemannite answered 17/6, 2019 at 7:16 Comment(2)
This only gets the annotated tag. Need to use git describe --tags --abbrev=0 to get the tag even if lightweight.Hesperian
Let's suppose I build a commit from tag 0.2 and then I want to rollback to 0.1. If I rebuild with the commit pointing to 0.1, what tag will the git describe command return? 0.1 or 0.2?Diggins
R
18

You can try using $CI_COMMIT_TAG or $CI_COMMIT_REF_NAME, this is part of the predefined variables accessible during builds.

If you want to see what are all the available environment variables during build step this should work as one of your jobs:

script:
    - env
Rhineland answered 13/6, 2019 at 20:21 Comment(2)
$CI_COMMIT_TAG is only non-empty if the build is for a tag. If the currently building commit is not tagged, it will be empty. $CI_COMMIT_REF_NAME is similarly only the the tag if it's a tagged build, otherwise that's the branch name.Tiemannite
renefritze yeah, I had to add only: - tagsMesonephros
D
1

The pre-defined variable $CI_COMMIT_TAG is empty if no git tag points to the current commit in the pipeline. If you either want the current tag or the current SHA of the commit (as a fallback), you can use IMAGE_VERSION=${CI_COMMIT_TAG:-"$CI_COMMIT_SHORT_SHA"}

Demesne answered 13/2, 2023 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.