Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate choice parameter in jenkinsfile with list of folders in SCM repository

I've got a Jenkinsfile that drives a pipeline which the user must select a specific folder in a bitbucket repo to target. I want that choice parameter dropdown to be dynamically populated.

Currently, I've got the choice param list hardcoded as per this generic example:

choice(name: 'IMAGE', choices: ['workload-x','workload-y','workload-z'])

I wondered if this is possible from within the jenkinsfile itself, or whether I'd have to create a specific groovy script for this then call it. Either way I'm a bit lost as I'm pretty new to jenkins and have only just started working with Jenkinsfiles.

Some trial and error googling has allowed me to create a groovy script which returns an array of folder names in the repository using json slurper:

import groovy.json.JsonSlurper
import jenkins.model.Jenkins

def creds = com.cloudbees.plugins.credentials.CredentialsProvider.lookupCredentials(
        com.cloudbees.plugins.credentials.Credentials.class,
        Jenkins.instance,
        null,
        null
    );

def credential = creds.find {it.id == "MYBITBUCKETCRED"}

if (!credential) { return "Unable to pickup credential from Jenkins" }
username = credential.username
pass = credential.password.toString()

def urlStr = "https://bitbucket.mydomain.com/rest/api/1.0/projects/MYPROJECT/repos/MYREPO/browse/"

HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection()
String encoded = Base64.getEncoder().encodeToString((username + ":" + pass).getBytes("UTF-8"));
conn.setRequestProperty("Authorization", "Basic " + encoded);
conn.connect();

def slurper = new JsonSlurper() 
def browseList = slurper.parseText(conn.getInputStream().getText())

def dfList = browseList.children.values.path.name.findAll {it.contains('workload-')}

return dfList

This returns a result as follows:

Result:   [workload-a,workload-b,workload-c,workload-x,workload-y,workload-z]

However I'm unsure how then to call this in my Jenkinsfile in order to populate the dropdown.

Any help would be greatly appreciated.

like image 359
Molenpad Avatar asked Oct 21 '25 06:10

Molenpad


2 Answers

you can do it this way (follow my example below) or make use of Active Choice Jenkins Plugins - because It allows some groovy scripting to prepare your choice

Note- The Choice parameter will be available after a first run.

def choiceArray = []
node {
    checkout scm
    def folders = sh(returnStdout: true, script: "ls $WORKSPACE")
    
    folders.split().each {
        //condition to skip files if any
        choiceArray << it
    }
}

pipeline {
    agent any;
    parameters { choice(name: 'CHOICES', choices: choiceArray, description: 'Please Select One') }
    stages {
        stage('debug') {
            steps {
                echo "Selected choice is : ${params.CHOICES}"
            }
        }
    }
}
like image 199
Samit Kumar Patel Avatar answered Oct 24 '25 12:10

Samit Kumar Patel


I used the previous example to load the list in the same build I send the command output to a file, to be consumed in the next step

Here the jenkinsfile:

def choiceArray = []

pipeline {
 agent any
  parameters {
  string defaultValue: '', description: 'PATH_to_scripts', name: 'SCRIPTPATH', trim: false
  string defaultValue: '', description: 'Optional parameters', name: 'MOREparams', trim: false
  }
 stages {
    stage('show available date') {
      steps {
        sh '''
        echo $JENKINS_HOME
        cd $JENKINS_HOME/scripts
        ./0_db_show_available.sh $DBlike $AWS_PROFILE $DATEFILTER > $JENKINS_HOME/scripts/lista.txt
        echo "Show available date"
        cat $JENKINS_HOME/scripts/lista.txt
        '''
      }
    }
   stage('Restore') {
        steps {
            script {
              def folders = sh(returnStdout: true, script: "cat $JENKINS_HOME/scripts/lista.txt")    
              //load the array using the file content (lista.txt)
                folders.split().each {
                    choiceArray << it
                }                  
                // wait for user input 
              def INPUT_DATE = input message: 'Please select date', ok: 'Next',
              //generate the list using the array content
              parameters: [ choice(name: 'CHOICES', choices: choiceArray, description: 'Please Select One') ]
            }
        }
    }
 }
}

samit-kumar-patel, thanks for first example, it helps me

like image 42
lordJeA Avatar answered Oct 24 '25 12:10

lordJeA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!