Build only latest commit on branch with Jenkins

Viewed 2109

This seems too trivial to ask, but I could not find an answer:

In a Multibranch Pipeline project (controlled by Jenkinsfile): How can I skip previous builds on a branch, if there is a newer one and only build the latest commit and/or the tip of the branch?

     Build is running        
  ├────────────────────┤

o────────o────────o────────o
↑        ↑        ↑        ↑
Build    Skip     Skip     Build this


──────────────────────────────────>
                              (t)
1 Answers

Jenkins built-in workflow-job-plugin has disableConcurrentBuilds directive that takes one boolean parameter named abortPrevious. The parameter is undocumented in the official Jenkins documentation but is mentioned in the PR to the workflow-job-plugin and available since version 2.42 of the aforementioned plugin.

Having that in mind the feature to cancel previous builds can be enabled in Jenkins by:

  • using Scripted Pipeline:

    node {
        properties([
            disableConcurrentBuilds(abortPrevious: true)
        ])
        [...]
    }
    
  • using Declarative Pipeline:

    pipeline {
        agent any
        options {
            disableConcurrentBuilds(abortPrevious: true)
        }
        stages { ... }
    }
    
Related