Jenkins 每个阶段有多个帖子部分

sem*_*ral 6 jenkins jenkins-pipeline

我有两个关于 Jenkins 管道中帖子部分的使用问题

1.我们可以在 Jenkins 声明式管道中的每个阶段使用多个 post 部分吗?

2.我们可以在post部分运行sh命令吗?

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

                ....
            }
            post {
                always {
                    script {
                        sh "..."
                    }
                }
            }
        }
     }
Run Code Online (Sandbox Code Playgroud)

Ser*_*ers 11

您可以在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'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以使用Post每个步骤Stage,但管道将在第一次失败时停止。在下面的示例中,如果Stage 1失败Stage 2将被跳过。Post毕竟所有阶段都会被执行。

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"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)