Marat Gareev
Marat Gareev

Reputation: 427

Active choice parameter with declarative Jenkins pipeline


I'm trying to use active choice parameter with declarative Jenkins Pipeline script.

This is my simple script:


environments = 'lab\nstage\npro'

properties([
    parameters([
        [$class: 'ChoiceParameter',
            choiceType: 'PT_SINGLE_SELECT',
            description: 'Select a choice',
            filterLength: 1,
            filterable: true,
            name: 'choice1',
            randomName: 'choice-parameter-7601235200970',
            script: [$class: 'GroovyScript',
                fallbackScript: [classpath: [], sandbox: false, script: 'return ["ERROR"]'],
                script: [classpath: [], sandbox: false, 
                    script: """
                        if params.ENVIRONMENT == 'lab'
                            return['aaa','bbb']
                        else
                            return ['ccc', 'ddd']
                    """
                ]]]
    ])
])

pipeline {
    agent any
    tools {
        maven 'Maven 3.6'
    }
    options {
        disableConcurrentBuilds()
        timestamps()
        timeout(time: 30, unit: 'MINUTES')
        ansiColor('xterm')
    }
    parameters {
        choice(name: 'ENVIRONMENT', choices: "${environments}")
    }
    stages {
        stage("Run Tests") {
            steps {
                sh "echo SUCCESS on ${params.ENVIRONMENT}"
            }
        }
    }
}

But actually the second parameter is empty

enter image description here

Is it possible to use together scripted active choice parameter and declarative parameter?

UPD Is there any way to pass list variable into script? For example

List<String> someList = ['ttt', 'yyyy']
...
script: [
    classpath: [], 
    sandbox: true, 
    script: """
        if (ENVIRONMENT == 'lab') { 
            return someList
        }
        else {
            return['ccc', 'ddd']
        }
    """.stripIndent()
]

Upvotes: 4

Views: 24822

Answers (2)

user1767316
user1767316

Reputation: 3631

As of Jenkins 2.249.2 without any plugin and using a declarative pipeline, the following pattern prompt the user with a dynamic dropdown menu (for him to choose a branch):

(the surrounding withCredentials bloc is optional, required only if your script and jenkins configuratoin do use credentials)

node {

withCredentials([[$class: 'UsernamePasswordMultiBinding',
              credentialsId: 'user-credential-in-gitlab',
              usernameVariable: 'GIT_USERNAME',
              passwordVariable: 'GITLAB_ACCESS_TOKEN']]) {
    BRANCH_NAMES = sh (script: 'git ls-remote -h https://${GIT_USERNAME}:${GITLAB_ACCESS_TOKEN}@dns.name/gitlab/PROJS/PROJ.git | sed \'s/\\(.*\\)\\/\\(.*\\)/\\2/\' ', returnStdout:true).trim()
}

} pipeline {

agent any

parameters {
    choice(
        name: 'BranchName',
        choices: "${BRANCH_NAMES}",
        description: 'to refresh the list, go to configure, disable "this build has parameters", launch build (without parameters)to reload the list and stop it, then launch it again (with parameters)'
    )
}

stages {
    stage("Run Tests") {
        steps {
            sh "echo SUCCESS on ${BranchName}"
        }
    }
}

}

The drawback is that one should refresh the jenkins configration and use a blank run for the list be refreshed using the script ...

Solution (not from me): This limitation can be made less anoying using an aditional parameters used to specifically refresh the values:

parameters {
        booleanParam(name: 'REFRESH_BRANCHES', defaultValue: false, description: 'refresh BRANCH_NAMES branch list and launch no step')
}

then wihtin stage:

stage('a stage') {
   when {
      expression { 
         return ! params.REFRESH_BRANCHES.toBoolean()
      }
   }
   ...
}

Upvotes: 2

yong
yong

Reputation: 13712

You need to use Active Choices Reactive Parameter which enable current job parameter to reference another job parameter value

environments = 'lab\nstage\npro'

properties([
    parameters([
        [$class: 'CascadeChoiceParameter', 
            choiceType: 'PT_SINGLE_SELECT',
            description: 'Select a choice',
            filterLength: 1,
            filterable: true,
            name: 'choice1',
            referencedParameters: 'ENVIRONMENT',
            script: [$class: 'GroovyScript',
                fallbackScript: [
                    classpath: [], 
                    sandbox: true, 
                    script: 'return ["ERROR"]'
                ],
                script: [
                    classpath: [], 
                    sandbox: true, 
                    script: """
                        if (ENVIRONMENT == 'lab') { 
                            return['aaa','bbb']
                        }
                        else {
                            return['ccc', 'ddd']
                        }
                    """.stripIndent()
                ]
            ]
        ]
    ])
])

pipeline {
    agent any

    options {
        disableConcurrentBuilds()
        timestamps()
        timeout(time: 30, unit: 'MINUTES')
        ansiColor('xterm')
    }
    parameters {
        choice(name: 'ENVIRONMENT', choices: "${environments}")
    }
    stages {
        stage("Run Tests") {
            steps {
                sh "echo SUCCESS on ${params.ENVIRONMENT}"
            }
        }
    }
}

Upvotes: 11

Related Questions