Eddie
Eddie

Reputation: 1161

Fail a Jenkins build from groovy script

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.

Upvotes: 25

Views: 41713

Answers (6)

Alexander Samoylov
Alexander Samoylov

Reputation: 2578

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.

Upvotes: 4

user666
user666

Reputation: 1172

You should be using

currentBuild.result = 'FAILURE'

Upvotes: 1

herm
herm

Reputation: 16405

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

assert condition : "Build fails because..."

Upvotes: 30

Jon S
Jon S

Reputation: 16346

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

import hudson.AbortException
//other code
throw new AbortException("Error message .")

Upvotes: 8

Chong
Chong

Reputation: 345

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

Upvotes: 3

burnettk
burnettk

Reputation: 14037

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"

Upvotes: 26

Related Questions