Search code examples
jenkinsgroovyjenkins-pipelinepipelinejenkins-groovy

How to create dynamic checkbox parameter in Jenkins pipeline?


I found out how to create input parameters dynamically from this SO answer

    agent any
    stages {
        stage("Release scope") {
            steps {
                script {
                    // This list is going to come from a file, and is going to be big.
                    // for example purpose, I am creating a file with 3 items in it.
                    sh "echo \"first\nsecond\nthird\" > ${WORKSPACE}/list"

                    // Load the list into a variable
                    env.LIST = readFile (file: "${WORKSPACE}/list")

                    // Show the select input
                    env.RELEASE_SCOPE = input message: 'User input required', ok: 'Release!',
                            parameters: [choice(name: 'CHOOSE_RELEASE', choices: env.LIST, description: 'What are the choices?')]
                }
                echo "Release scope selected: ${env.RELEASE_SCOPE}"
            }
        }
    }
}

This allows us to choose only one as it's a choice parameter, how to use the same list to create checkbox parameter, so the user can choose more than one as needed? e.g: if the user chooses first and third, then the last echo should print Release scope selected: first,third or the following is fine too, so I can iterate over and find the true ones Release scope selected: {first: true, second: false, third: true}


Solution

  • I could use extendedChoice as below

        agent any
        stages {
            stage("Release scope") {
                steps {
                    script {
                        // This list is going to come from a file, and is going to be big.
                        // for example purpose, I am creating a file with 3 items in it.
                        sh "echo \"first\nsecond\nthird\" > ${WORKSPACE}/list"
    
                        // Load the list into a variable
                        env.LIST = readFile("${WORKSPACE}/list").replaceAll(~/\n/, ",")
    
                        env.RELEASE_SCOPE = input message: 'User input required', ok: 'Release!',
                                parameters: [extendedChoice(
                                name: 'ArchitecturesCh',
                                defaultValue: "${env.BUILD_ARCHS}",
                                multiSelectDelimiter: ',',
                                type: 'PT_CHECKBOX',
                                value: env.LIST
                          )]
                          // Show the select input
                          env.RELEASE_SCOPE = input message: 'User input required', ok: 'Release!',
                                parameters: [choice(name: 'CHOOSE_RELEASE', choices: env.LIST, description: 'What are the choices?')]
                    }
                    echo "Release scope selected: ${env.RELEASE_SCOPE}"
                }
            }
        }
    }