如何在声明式管道中执行when..else [英] How to perform when..else in declarative pipeline

查看:65
本文介绍了如何在声明式管道中执行when..else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用声明性管道.此部分有效:

I'm using a declarative pipeline. This part works:

        steps {
            script {
                if ('xxx' == 'cloud') {
                    sh 'xxx'
                } else {
                    sh 'xxx'
                }
            }
        }

但是我想使用何时来使用更具声明性的管道语法. . 我尝试过这样的事情:

But I want to follow the more declarative pipeline syntax using when. I tried something like this:

        stage ('Newman run') {
            when {
                expression { "xxx" == "cloud" }
            }
            steps {
                echo 'Use proxy for cloud'
                sh 'xx'
            }
            when {
                expression { "cloud" == "cloud" }
            }
            steps {
                echo 'Do not use proxy (non-cloud)'
                sh 'xxx'
            }

但是没有用.如何在声明性管道中的when之后指定一种'else'语句.还是如果这种方法行不通,推荐的方法是这样做吗?

But it didn't work. How I can specify a sort of 'else' statement after a when in a declarative pipeline. Or if this not works, the recommended way to do this?

推荐答案

您发布的第一个代码段是一个不错的选择.您可以在第二阶段使用'not'指令,如下所示:

The first snippet you posted is a good way to go. You could use the 'not' directive in a second stage like this:

stage('then') {
  when {
    <condition>
  }
  steps {
    ...
  }
}
stage('else') {
  when {
    not {
      <condition>
    }
  }
  steps {
    ...
  }
}

但这看起来并不比将其包装在"script"语句中更好,因为您甚至可以将条件保持两次.这是两个单独的阶段出现在您的管道中.

But that doesn't look better than wrapping it in a 'script' statement, because you would even maintain the condition twice. And it's two separate stages that appear in your pipeline.

因此,在脚本块中使用if-then-else.

So stay with the if-then-else inside a script block.

合理性:声明性管道的想法是保持它简单而不包含复杂的算法.当您试图在Jenkinsfile中使用if语句,循环等时,请问自己是否做正确的事.通常使用这些东西,即使没有错,但可能是您的问题有一个更简单的解决方案.

Rationale: The idea of the declarative pipeline is to keep it simple without complex algorithms in it. When you are tempted to use if statements, loops, etc. in your Jenkinsfile, ask yourself if you are doing the right thing. Using these things if not wrong in general, but it could be that there is a simpler solution for your problem.

这篇关于如何在声明式管道中执行when..else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆