0

I wanted to take some action based on all the concurrent running job displayName before starting a new run of the same pipeline job.

Could not get any satisfactory reference, if anyone has tried something similar please share.

  • 1
    Can you please elaborate a bit? – Surendra Deshpande May 12 '18 at 10:00
  • `Jenkins.getInstance()` should give you access to such things. – StephenKing May 12 '18 at 15:07
  • Let me explain: Let's say my pipeline job is triggered on gerrit review - I wanted to cancel previous build if a new patchset came in for the same review - To handle the scenario I have the gerrit review id and patchset number in the displayname - I wanted to find all the current jobs running and findout if the flow is running for the same review ID and cancel one of them. – Dillip Kumar Behera May 21 '18 at 11:49

1 Answers1

0

Could able to write the following code to achieve my goal, it's working absolutely fine. Catch is to use same Displayname format in all the jobs and identifying same in the loop. This piece of code is written inside shared library vars folder example: vars/abortPreviousWorklow.groovy.

import hudson.model.Result
import hudson.model.Run
import jenkins.model.CauseOfInterruption.UserInterruption
def call(){
    currentDisplayName = env.GERRIT_PROJECT+' '+env.GERRIT_BRANCH+' '+env.GERRIT_CHANGE_NUMBER
    Run previousBuild = currentBuild.rawBuild.getPreviousBuildInProgress()

    while (previousBuild != null) {
        if (previousBuild.isInProgress()) {
            echo ">>DisplayName of previous Build : ${previousBuild.displayName}"
            if(previousBuild.displayName.find(currentDisplayName)) {
                def executor = previousBuild.getExecutor()
                if (executor != null) {
                    echo ">> Aborting older build #${previousBuild.number}"
                    executor.interrupt(Result.ABORTED, new UserInterruption(
                        "Aborted by newer build #${currentBuild.number}"
                    ))
                }
            }
        }
        previousBuild = previousBuild.getPreviousBuildInProgress()
    }
}