semural
semural

Reputation: 4611

Jenkins multipe post sections per stage

I have two question for usage of post section in Jenkins pipeline

1.Can we use multiple post section per stage in Jenkins declarative Pipeline?

2.Can we run sh command in post section?

pipeline{
    stages{
        stage("....") {
            steps { 
               script {
                ....
            }
        }
        post {
          failure{
               sh "....."
            }
        }
        stage("Second stage") {
            when {
                expression { /*condition */ }
            }
            steps {
                script{

                ....
            }
            post {
                always {
                    script {
                        sh "..."
                    }
                }
            }
        }
     }

Upvotes: 6

Views: 12676

Answers (1)

Sers
Sers

Reputation: 12255

You can find information in https://jenkins.io/doc/book/pipeline/syntax/#post

pipeline {
    agent any
    stages {
        stage('Example') {
            steps {
                echo 'Hello World'
            }
        }
    }
    post { 
        success { 
            sh label: 'success', script: 'ls'
        }
        failure { 
            sh label: 'failure', script: 'ls'
        }
        aborted { 
            sh label: 'aborted', script: 'ls'
        }
    }
}

You can use Post steps each Stage, but pipeline will stop on first failure. In example below, if Stage 1 fail Stage 2 will be skipped. Post after all stages will always executed.

pipeline{
    stages{
        stage("Stage 1") {
            steps {
                catchError(message: 'catch failure') { 
                    script {
                        sh "echo stage 1"
                    }
                }
            }
            post {
              always {
                    sh "echo post stage 1"
                }
            }
        }
        stage("Stage 2") {
            when {
                expression { /*condition */ }
            }
            steps {
                script{
                    sh "echo stage 2"
                }
            }
            post {
                always {
                    script {
                        sh "echo post stage 2"
                    }
                }
            }
        }
    }
    post {
        always {
            sh "echo post after all stages"
        }
    }
}

Upvotes: 12

Related Questions