Jenkins declarative pipeline. Conditional statement in post block

不羁岁月 提交于 2019-12-06 13:28:19

It's true you currently can't use when in the global post block. When must be used inside a stage directive.

It's a logical choice to use if else, but you'll need a scripted block inside the declarative pipeline to make this work:

pipeline {
    agent any

    parameters {
        string(defaultValue: "master", description: 'Which branch?', name: 'BRANCH_NAME')
    }

    stages {
        stage('test'){
            steps {
                echo "my branch is " + params.BRANCH_NAME
            }
        }
    }

    post {
        success{
            script {
                if( params.BRANCH_NAME == 'master' ){
                    echo "mail list master"
                }
                else {
                    echo "mail list others"
                }
            }
        }
    }
}

Output when parameter is master:

[Pipeline] {
[Pipeline] stage
[Pipeline] { (test)
[Pipeline] echo
my branch is master
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
mail list master
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

output when parameter is 'test':

[Pipeline] {
[Pipeline] stage
[Pipeline] { (test)
[Pipeline] echo
my branch is test
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] script
[Pipeline] {
[Pipeline] echo
mail list others
[Pipeline] }
[Pipeline] // script
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

Or to make it even more clean you can call the script as a function:

pipeline {
    agent any

    parameters {
        string(defaultValue: "master", description: 'Which branch?', name: 'BRANCH_NAME')
    }

    stages {
        stage('test'){
            steps {
                echo "my branch is " + params.BRANCH_NAME
            }
        }
    }

    post {
        success{
            getMailList(params.BRANCH_NAME)
        }
    }
}

def getMailList(String branch){
    if( branch == 'master' ){
        echo "mail list master"
    }
    else {
        echo "mail list others"
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!