Jenkinsfile get current tag

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()


The TAG_NAME should work now at least in declarative pipelines.

When condition actually filters on this property. BRANCH_NAME has the same value.

stage('release') {
   when {
     tag 'release-*'
   }
   steps {
     echo "Building $BRANCH_NAME"
     echo "Building $TAG_NAME"
   }
}

See https://jenkins.io/doc/book/pipeline/syntax/#when


I'd consider returnStdout rather than writing to a file:

sh(returnStdout: true, script: "git tag --sort version:refname | tail -1").trim()