Execute Jenkins Pipeline step only when building a tag
Update: As of version 1.2.8 of the Pipeline Model Definition Plugin you can now use buldingTag()
:
stage('Deploy') { when { buildingTag() } steps { echo 'Replace this with your actual deployment steps' }}
When using the Multibranch Pipeline configuration you can use the expression
condition along with the TAG_NAME
environment variable provided by the underlying Branch API Plugin. Unfortunately, you can't directly check if the environment variable is defined at the Groovy level (API restrictions) so you have to test in in the shell:
stage('Deploy') { when { expression { sh([returnStdout: true, script: 'echo $TAG_NAME | tr -d \'\n\'']) } } steps { echo 'Replace this with your actual deployment steps' }}
The above takes advantage of non-empty strings being truthy in Groovy.
An easier way may be introduced in future versions. See jenkinsci/pipeline-model-definition-plugin#240.
I had a similar situation which I handled by getting the branch name ,in case of tag it is like refs/tags/v101.0.0-beta8468
, so you have to extract / parse this to check if its a tag otherwise its just the branch name like pipeline
. eg.
if(env.gitlabBranch.contains("tags")) { isTag = true echo "----------------true----------------" branch = env.gitlabBranch.split("/")[2] imageTag = branch } else { branch = "origin/$env.gitlabBranch" }
And in the chekout step mention the branch as
branches: [[name: "${branch}"]
if you want to checkout from the same project. Based on the isTag variable you can choose to run a certain stage .Like:
if(isTag) {stage('Deploy') { // your logic here}
initialise your isTag as false :)