1

I have a jenkins job:

properties([
    parameters([
        [$class: 'ChoiceParameter', choiceType: 'PT_CHECKBOX', description: '''The name of the image to be used.''', filterLength: 1, filterable: true, name: 'OS', randomName: 'choice-parameter-15413073438404172', script: [$class: 'GroovyScript', fallbackScript: [classpath: [], sandbox: true, script: ''], script: [classpath: [], sandbox: true, script: '''templates = [
        "BB-Win7-x32-SP1",
        "BB-Win7-x64-SP1",
        "BB-Win10-x64-RS1",
        "BB-Win10-x64-RS2",
        "BB-Win10-x32-RS5"]

        return templates''']]]])
])
....
....

Which is working and generates the checkbox property for the GUI as expected.

Now, I want to generate those options dynamically, based on a file in my workspace. For this, I need the workspace environment variable inside the groovy script. How can I do that?

omer mazig
  • 965
  • 2
  • 10
  • 17
  • To run your groovy script (the one that will need to read the file in your workspace after it checks out the workspace from Git...) Jenkins needs to create parameters. In order to create parameters, it needs to run a groovy script. You're in some chicken-and-egg problem here. Did you look at ActiveChoice plugin? – MaratC Mar 08 '20 at 09:25
  • The groovy script I'm talking about is not the actual pipeline. It's the script inside the `ChoiceParameter` class. – omer mazig Mar 08 '20 at 09:40
  • That's what ActiveChoice can achieve. – MaratC Mar 08 '20 at 10:15

1 Answers1

0

Jenkins needs to figure out all the parameters before it runs a pipeline. So your problem, basically, boils down to "How can I run an (arbitrary) groovy script before I run a pipeline?"

There are two options for this:

  1. As I mentioned, ActiveChoice plugin allows you to define a parameter that returns a script. Jenkins will then run the script (don't forget to approve it) in order to show you your "Build with parameters" page. Debugging this is notoriously hard, but this can go to great lengths.

  2. Alternatively, you may want to run a scripted pipeline before you run the Declarative (main) one, as outlined e.g. in this answer. This may look a bit like this:

def my_choices_list = []

node('master') {
   stage('prepare choices') {
       // read the file contents
       def my_choices = sh script: "cat ${WORKSPACE}/file.txt", returnStdout:true
       // make a list out of it - I haven't tested this!
       my_choices_list = my_choices.trim().split("\n")
   }
}

pipeline {
   parameters { 
        choiceParam('OPTION', my_choices_list)
MaratC
  • 6,418
  • 2
  • 20
  • 27
  • 1
    `returnOutput` should be `returnStdout`. But why not just use `readFile 'file.txt'`? – zett42 Mar 08 '20 at 11:15
  • 1
    Fixed, regarding the latter I usually start with `cat` since you can pipe that into `grep` or `awk` or `sed` depending on the use case, and I prefer to do these in bash and not in groovy. But for the simple case, `readFile` will work, too. – MaratC Mar 08 '20 at 12:18