How to do simple if-statements inside a declarative pipeline in Jenkins How to do simple if-statements inside a declarative pipeline in Jenkins jenkins jenkins

How to do simple if-statements inside a declarative pipeline in Jenkins


This should work

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


Unfortunately you have to wrap it within a script, for now. As it says here;

Declarative Pipelines may use all the available steps documented in the Pipeline Steps reference, which contains a comprehensive list of steps, with the addition of the steps listed below which are only supported in Declarative Pipeline.

And if you look at the step reference it simply lists all plugins which contributes pipeline steps. And as far as I can see, there is no step supporting if, then, else. So the answer is, no, right now it is not possible, but, it should be fairly simple to implement this as a step and add to a plugin.


I think that this is the most correct/best practice way about using if/else or control logic within your Jenkins Declarative pipeline.

https://jenkins.io/doc/book/pipeline/syntax/#when

@IronSean answer, doesn't seem like you need that plugin (anymore).