Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkinsfile get current tag

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 this commit has a tag. I tried:

env.TAG_NAME

and

binding.variables.get("TAG_NAME")

both are always null - even though this ( https://issues.jenkins-ci.org/browse/JENKINS-34520 ) indicates otherwise

like image 955
ligi Avatar asked May 27 '16 16:05

ligi


People also ask

How do I get tags in Jenkins?

Under the Source Control Management section in your job configuration, if you have selected "Git", then there should be a section labelled "Additional Behaviours". Click "Add" and select "Export git tag and message as environment variables".

How do you list a tag?

In order to list Git tags, you have to use the “git tag” command with no arguments. You can also execute “git tag” with the “-n” option in order to have an extensive description of your tag list. Optionally, you can choose to specify a tag pattern with the “-l” option followed by the tag pattern.

How do I pass tag name in Jenkins pipeline?

In the "Git Repository" section of your job, under the "Source Code Management" heading, click "Advanced". Under "Branches to build", "Branch specifier", put */tags/<TAG_TO_BUILD> (replacing <TAG_TO_BUILD> with your actual tag name).

What is tag in Jenkins?

Job tag plugin is one simple plugin to help user to add multiple tags to job configuration, and display in list view.


3 Answers

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

like image 130
Florian Avatar answered Sep 20 '22 17:09

Florian


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

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

like image 35
Víctor Romero Avatar answered Sep 19 '22 17:09

Víctor Romero


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

like image 42
kuhnroyal Avatar answered Sep 22 '22 17:09

kuhnroyal