mesiu84
mesiu84

Reputation: 31

Choice paramter in jenkins as an output from shell script (pipeline)

I'm looking for a way to use an output from shell as a jenkins parameter but in pipeline, don't want to use any of UI plugins.

For example I want to use output from command

ls /home

as a choice parameter (so I would be able to choose users from the list), is it possible to do something like that? It must be done in pipeline, I'm not looking for some plugins which allow you to do something like that, but you need to do all in UI, if plugin support pipelines then it's also ok.

Upvotes: 1

Views: 2928

Answers (1)

MaratC
MaratC

Reputation: 6869

For a pipeline to run, its parameters need to be completely defined before the pipeline is started.

For the pipeline to parse the output of ls /home, it needs to run and allocate a node and a workspace, which can only happen after the pipeline is started.

So you are in a kind of a chicken-and-egg problem, where you need to run some code before you start a pipeline, but you can't run pipeline before you run that code.

So your issue boils down to "How can I run some arbitrary Groovy script before I start my pipeline?"

There are two options for this:

  1. 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 folder contents
       def my_choices = sh script: "ls -l /home", 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)

Upvotes: 2

Related Questions