Search code examples
jenkinsgroovyparametersjenkins-pluginshudson

Getting a second parameter based on the first parameter in Jenkins


I have a task where my Jenkins job needs two parameters for build. The first specifies the application name and can be either QA, Dev, Prod etc and the second is a server which is dependent on the first one.

Example: If I chose the app name as QA, the second parameter should display values like QAServer1, QAServer2, QAServer3.

I'm using Active Choices Plugin (https://wiki.jenkins.io/display/JENKINS/Active+Choices+Plugin) to get this done but facing an problem in fetching the second parameter contents.

Snapshots: enter image description here

For obtaining the second parameter, I've written a Groovy code which reads the respective files of the selected first parameter and gets the details.

code:

#!/usr/bin/env groovy
import hudson.model.*
def Appliname = System.getenv("APPNAME")
//println Appliname
def list1 = []
def directoryName = "C:/Users/Dev/Desktop/JSONSTest"
def fileSubStr = Appliname
def filePattern = ~/${fileSubStr}/
def directory = new File(directoryName)
def findFilenameClosure =
{
   if (filePattern.matcher(it.name).find())
   {
      def jsoname = it.name
      def jsoname1 = jsoname.reverse().take(9).reverse()
      list1.add(jsoname1.substring(1,4))
      String listAsString =  "[\'${list1.join("', '")}\']"
      println "return"+listAsString
   }

}
directory.eachFileRecurse(findFilenameClosure)

The above code will print the output as return['QAServer1', 'QAServer2'] which i want to use it as input for the second parameter.

Snapshot of Second parameter:

enter image description here

Somehow the Groovy script is not being executed and second parameter value remains empty. How can i get this done dynamically. Am i following the right away to it. Kindly help me figure out. TIA


Solution

  • Would you like to try below change

    From:

    def findFilenameClosure =
    {
       if (filePattern.matcher(it.name).find())
       {
          def jsoname = it.name
          def jsoname1 = jsoname.reverse().take(9).reverse()
          list1.add(jsoname1.substring(1,4))
          String listAsString =  "[\'${list1.join("', '")}\']"
          println "return"+listAsString
       }
    
    }
    directory.eachFileRecurse(findFilenameClosure)
    

    To:

    directory.eachFileRecurse {
           if (filePattern.matcher(it.name).find()) {
              def jsoname = it.name
              def jsoname1 = jsoname.reverse().take(9).reverse()
              list1.add(jsoname1.substring(1,4))      
           } 
        }
        return list1