Multiple when clause inside single stage in Jenkins file

Viewed 8044

I want to put multiple when clause in a single stage. Here is the basic example

def foo = 0
pipeline {
    agent any

    stages {
        stage('Hello') {
        when {
            expression {foo == 0}
        } 
            steps {
                echo 'foo is 0'
            }
        when {
            expression {foo == 1}
        } 
            steps {
                echo 'foo is 1'
            }
        }
    }
}

When I try this I recieve an error

 Multiple occurrences of the when section 

Actually my real problem is different but solving this will probably solve my real problem. Thanks in advance

1 Answers

It looks you'll be much better off using the directives as intended:

Multiple when is disallowed by design, if you looking a simple if else logic it's there:

  1. Straghtforward if statement:
stage {
    steps {
        script {
            if (foo == 0){
                echo 'foo is 0'
            }
            else if (foo == 1){
                echo 'foo is 1'
            }
        }
    }
}

If you'd like to use nested conditions in when:
2. Here you go:

stage {
    when {
      anyOf {
        environment name: 'VAR_1', value: '1'
        branch 'production'
      }
    }
    steps {
         <your steps>
    }
Related