How to run a post -> failure element in a declarative pipeline in a Jenkinsfile conditionally only?

Viewed 924

I have a declarative pipeline for I'd like to define a global post -> failure element which is only executed on certain branches. It ought to be executed after all stages in order to capture any failue in the pipeline. I want to use imported methods (e.g. from other groovy scripts), i.e. instead of an echo command shown in the example.

My aim is to create a notification which only happens on a certain set of branches and only in case of failure of any stage in the pipeline.

pipeline {
    agent any
    stages {
        stage('Compile') {
            steps {
                ...
            }
        }
        /* ... other stages ... */
    }
    post {
        success {
            echo 'whole pipeline successful'
        }
        failure {
            echo 'pipeline failed, at least one step failed'
        }
    }
}

post is supposed to contain step, just like steps, however steps are commands afaik (searched for one hours and didn't find a definition) and that means that I can't use when or nested steps (is that possible - I searched for hours as well).

I can't approach this with a linter, because all of them are limited to syntax checks and don't check the pipeline logic. I have tried the /pipeline-model-converter/validate URL which is painful because it can't be used from within the web sureface and in postman you need to approach OAuth authentification with trial and error. There's not even a Docker image for validation.

1 Answers

You can use a script block within the post block to execute Groovy statements. For example:

post {
    failure {
        script {
            if (env.GIT_BRANCH == 'dev') {
                echo 'pipeline failed'
                // email...
            }
        }
    }
}
Related