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.
question from:
https://stackoverflow.com/questions/66049517/populate-choice-parameter-in-jenkinsfile-with-list-of-folders-in-scm-repository 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…