post equivalent in scripted pipeline?

倾然丶 夕夏残阳落幕 提交于 2019-11-26 20:33:13

问题


What is the syntax of 'post' in scripted pipeline comparing to declarative pipeline? https://jenkins.io/doc/book/pipeline/syntax/#post


回答1:


For scripted pipeline, everything must be written programmatically and most of the work is done in the finally block:

Jenkinsfile (Scripted Pipeline):

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




回答2:


You can modify @jf2010 solution by using closures so that it looks a little neater (in my opinion)

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

postFailure = {
    echo 'This will run only if failed'
}

postAlways = {
    echo 'This will always run'
}


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


来源:https://stackoverflow.com/questions/48989238/post-equivalent-in-scripted-pipeline

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