7

I am trying to utilize Exit code to set build unstable in job -> publishers -> postBuildScripts -> steps -> shell -> advance option to set my build unstable based on a condition. I have the script below.

...
postBuildScripts {
                onlyIfBuildSucceeds(false)
                steps {
                  shell('echo "Before exit 1"\n' +
                        'if [ ! condition ]; then\n' +
                        'echo failed-condition\n' +
                        'exit 1\n' +
                        'fi'
                       )
                }
            }
...

On executing the above DSL script, I get as below in jenkins enter image description here

With the above script exit 1, the build fails. But I wanted to make it unstable and I DO NOT want to use markBuildUnstable(true). I wanted to mark build unstable based on certain exit codes only. I can do it by setting the exit code manually to 1 like below enter image description here After this, the build is marked unstable.

I'm looking for script to set this field through scripts and not manually as I have many jobs.

Can someone please help me on this with suggestions?

Siddarth
  • 351
  • 2
  • 6
  • 20

2 Answers2

6

I was able to get this to work using the "raw" configure interface. When I was trying it, if I had a steps { shell () } anywhere else, it would overwrite and lose the settings, so I had to specify the command option as well. I was under the impression that << would append and not overwrite, but I've never used Node before.

def final my_script = readFileFromWorkspace('my_script.sh') // Seed workspace
freeStyleJob("jobname") {
  ...
    configure { project ->
        project / builders << 'hudson.tasks.Shell' {
          command my_script
          unstableReturn 2
        }
    }
  ...
}
Aaron D. Marasco
  • 6,506
  • 3
  • 26
  • 39
2

You can also use the Dynamic DSL:

job('example') {
  steps {
    shell {
      command('echo TEST')
      unstableReturn(2)
    }
  }
} 
daspilker
  • 8,154
  • 1
  • 35
  • 49
  • This doesn't work in my local lJenkins install (2.150.3, DSL 1.71) or the Job DSL playground (1.69): http://job-dsl.herokuapp.com/ . `No signature of method: javaposse.jobdsl.dsl.helpers.step.StepContext.shell() is applicable for argument types: (script$_run_closure1$_closure2$_closure3)` The dynamic DSL does show up in my local install (hence why I tried it). Perhaps this is a bug in the Job DSL plugin? – Alex Palmer Mar 13 '19 at 10:46
  • 1
    It works!! Thank you so much. There is no doc about this. You saved my life. – Frank Escobar Jan 27 '21 at 20:40