如何在 Jenkins 的声明性管道中执行简单的 if 语句 [英] How to do simple if-statements inside a declarative pipeline in Jenkins

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

问题描述

我正在尝试将我的脚本化管道转换为声明性管道.想知道如何在 steps {} 块中执行简单的 if 语句.

I'm trying to convert my Scripted pipeline to a Declarative Pipeline. Wondering how to do a simple if-statement inside a steps {} block.

    stage ('Deploy to Docker') {
        steps {
            parallel (
                "instance1" : {
                    environment {
                        containerId = sh(script: "docker ps --quiet --filter name=${fullDockerImageName}", returnStdout: true).trim()
                    }
                    steps {
                        if (containerId.isEmpty()) {
                            docker.image('some/image').run("--name ${fullDockerImageName}")
                        }
                    }
                }
            )
        }
   }

这会导致以下异常:

WorkflowScript: 201: Expected a step @ line 201, column 29.
                           if (containerId.isEmpty()) {

由于我不允许在 steps {} 块内执行简单的 if(..),因此您知道如何执行此操作吗?

Since I'm not allowed to do a simple if(..) inside a steps {} block, any idea on how to do this?

使用 when {} 将其设为完整阶段似乎没有意义,因为在简单阶段中会发生更多步骤(如果存在,则启动已停止的容器,等).

It doesn't seem to make sense to make this a full stage with a when {}, since there are more steps that happens in a simple stage (starting a stopped container if it exists, etc).

做一个简单的 if 的最佳方法是什么?

What's the best way to do a simple if?

推荐答案

这应该可行

pipeline {
     stages {
        stage ('Main Stage') {
            steps {
                script {
                    if (true) {
                        stage ('Stage 1') {
                            sh 'echo Stage 1'
                        }
                    }
                    if (false) {
                        stage ('Stage 2') {
                            sh 'echo Stage 2'
                        }
                    }
                }
            }
        }
    }
}

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

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