Jenkins 管道冒泡 shell 退出代码使阶段失败 [英] Jenkins pipeline bubble up the shell exit code to fail the stage

查看:22
本文介绍了Jenkins 管道冒泡 shell 退出代码使阶段失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里绝对是 Jenkins 流水线/groovy noob,我有一个舞台

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

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

使用的是共享库,Build.groovy 的源代码在这里:

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

如何冒泡 shell 脚本的退出代码并导致阶段失败?

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

推荐答案

sh 步骤返回的状态代码与您的实际 sh 命令(在本例中为您的脚本)返回的状态代码相同.来自 sh 文档 :

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.

您必须确保您的脚本在失败时返回非零状态代码.如果您不确定您的脚本返回什么,您可以使用 sh 步骤的 returnStatus 参数检查返回值,这不会使构建失败,但会返回状态码.例如:

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.

您可以使用:

  • currentBuild.result = 'FAILURE'currentBuild.result = 'UNSTABLE' 分别将步骤标记为红色/黄色.在这种情况下,构建仍将处理后续步骤.
  • error "Your error message" 如果您希望构建失败并立即退出.
  • 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.

这篇关于Jenkins 管道冒泡 shell 退出代码使阶段失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆