Issue
A stage in my Jenkins pipeline should be set as unstable depending on the exit code of the script within its steps: 2 should set the stage status to unstable when 1 should set the stage result to failed.
How to achieve this? I checked "catchError" but it doesn't seem to differenciate between failed status, offering only a way to catch non 0 exit (1,2...).
pipeline {
agent any
parameters {
string(name: 'FOO', defaultValue: 'foo', description: 'My foo param')
string(name: 'BAR', defaultValue: 'bar', description: 'My bar param')
}
stages {
stage('First') {
steps {
// If "script.py" exit code is 2, set stage to unstable
// If "script.py" exit code is 1, set stage to failed
sh """
. ${WORKSPACE}/venv/bin/activate
python ${WORKSPACE}/script.py --foo ${FOO} --bar ${BAR}
deactivate
"""
}
}
}
stage('Second') {
steps {
echo('Second step')
}
}
}
}
Solution
Solution
You will need to do the following steps
- Place all your code into a
script
block - Modify
sh
to return status code - Use a conditional to check the status code
- Throw and Catch an error with
catchError
. Set the build to SUCCESS and the stage to FAILURE or UNSTABLE accordingly
I am using
error
to force the exception but you can also usesh 'exit 1'
orthrow new Exception('')
pipeline {
agent any
parameters {
string(name: 'FOO', defaultValue: 'foo', description: 'My foo param')
string(name: 'BAR', defaultValue: 'bar', description: 'My bar param')
}
stages {
stage('First') {
steps {
script {
def pythonScript = """
. ${WORKSPACE}/venv/bin/activate
python ${WORKSPACE}/script.py --foo ${FOO} --bar ${BAR}
deactivate
"""
def statusCode = sh( script:pythonScript, returnStatus:true )
if(statusCode == 2) {
catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE') {
error 'STAGE UNSTABLE'
}
} else if(statusCode == 1) {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
error 'STAGE FAILURE'
}
}
}
}
}
}
}
Answered By - Chris Maggiulli