How to use Folder Vars with Active Choices Groovy script

Article ID:360015623532
1 minute readKnowledge base

Issue

How can I access Folder variables from an Active Choices Groovy script?

Resolution

Folder variables are not directly supported by the plugin, i.e. they can not be used directly in a Groovy script to provide different dynamic choices.

Nevertheless, it is possible to access these Folder variables following the steps shown below.

  • Given a folder named Folder-A, let’s create a variable ENVVAR_001 as shown in the image below. Creating the var in the Folder

  • Create a job inside that folder (Job-B).

  • Once created, we can create an Active Choice Parameter: Parameter Definition

  • And provide a Groovy script to dynamically generate that parameter. For that, we can use a code snippet like the one shown below:

      import hudson.model.*
      import jenkins.model.*
      import hudson.Util
      myValue=""
    
      def p = Jenkins.instance.getItemByFullName("FOLDER-A/job-B").getParent().getProperties().getAll(com.cloudbees.hudson.plugins.folder.properties.EnvVarsFolderProperty.class).get(0)
    
      def myvar= p.getClass().getDeclaredField("properties").get(p)
      Map myProperties= (Map) Util.loadProperties(myvar)
    
      // We got just first value in the properties as that is the value that we want to use.
      return ['-select-', myProperties.values()[0]]

    This will render the results shown below:

    This is a very basic example but can serve as a starting point for more complex scripts.

NOTE: This has been tested with CloudBees Core Traditional Platforms - Client controller 2.73.30.0.1 and Active Choices Plugin 2.1