【问题标题】:Jenkins pipeline analogue of exit 0出口 0 的 Jenkins 管道模拟
【发布时间】:2018-03-29 19:38:03
【问题描述】:

我有 Jenkins 管道,它由 2 个阶段组成,

我只想在特定条件下执行第二阶段,例如如果 git 分支不是 master。

当它在 bash 上时,我曾经使用简单的逻辑:

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

在 Jenkins 流水线 groovy 中怎么可能?

我的 Jenkinsfile 看起来像这样 -

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"
            }
        }
    }
}

..它不起作用:

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

【问题讨论】:

标签: groovy jenkins-pipeline


【解决方案1】:

经过一番研究,事实证明没有简单的方法可以做到这一点,只有一些解决方法。

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

所以最终决定是从声明式管道切换到脚本式管道,它简单明了:

【讨论】:

    【解决方案2】:

    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"
                }
            }
        }
    }
    

    参数:“主”:

    [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
    

    参数“与主不同的东西”:

    [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
    

    【讨论】:

      猜你喜欢
      • 2018-08-20
      • 2012-12-13
      • 1970-01-01
      • 2017-11-06
      • 2023-02-08
      • 1970-01-01
      • 1970-01-01
      • 2019-04-11
      • 1970-01-01
      相关资源
      最近更新 更多