How to use Folder Vars with Active Choices Groovy script

Issue

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

Environment

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:
    Results

    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 Master 2.73.30.0.1 and Active Choices Plugin 2.1

Have more questions?

1 Comments

  • 0
    Avatar
    Michele Vanini

    Is there a way to get actual fullJobName for both freestyle and pipeline jobs from the job itself? So the script in active-choice will be dynamically update if I move/copy job

    Edited by Michele Vanini
Please sign in to leave a comment.