user6348718
user6348718

Reputation: 1395

Jenkins pipeline conditional stage using "When" for choice parameters

I am trying to build a jenkins pipeline where I have a choice parameter with n choices and want to create a stage which does something when some values from the choice parameter are selected I have something like below but doesn't seem to work.

#!/usr/bin/env groovy

pipeline {

agent any

    parameters {

        choice(
                choices: 'a\nb\n\c\n\d\ne\nf',
                description: 'name of the student',
                name: 'name'
        )
    }
 stages {
       stage ('callNames') {

        when {
             expression { params.name == 'a|d|f' }
        }
        steps{
        echo "selected name is: ${name}"
        //do something

            }
        }        
    }
}

So, I want to do something when the selected values for the parameter name are either a or d of f For the above, I get no errors but I am seeing this in the console output

Stage 'callNames' skipped due to when conditional when I select the value a/d/f during the build

Please let me know what's missing here Thanks in advance

Upvotes: 15

Views: 50238

Answers (1)

Travenin
Travenin

Reputation: 1590

Your when expression has an error. If your parameter's name value is 'a', you are comparing strings 'a' == 'a|d|f' in your code, which is false.

You probably want to do

when {
    expression { 
        params.name == 'a' ||
        params.name == 'd' ||
        params.name == 'f' 
    }
}

Or, if you prefer oneliner, you can use regular expression

when {
    expression { 
        params.name ==~ /a|d|f/
    }
}

Upvotes: 25

Related Questions