Jenkins管道冒出shell退出代码以使阶段失败

Jam*_*Lin 18 groovy jenkins jenkins-pipeline

Absolute Jenkins管道/常规noob在这里,我有一个舞台

stage('Building and Deploying'){
    def build = new Build()
    build.deploy()
}
Run Code Online (Sandbox Code Playgroud)

这是使用共享库,其来源Build.groovy是:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是当未能将构建推送到远程仓库(见下文)时,该阶段仍然显示成功.

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
Run Code Online (Sandbox Code Playgroud)

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

Pom*_*m12 43

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

通常,以非零状态代码退出的脚本将导致步骤失败并出现异常.

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

def statusCode = sh script:script, returnStatus:true
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用此状态代码来设置当前构建的结果.

您可以使用 :

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