Shut down the jenkins pipeline

We have a couple of steps in our work on the Jenkins pipeline, and I would like the assembly to be stopped if any of the steps fail, and not proceed to the next steps.

Here is an example of one of the steps:

stage('Building') { def result = sh returnStatus: true, script: './build.sh' if (result != 0) { echo '[FAILURE] Failed to build' currentBuild.result = 'FAILURE' } } 

The script will fail and the build result will be updated, but the work proceeds to the next steps. How can I interrupt or stop work when this happens?

+11
jenkins jenkins-pipeline
source share
3 answers

This is basically what the sh step does. If you do not commit the result to a variable, you can simply run:

 sh "./build" 

This will end if the script returns a non-zero exit code.

If you need to make the material first, and you need to fix the result, you can use the shell step to exit the task

 stage('Building') { def result = sh returnStatus: true, script: './build.sh' if (result != 0) { echo '[FAILURE] Failed to build' currentBuild.result = 'FAILURE' // do more stuff here // this will terminate the job if result is non-zero // You don't even have to set the result to FAILURE by hand sh "exit ${result}" } } 

But the following will give you the same thing, but it seems more reasonable to do

 stage('Building') { try { sh './build.sh' } finally { echo '[FAILURE] Failed to build' } } 

You can also call a return in code. However, if you are inside the stage , it will only return at this stage. So,

 stage('Building') { def result = sh returnStatus: true, script: './build.sh' if (result != 0) { echo '[FAILURE] Failed to build' currentBuild.result = 'FAILURE' return } echo "This will not be displayed" } echo "The build will continue executing from here" 

cannot complete the task but

 stage('Building') { def result = sh returnStatus: true, script: './build.sh' } if (result != 0) { echo '[FAILURE] Failed to build' currentBuild.result = 'FAILURE' return } 

will be.

+11
source share

Another way to achieve this behavior is to throw an Exception. In fact, this is exactly what Jenkins himself does. That way you can also set the build status to ABORTED or FAILURE . This example aborts the assembly:

 stage('Building') { currentBuild.rawBuild.result = Result.ABORTED throw new hudson.AbortException('Guess what!') echo 'Further code will not be executed' } 

Output:

 [Pipeline] stage [Pipeline] { (Building) [Pipeline] } [Pipeline] // stage [Pipeline] End of Pipeline ERROR: Guess what! Finished: ABORTED 
+8
source share

Since Jenkins v2 this should also work

 error('Failed to build') 

Work will end with:

 ERROR: Failed to build Finished: ERROR 
+1
source share

All Articles