Skipping builds in a multi-branch job

Skipping builds in Jenkins is possible, there’s a “CI Skip” plug-in for Jenkins, but this plug-in doesn’t work with multi-branch jobs… How can you skip builds then in such a case? Here’s my take on it. Of course, feel free to modify it for your  pipeline’s needs.

I originally wrote about this in my Stack Overflow question: https://stackoverflow.com/questions/43016942/can-a-jenkins-job-be-aborted-with-success-result

Some context
Lets say a git push to GitHub was made, and this triggers either the pull_request or push webhook. The webhook basically tells Jenkins (if you have your Jenkins’ master URL set up there) that the job for this repository should start… but we don’t want a job to start for this specific code push. To skip it I could simply error the build (instead of the if statement below) but that’d produce a “red” line in the Stage View area and that’s not nice. I wanted a green line.

  1. Add a boolean parameter:
    pipeline {
     parameters {
         booleanParam(defaultValue: true, description: 'Execute pipeline?', name: 'shouldBuild')
     }
     ...
    
  2. Add the following right after the repository is checked out. We’re checking if the git commit has “[ci skip]” in the very latest commit log.
    stages {
     stage ("Skip build?") {
         result = sh (script: "git log -1 | grep '.*\\[ci skip\\].*'", returnStatus: true)
         if (result == 0) {
             echo ("This build should be skipped. Aborting.")
             env.shouldBuild = "false"
         }
     }
     ...
    }
    
  3. In each of the stages of the pipeline, check… e.g.:
    stage ("Unit tests") {
     when {
         expression {
             return env.shouldBuild != "false"
         }
     }
    
     steps {
         ...
     }
    }
    

If shouldBuild is true, the stage will be run. Otherwise, it’ll get skipped.