【问题标题】:post equivalent in scripted pipeline?在脚本化管道中发布等价物?
【发布时间】:2018-02-26 13:05:26
【问题描述】:

与声明式管道相比,脚本管道中的“post”的语法是什么? https://jenkins.io/doc/book/pipeline/syntax/#post

【问题讨论】:

    标签: jenkins-pipeline


    【解决方案1】:

    对于脚本化管道,一切都必须以编程方式编写,并且大部分工作都在 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'
        }
    }
    

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

    【讨论】:

    • 难道没有更好的方法 - 我们是否希望在我们的脚本化管道中复制所有这些逻辑?
    • 感谢您指出这一点。每次浏览都有很多“代码噪音”
    • try 块可以封装多个阶段吗?这样我只需要为整个管道制作一次这个怪物。
    • 可悲的开销,因为我们想在多个阶段之后执行发布操作..
    • 如果你使用脚本,你可以使用共享库。你仍然需要尝试最后的歌舞,但至少你不必重复整个逻辑。
    【解决方案2】:

    您可以修改@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'
    }
    

    【讨论】:

      猜你喜欢
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多