Is there a way to get the current tag ( or null if there is none ) for a job in a Jenkinsfile? The background is that I only want to build some artifacts ( android APKs ) when t
All the other answers yield an output in any case even if HEAD is not tagged. The question was however to return the current tag and "null" if there is nothing like that.
git tag --contains
yields the tag name name if and only if HEAD is tagged.
For Jenkins Pipelines it should look like this:
sh(returnStdout: true, script: "git tag --contains").trim()
An example of declarative pipeline following the OP usecase: "do something if this particular commit has a tag attached":
def gitTag = null
pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout(...)
script {
gitTag=sh(returnStdout: true, script: "git tag --contains | head -1").trim()
}
}
}
stage('If tagged') {
when {
expression {
return gitTag;
}
}
steps {
// ... do something only if there's a tag on this particular commit
}
}
}
}
In my case, I have:
I need to analyze the current tag to check if it concerns my pipeline project (using a PROJECT_NAME variable per project):
def gitTag = null
def gitTagVersion = null
pipeline {
agent any
stages {
stage('Checkout') {
steps {
checkout(...)
script {
gitTag=sh(returnStdout: true, script: "git tag --contains | head -1").trim()
if(gitTag) {
def parts = gitTag.split('_')
if( parts.size()==2 && parts[0]==PROJECT_NAME ) {
gitTagVersion=parts[1]
}
}
}
}
}
stage('If tagged') {
when {
expression {
return gitTagVersion;
}
}
steps {
// ... do something only if there's a tag for this project on this particular commit
}
}
}
}
Note that I'm new at Jenkins and Groovy and that this may be written more simply/cleanly (suggestions welcome).
(with Jenkins 2.268)
best way from my site is:
git tag --sort=-creatordate | head -n 1
with:
latestTag = sh(returnStdout: true, script: "git tag --sort=-creatordate | head -n 1").trim()
Than you can handle with simple regex, for prefix/suffix/version_number what is to do with the tag.
other solution:
git describe --tags --abbrev=0
of course this is the current/latest tag in git. Independent from writing.
sh(returnStdout: true, script: "git describe --tags --abbrev=0").trim()
sh "git tag --sort version:refname | tail -1 > version.tmp"
String tag = readFile 'version.tmp'
If the current build is a tag build -- as in, when { buildingTag() }
was "true" -- then the (undocumented) environment variable BRANCH_NAME
contains the name of the tag being build.
I'd consider returnStdout
rather than writing to a file:
sh(returnStdout: true, script: "git tag --sort version:refname | tail -1").trim()