Home > Net >  Jenkins treats any non-zero exit code as error
Jenkins treats any non-zero exit code as error

Time:10-16

This is a concern as we have an executable which returns 2 as warning. We do not want to fail the Jenkins build pipeline just because of this. How can we modify the pipeline to accept an exit code 2, and prints out a reasonable warning message based on the exit code?

D:\Stage>c:\bin\mycommand
script returned exit code 2

CodePudding user response:

When you run sh or bat in a Jenkins pipeline it will always fail the build (and throw an exception) for any non zero exit code - and that cannot be changed.
What you can do is use the returnStatus of the sh step (or cmd) which will return the exit code of the script instead of failing the build, and then you can use something like:

pipeline {
    agent any
    stages {
        stage('Run Script') {
            steps {
                script {
                    def exitCode = sh script: 'mycommand', returnStatus: true
                    if (exitCode == 2) {
                        // do something
                    }
                    else if (exitCode){
                        // other non-zero exit codes
                    }
                    else {
                        // exit code 0
                    }
                }
            }
        }
    }
}

The only drawback of this approach is that returnStatus cannot be used together with returnStdout, so if you need to get the returned output you will need to get it in another way (write to file and then read it for example).

  • Related