Search code examples
jenkins-pipelinejenkins-groovy

Jenkins Parameters: variables as default parameter


I have a choice parameter in my Jenkins job similar to this:

choice(name: 'CHOICE', choices: ['One', 'Two', 'Three'], description: 'Pick something')

Is there any way I could pass an array into my default choices instead of the static ['One', 'Two', 'Three']? Something like:

String[] DEFAULT_CHOICES = ['One', 'Two', 'Three']

choice(name: 'CHOICE', choices: DEFAULT_CHOICES, desc...)

————————————————————————————————————

Edit: How would I implement this in a declarative pipeline? I’ve tried:

extendedChoice(..., groovyScript: “return ${DEFAULT_CHOICES}”

And I keep getting errors. There doesn’t seem to be many examples on this implementation.


Solution

  • yes, you can do it in many ways. let me give you an example of 2 ways you can inject choice parameters

    def choiceVariableInjectFromAnApi=[]
    node {
        ['a','b','c'].each {
            choiceVariableInjectFromAnApi << "${it}"
        }
    }
    
    def choiceVariable = [1,2,3,4]
    
    pipeline {
        agent any;
        parameters {
            choice(name: 'CHOICE', choices: choiceVariableInjectFromAnApi, description: 'Pick something')
            choice(name: 'CHOICE2', choices: choiceVariable, description: 'Pick something')
        }
        stages {
            stage('debug') {
                steps {
                    echo "Selected Value From Choce parameter are  CHOICE = ${params.CHOICE} & CHOICE2 = ${params.CHOICE2}"
                }
            }
        }
    }