22

I have a groovy script that goes and promotes code. Long story short, I know at a point of time within that script if it was successful or not. I would like to fail the build if not successful. Is there a way in groovy to fail the build?

Example:

in the "execute Groovy script" plugin. you can write code.

(insert API call to promote code) if(checkPromote()){ //fail build here }

where 'checkPromote' returns a true or false value depending on the status of the promote.

Eddie
  • 1,081
  • 2
  • 12
  • 28

6 Answers6

30

The most elegant way to abort a programm in my opinion is an assertion.

assert condition : "Build fails because..."

herm
  • 14,613
  • 7
  • 41
  • 62
24

The declarative pipeline dsl has an error step:

error('Failing build because...')

See https://jenkins.io/doc/pipeline/steps/workflow-basic-steps and search the page for "Error signal".

this would also do it:

sh "exit 1"
burnettk
  • 13,557
  • 4
  • 51
  • 52
8

From this page, https://wiki.jenkins-ci.org/display/JENKINS/Groovy+plugin

import hudson.AbortException
//other code
throw new AbortException("Error message .")
Jon S
  • 15,846
  • 4
  • 44
  • 45
  • Have you tried this? You'd seen the following error `org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new hudson.AbortException`. – acm Sep 06 '17 at 07:20
  • @acm Yes it works, although you have to approve the constructor for AbortException first, see https://stackoverflow.com/a/39412951/7509826 – Jon S Sep 06 '17 at 14:33
  • Nicely this doesn't include an unnecessary stack trace. – Jeremy Gosling Jun 23 '18 at 21:07
4

There are different "groovy script"s in the Jenkins world. For every of them the solution is different.

  1. "Execute Groovy script" plugin (a plain Groovy script which runs on a node)

     System.exit(1)
     // NOTE: Don't use it in System Groovy Script, Groovy Postbuild, Scriptler or Pipeline
     // because it runs on master and terminates the Jenkins server process!
    
  2. System Groovy Script / Groovy Postbuild / Scriptler (runs on master):

     import hudson.model.*;
     def currentBuild = Thread.currentThread().executable
     currentBuild.result = Result.FAILURE
    

    This works only for "System Groovy Script"

     return 1
    
  3. Pipeline:

     currentBuild.result = 'FAILURE'// one way
     error("Error Message") // another way
    

There are of course more artificial methods like throwing an exception, execution of a faulty command, calling of unexisting function or a function with wrong arguments etc etc.

Alexander Samoylov
  • 2,358
  • 2
  • 25
  • 28
2

I usually use something as simple as throw new Exception("Error Message") so maybe you can have try with:

    if(checkPromote()){
         throw new Exception("Error Message")
     }

Hope this also works for you

Chong
  • 335
  • 2
  • 9
0

You should be using

currentBuild.result = 'FAILURE'
user666
  • 1,104
  • 12
  • 20