Home > Net >  How to run a task if tests fail in Jenkins
How to run a task if tests fail in Jenkins

Time:06-11

I have a site in production. And I have a simple playwright test that browses to the site and does some basic checks to make sure that it's up.

I'd like to have this job running in Jenkins every 5 minutes, and if the tests fail I want to run a script that will restart the production server. If the tests pass, I don't want to do anything.

What's the easiest way of doing this?

I have the MultiJob plugin that I thought I could use, and have the restart triggered on the failed test step, but it doesn't seem to have the ability to trigger specifically on fail.

CodePudding user response:

Something like the following will do the Job for you. I'm assuming you have a second Job that will take care of the restart.

pipeline {
    agent any
    triggers{
        cron('5 * * * *')
    }
    stages {
     stage("Run the Test") {
                steps{
                    echo "Running the Test"
                    // I'm returning exit code 1 so jenkins will think this failed
                    sh '''
                    echo "RUN SOMETHING"
                    exit 1
                    '''
                    
            }
    }
    }
    post {
        success {
            echo "Success: Do nothing"
        }
        failure {
            echo 'I failed :(, Execute restart Job'
            // Executing the restart Job. 
            build job: 'RestartJob'
        }
    }
}
  • Related