bp2*_*010 36

对于脚本化管道,一切都必须以编程方式编写,大部分工作都在finally块中完成:

Jenkinsfile (脚本管道):

node {
    try {
        stage('Test') {
            sh 'echo "Fail!"; exit 1'
        }
        echo 'This will run only if successful'
    } catch (e) {
        echo 'This will run only if failed'

        // Since we're catching the exception in order to report on it,
        // we need to re-throw it, to ensure that the build is marked as failed
        throw e
    } finally {
        def currentResult = currentBuild.result ?: 'SUCCESS'
        if (currentResult == 'UNSTABLE') {
            echo 'This will run only if the run was marked as unstable'
        }

        def previousResult = currentBuild.getPreviousBuild()?.result
        if (previousResult != null && previousResult != currentResult) {
            echo 'This will run only if the state of the Pipeline has changed'
            echo 'For example, if the Pipeline was previously failing but is now successful'
        }

        echo 'This will always run'
    }
}
Run Code Online (Sandbox Code Playgroud)

https://jenkins.io/doc/pipeline/tour/running-multiple-steps/#finishing-up

  • 是不是有更好的方法 - 我们是否希望在我们的脚本管道中复制所有这些逻辑? (4认同)
  • try块可以封装多个阶段吗?这样,我只需要对整个管道进行一次怪异操作即可。 (2认同)
  • 如果您使用脚本,则可以使用共享库。你仍然需要尝试最后的歌曲和舞蹈,但至少你不必重复整个逻辑。 (2认同)
  • 这是最好的答案,但也不是完全正确的答案。`currentBuild.result` 和 `currentBuild.currentResult` 在 `finally` 块中的值不正确,请参阅:https://issues.jenkins.io/browse/JENKINS-47403 以及其他一些报告。 (2认同)

sme*_*elm 11

您可以通过使用闭包来修改 @jf2010 解决方案,使其看起来更整洁(在我看来)

try {
    pipeline()
} catch (e) {
    postFailure(e)
} finally {
    postAlways()
}


def pipeline(){
    stage('Test') {
        sh 'echo "Fail!"; exit 1'
    }
    println 'This will run only if successful'
}

def postFailure(e) {
    println "Failed because of $e"
    println 'This will run only if failed'

}

def postAlways() {
    println 'This will always run'
}
Run Code Online (Sandbox Code Playgroud)