jenkinsgroovyjenkins-pipelinejenkins-pluginsjenkins-groovy

Access JOB_BASE_NAME or JOB_NAME variable inside Active Choice Parameter Script


Either JOB_BASE_NAME or JOB_NAME needs to be accessed inside the active choice parameter script. Using the jobBaseName active choice parameter should dynamically process and present a drop-down list of inputs. According to active-choices-plugin docs it should be possible to access jenkinsBuild and jenkinsProject objects. Input() is not applicable since the users cannot be allowed to enter inputs, but rather select what's provided. How to read either JOB_NAME or JOB_BASE_NAME inside the script ? Appreciate any help in advance.

Below is the sample Jenkinsfile.

pipeline {
    agent {
        label "slave-2"
    }

    parameters {
        activeChoice choiceType: 'PT_SINGLE_SELECT', description: 'Some Description', filterLength: 1, filterable: false, name: 'PARAM_NAME', script: [ 
            classpath: [], sandbox: true, script: '''
                try {
                    def jobBaseName = env.JOB_BASE_NAME
                    
                    // Do something with jobBaseName and return result
                } catch(e) {return [e.toString()] } 

                /* try {
                    def jobBaseName = jenkinsProject.getDisplayName().split('/')?.first() 

                    // Do something with jobBaseName and return result
                } catch(e) {return [e.toString()] } */ 
            ''' 
        ] 
    } 
}

Attempted both approaches specified in the sample Jenkinsfile with no luck. Commented out the second approach but included for reference. If the jobBaseName is hardcoded, the active choice parameter is working as expected, so no issues in the rest of the functionality. But that would not be a feasible approach. Added try-catch exceptions to aid in troubleshooting. Please point out any mistakes since I'm a beginner in groovy.

Thanks !


Solution

  • try converting ''' to """ and using variable interpolation like - ${env.JOB_NAME}