0

When a new merge is made the previous job keeps building keeping the new one in queue.

What I Want: When a new merge is made, I want jenkin to focus on that job stopping the previous build using powershell or cmd.

Is that possible.

Screenshot of a problem

Thank You in advance.

1 Answers1

0

You can use the sample to abort the previous job:

pipeline {
    agent any

    stages {
        stage('Abort previous running builds') {
            steps {
                abortPreviousRunningBuilds()
            }
        }
        
        stage('Build') {
            steps {
                sleep(5)
            }
        }
        
        stage('Test') {
            steps {
                sleep(5)
            }
        }
    }
}

def abortPreviousRunningBuilds() {
    def previousBuild = currentBuild.getRawBuild().getPreviousBuildInProgress()
    while (previousBuild != null) {
        if (previousBuild.isInProgress()) {
            def executor = previousBuild.getExecutor()
            if (executor != null) {
                echo ">> Aborting older build #${previousBuild.number}"
                executor.interrupt(Result.ABORTED, new CauseOfInterruption.UserInterruption("Aborted by newer build #${currentBuild.number}"))
            }
        }
        previousBuild = previousBuild.getPreviousBuildInProgress()
    }
}

If you get some RejectedAccessException, you need to allow in-process script approval by this way.

Update

Or you can use the solution: install Jenkins plugin - Pipeline: Milestone Step and write like this:

pipeline {
    agent any

    stages {
        stage('Abort previous running builds') {
            steps {
                abortPreviousRunningBuilds()
            }
        }
        
        stage('Build') {
            steps {
                sleep(5)
            }
        }
        
        stage('Test') {
            steps {
                sleep(5)
            }
        }
    }
}

def abortPreviousRunningBuilds() {
    def buildNumber = env.BUILD_NUMBER as int
    if (buildNumber > 1) milestone(buildNumber - 1)
        milestone(buildNumber)
}
bnet
  • 265
  • 1
  • 5