Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 873
user6348718 Avatar asked May 17 '18 00:05

user6348718


People also ask

How does Jenkins pipeline pass Choice parameters?

Go to Jenkins Home, select New Item, add a name for your Job, for the project type, select Pipeline project and click on Ok. On the configure job page select the This project is parameterized checkbox in the general tab. Now, we will add an Active Choices Parameter which renders our Application Tiers as a Dropdown.

Can we run a step conditionally in Jenkins?

Jenkins “when” Directive:Execution of the pipeline stages can be controlled with conditions. These conditions must be defined in the when block within each stage. Jenkins supports a set of significant conditions that can be defined to limit stage execution. Each when block must contain at least one condition.

How do I add extended choice parameters in Jenkins?

To install this plugin, you simply need to go to your jenkins instance and navigate to “/pluginManager/available”, and then search for “Extended Choice Parameter Plug-in” in the search box. Be careful! There is another plugin called “Extensible Choice Parameter Plug-in”.


1 Answers

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/
    }
}
like image 174
Travenin Avatar answered Nov 16 '22 00:11

Travenin