Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute Jenkins Pipeline step only when building a tag

I have certain build logic, such as publication, that I would like to have Jenkins perform only when it is building a Git tag. How can I accomplish this using Jenkin's Declarative Pipeline?

In other words, I am trying to build functionality equivalent to Travis CI's deploy on tags functionality:

deploy:
  [...]
  on: 
    tags: true

There is a built-in condition to check the branch, but I do not see one that indicates the tag.

like image 240
vossad01 Avatar asked Jan 21 '18 02:01

vossad01


People also ask

Can we run a step conditionally in Jenkins?

The Conditional BuildStep plugin lets users add conditional logic to Freestyle jobs from within the Jenkins web UI. It does this by: Adding two types of Conditional BuildStep ("Single" and "Multiple") - these build steps contain one or more other build steps to be run when the configured condition is met.

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

How do you run a pipeline on a specific node?

If you are running a Pipeline job, you first want to add a label (e.g. 'slave') to the slave node (or agent as it seems to be called now). Then, in the pipeline script, you specify the label the job runs on: Declarative pipeline: pipeline { agent {label 'slave'} stages { ... } }


1 Answers

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.

like image 74
vossad01 Avatar answered Oct 25 '22 05:10

vossad01