Issue
I have a consul keys AAA/BBB/test-key like '1,2,3', AAA/CCC/test-key like '4,5,6' and others.
I have a shared Jenkinsfile between several jobs.
I do not want to make Jenkinfile per each job. I want to access keys by job name but I can't make it working.
It works if I hardcode key in the URL, e.g.
node('master') {
properties([parameters([
[ $class: 'ChoiceParameter',
name: 'GROUPS',
description: 't2',
randomName: 't3',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [], sandbox: false, script: ''
],
script: [
classpath: [], sandbox: false, script:
'''
def text = new URL('http://consul.local:8500/v1/kv/AAA/BBB/test-key?raw').getText()
return text.split(",").collect{ (it=~/\\d+|\\D+/).findAll() }.sort().collect{ it.join() } as List
'''
]
],
choiceType: "PT_RADIO", //PT_SINGLE_SELECT,PT_MULTI_SELECT,PT_RADIO,PT_CHECKBOX
filterable: true,
filterLength: 1
]
])])
}
However, when I try to use env.JOB_NAME
inside the URL, it does not work:
node('master') {
properties([parameters([
[ $class: 'ChoiceParameter',
name: 'GROUPS',
description: 't2',
randomName: 't3',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [], sandbox: false, script: ''
],
script: [
classpath: [], sandbox: false, script:
'''
def text = new URL('http://consul.local:8500/v1/kv/AAA/'+ env.JOB_NAME + '/test-key?raw').getText()
return text.split(",").collect{ (it=~/\\d+|\\D+/).findAll() }.sort().collect{ it.join() } as List
'''
]
],
choiceType: "PT_RADIO", //PT_SINGLE_SELECT,PT_MULTI_SELECT,PT_RADIO,PT_CHECKBOX
filterable: true,
filterLength: 1
]
])])
}
How can I access env variables inside the choice parameter defined with the Groovy script?
Solution
If you want to pass env.JOB_NAME
to the script content you have to replace '''
with """
and refer to the variable with ${env.JOB_NAME}
. Something like this:
script: [
classpath: [], sandbox: false, script:
"""
def text = new URL('http://consul.local:8500/v1/kv/AAA/${env.JOB_NAME}/test-key?raw').getText()
return text.split(",").collect{ (it=~/\\d+|\\D+/).findAll() }.sort().collect{ it.join() } as List
"""
]
Answered By - Szymon Stepniak
Answer Checked By - Clifford M. (JavaFixing Volunteer)