Running a Post Build script when a Jenkins job is aborted
Asked Answered
S

4

26

Is there a possible way / plugin that can run a post build script when a Jenkins job is aborted. I do see that the post build plugin provides an action to execute a set of scripts, but these can be run only on 2 options either a successful job or a failed job.

Schacker answered 30/7, 2014 at 21:45 Comment(0)
S
26

This question is positively answered here.

The Post Build Task plugin is run even if a job is aborted.

Use it to search the log text for "Build was aborted" and you can specify a shell script to run.

Works like a charm. :-)

Sightread answered 28/8, 2014 at 7:44 Comment(2)
I will try. However the issue here is that the Jenkins status is Success, not AbortedOvershadow
The linked answer does not exist anymore :/Pacifism
M
6

For a declarative Jenkins pipeline, you can achieve it as follows:

pipeline {
    agent any

    options {
        timeout(time: 2, unit: 'MINUTES')   // abort on exceeding the timeout
    }

    stages {
        stage('Echo 1') {
           steps {
              echo 'Hello World'
          } 
        }
        stage('Sleep'){
            steps {
                sh 'sleep 180'
            }
        }
        stage('Wake up'){
            steps {
                echo "Woken up"
            }
        }
    }
    // this post part is executed if job is aborted
    post {
        aborted {
            script{
              echo "Damn it. I was aborted!"
            }
        }
    }
}
Mack answered 21/10, 2020 at 6:51 Comment(1)
Also, instructions in the always, unsuccessful and cleanup conditions of the post step are run when a job is aborted (jenkins.io/doc/book/pipeline/syntax/#post-conditions).Coign
M
2

As far as I know, if a build is aborted, there's no way to execute any build steps (or post build steps) in it any more - which makes sense, that's what I would expect of "abort".

What you could do is create another job that monitors the first one's status, and triggers if it was aborted (e.g. see the BuildResultTrigger plugin).

Another solution might be to create a "wrapper" job, which calls the first one as a build step - this way you can execute additional steps after its completion, like checking its status, even if it was aborted.

Mucous answered 30/7, 2014 at 23:0 Comment(0)
J
0

If you use a scripted pipeline, you can always use a try/catch/finally set, where the build gets executed in the try block and the postbuild steps are in the finally block. This way, even if the build fails, post build steps are executed.

try {
        build here
}catch(FlowInterruptedException interruptEx){

    catch exception here
} finally {

    postBuild(parameters)

}
Junitajunius answered 11/1, 2019 at 20:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.