Jenkins管道模拟出口0

时间:2018-03-28 08:48:04

标签: groovy jenkins-pipeline

我有Jenkins管道,包括两个阶段,

我想仅在某些条件下执行第二阶段,例如如果git branch不是master。

当它在bash上时我常常使用简单的逻辑:

if [condition] {exit 0} else {stage2 function} fi

Jenkins管道如何实现groovy?

我的Jenkins文件看起来像这样 -

pipeline {
    agent any
    stages {
        stage ('First') {
            steps {
                echo "First"
            }

            if (env.BRANCH_NAME == 'master') {
                echo 'First stage is enought, exit 0 shoul happened here'
                currentBuild.result = 'SUCCESS'
                return
            } else {
                echo 'Second stage must be executed'
            }

        }

        stage('Second') {
            steps {
                echo "Second"
            }
        }
    }
}

..它不起作用: enter image description here

但是,它在脚本管道中按预期工作 - https://github.com/kagarlickij/jenkins-pipeline/blob/scripted/Jenkinsfile

2 个答案:

答案 0 :(得分:1)

声明性管道阶段内的

exit 0只会退出当前阶段而不是完整管道。这就是为什么我会推荐以下解决方法(我使用参数,但你当然也可以使用env var):

pipeline {
    agent any

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

    stages {
        stage ('First') {
            when { 
                expression 
                    {  params.BRANCH == 'master' } 
            }
            steps {
                echo "Branch is master"
            }
        }

        stage('Second') {
            when { 
                expression 
                    {  params.BRANCH != 'master' } 
            }
            steps {
                echo "Branch is not master"
            }
        }
    }
}

参数:" master":

[Pipeline] {
[Pipeline] stage
[Pipeline] { (First)
[Pipeline] echo
Branch is master
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Second)
Stage 'Second' skipped due to when conditional
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

参数"与master不同的东西":

[Pipeline] {
[Pipeline] stage
[Pipeline] { (First)
Stage 'First' skipped due to when conditional
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Second)
[Pipeline] echo
Branch is not master
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

答案 1 :(得分:1)

经过一番研究后发现,没有简单的方法可以做到,只需要几个解决方法。

变通办法可能对超级简单的管道有好处,但如果管道有几十个阶段,那就不会更糟。

因此,最终的决定是从声明性转换为脚本化管道,其中简单明了: enter image description here