kol23
kol23

Reputation: 1598

post equivalent in scripted pipeline?

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

Upvotes: 57

Views: 37596

Answers (3)

Barel elbaz
Barel elbaz

Reputation: 636

For 'post always' with maintaining the build result you can use:

node{
    catchError{
        stage("Stage 1"){
            echo "Stage 1 is running"
        }

        stage("Stage 2"){
            echo "Stage 2 is running"
            error("fatal")
        }
    }

    stage("Send Email"){
        echo "currentResult: ${currentBuild.currentResult}" //FAILURE
        echo "Result: ${currentBuild.result}" //FAILURE
    }
}

https://www.jenkins.io/doc/pipeline/steps/workflow-basic-steps/#catcherror-catch-error-and-set-build-result-to-failure

Upvotes: 0

smelm
smelm

Reputation: 1334

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

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'
}

Upvotes: 17

bp2010
bp2010

Reputation: 2472

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

Upvotes: 94

Related Questions