'Jenkins groovy - How to retrieve tag from latest commit?
To fetch the latest commit from branchName
, we run below code:
treeMapData = git(branch: branchName, credentialsId: credential, url: "${gitLabServer}/${projectName}/${repo}.git")
It is ensured that there is one tag per commit, as per our workflow
We want to build the code, only if the commit is tagged.
How to retrieve the tag name for that latest commit?
Solution 1:[1]
We can fetch the tags from the repo in case Jenkins hasn't already.
git fetch --tags
We need to find a tag(s) which point to a specific commit or HEAD
in our case. Thankfully there is a handy command in git which allows us to do this.
git tag --points-at HEAD
Using awk
we can turn this into an output which groovy can falsify.
awk NF
So we, first we check if the pushed branch is master
if (env.BRANCH_NAME == 'master') {
lock it down
lock('publish master') {
execute the git tag shell script and assign it to TAG
TAG = sh (
returnStdout: true,
script: 'git fetch --tags && git tag --points-at HEAD | awk NF'
).trim()
if a tag exists, do something!
if (TAG) {
stage('Deploy Prod') {
echo "Deploying to Prod ${TAG}"
}
}
Hopefully this answers your question, or at the very least will get you on the right track.
Solution 2:[2]
Just in case anyone needs this (like I did): you need to build from a tag, not from a commit. Then env.TAG_NAME becomes available and you can write code like this:
if(env.TAG_NAME) {
...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | evolutionxbox |
Solution 2 | Geff |