Jenkins pipeline bubble up the shell exit code to fail the stage

我与影子孤独终老i 提交于 2019-11-30 12:00:12

问题


Absolute Jenkins pipeline/groovy noob here, I have a stage

stage('Building and Deploying'){
    def build = new Build()
    build.deploy()
}

which is using the shared lib, the source of the Build.groovy is here:

def deploy(branch='master', repo='xxx'){
    if (env.BRANCH_NAME.trim() == branch) {
        def script = libraryResource 'build/package_indexes/python/build_push.sh'
        // TODO: Test out http://stackoverflow.com/questions/40965725/jenkins-pipeline-cps-global-lib-resource-file-for-shell-script-purpose/40994132#40994132
        env.PYPI_REPO = repo
        sh script
    }else {
        echo "Not pushing to repo because branch is: "+env.BRANCH_NAME.trim()+" and not "+branch
    }
}

Problem is when failing to push the build to a remote repo (see below), the stage still ends up showing successful.

running upload
Submitting dist/xxx-0.0.7.tar.gz to https://xxx.jfrog.io/xxx/api/pypi/grabone-pypi-local
Upload failed (403): Forbidden
...
Finished: SUCCESS

How do I bubble up the exit code of the shell script and fail the stage?


回答1:


The sh step returns the same status code that your actual sh command (your script in this case) returns. From sh documentation :

Normally, a script which exits with a nonzero status code will cause the step to fail with an exception.

You have to make sure that your script returns a nonzero status code when it fails. If you're not sure what your script returns, you can check the return value using the returnStatus param of the sh step, which will not fail the build but will return the status code. E.g:

def statusCode = sh script:script, returnStatus:true

You can then use this status code to set the result of your current build.

You can use :

  • currentBuild.result = 'FAILURE' or currentBuild.result = 'UNSTABLE' to mark the step as red/yellow respectively. In this case the build will still process the next steps.
  • error "Your error message" if you want the build to fail and exit immediately.



回答2:


Just stumbled onto this question again, it turned out to be a Python version problem, I cannot remember the exact version of the Python but it was a problem within setuptools, IIRC upgrading Python to 2.7.1x fixed it.



来源:https://stackoverflow.com/questions/42428871/jenkins-pipeline-bubble-up-the-shell-exit-code-to-fail-the-stage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!