Pass Groovy object into active choice parameter - jenkins

I use active choice reactive parameter with declarative pipeline. But I ran into a problem.
Is there any way to pass list object into script or call external method?
For example
environments = 'lab\nstage\npro'
List<String> someList = ['ccc', 'ddd']
def someMethod() {
return ['aaa', 'bbb']
}
properties([
parameters([
choice(name: 'ENVIRONMENT', choices: "${environments}"),
[$class: 'CascadeChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
description: 'Select a choice',
filterLength: 1,
filterable: true,
name: 'choice1',
referencedParameters: 'ENVIRONMENT',
script: [$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script: 'return ["ERROR"]'
],
script: [
classpath: [],
sandbox: true,
script: """
if (ENVIRONMENT == 'lab') {
return someMethod() // !!! call method
}
else {
return someList // !!! return object
}
""".stripIndent()
]
]
]
])
])
pipeline {
agent any
...
}
I would be grateful for any hints.

Solved it by using string interpolation
List<String> someList = ['ccc', 'ddd']
def someMethod() {
return ['aaa', 'bbb']
}
...
script: """
if (ENVIRONMENT == 'lab') {
return ["${someMethod().join('","')}"] // !!! call method
}
else {
return ["${someList.join('","')}"] // !!! return object
}
""".stripIndent()
UPD: a function call with an argument that is a job parameter.
In this case, the current solution will not work, since the argument variable will be searched for in the external context. You can replace it with params.ParamName:
return ["${someMethod(params.ParamName).join('","')}"]
but then its value will be null.
So, you have to put whole function into parameter script like this:
properties([
parameters([
[$class: 'ChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
filterable: false,
name: 'PartnerName',
script: [$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script: 'return ["ERROR"]'
],
script: [
classpath: [],
sandbox: true,
script: """
return ["single_partner"]
""".stripIndent()
]
]
],
[$class: 'CascadeChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
filterLength: 1,
filterable: false,
name: 'AutoCalcParam',
referencedParameters: 'PartnerName',
script: [$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script: 'return ["ERROR"]'
],
script: [
classpath: [],
sandbox: true,
script: """
def getGFEPartners(String partnerName) {
return [partnerName+'_aaa', partnerName+'_bbb']
}
return getGFEPartners(PartnerName)
""".stripIndent()
]
]
],
And will see expected result:

Related

How to order Jenkins Parameters using groovy script

I am using this groovy script to parameterize a Jenkins Job:
properties([
parameters([
[$class: 'ChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
description: 'Select param1',
filterLength: 1,
filterable: false,
name: 'param1',
randomName: 'choice-parameter-5631314439613978',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script:
'return[\'Could not get param1\']'
],
script: [
classpath: [],
sandbox: true,
script:
'return["value1", "value2", "value3"]'
]
]
],
[$class: 'CascadeChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
description: 'Select param3',
filterLength: 1,
filterable: false,
name: 'param3',
randomName: 'choice-parameter-10000000000000000',
referencedParameters: 'param1',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script:
'return[\'Could not get param3\']'
],
script: [
classpath: [],
sandbox: true,
script:
''' if (param1.equalsIgnoreCase('value1')){
return["1", "2"]
}
else if(param1.equalsIgnoreCase("value2")){
return["3", "4"]
}
else if(param1.equalsIgnoreCase("value3")){
return["5", "6"]
}
'''
]
]
]
])
])
pipeline {
agent any
parameters {
string(name: "param2", defaultValue: "test1", description: "Test value")
}
stages {
stage ("Example") {
steps {
script{
echo 'Hello'
}
}
}
}
}
If I use this script as is, On the Jenkins job, parameters will be shown in this order: param2, param1, param3. What I really want, is to have them in this order: param1, param2, param3.
From the code as you can see, for param 1 and 3 I am using Active Choice Parameter and Active Choice Reactive Parameter which will be dependent from the value selected in param1. For param2, I need it as string.
Is there a way to achieve this, have them in this order: param1, param2, param3?
Okay, i found that i can use also this in the properties:
[$class: 'StringParameterDefinition',
description: 'Enter param2',
name: 'param2',
defaultValue: '',
randomName: 'string-parameter-1343433232',
trim: true
]

Access global map variable inside active choice reactive reference parameter

I am trying to set a global map variable in a jenkins declarative pipeline. I am trying to access it inside an Active Choice Reactive Reference parameter. I tried many ways to achieve this but nothing worked.
Below is my sample Pipeline.
def sampleMap= [
'students' : ['12312312'],
'teachers' : ['145436436']
]
pipeline {
agent any
stages {
stage('set params') {
steps{
script {
properties([
parameters([
[
$class: 'CascadeChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
description: '',
filterLength: 1,
filterable: false,
name: 'Type',
randomName: 'choice-parameter-1325654724334254',
referencedParameters: '',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script: ''
], script: [
classpath: [],
sandbox: true,
script: '''
def choices = []
choices.add('students')
choices.add('teachers')
return choices'''
]
]
],
[
$class: 'DynamicReferenceParameter',
choiceType: 'ET_FORMATTED_HTML',
description: '',
name: 'value',
randomName: 'choice-parameter-14347325234254',
referencedParameters: 'Type',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script: ""
],
script: [
classpath: [],
sandbox: true,
script: '''
def result= ${sampleMap.get(Type)}
return """<input name=\"value\" value=\"${result}\" class=\"setting-input\" type=\"text\">"""
'''
]
],
omitValueField: true
]
])
])
}
}
}
}
As per above script, I have a global Map variable with list of students and list of teachers. I have two build parameters named as Type and value. Type is a dropdown with values 'students' and 'teachers' . Based on the dropdown selection, I want to refer to the global map variable and access it's respective value in another build parameter.
It seems like the active choice parameter is unable to access global variables. Or is that a syntax issue?
Can anyone help?
Thanks!
You should pass whole map into script and call it:
[$class: 'CascadeChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
filterLength: 1,
filterable: false,
name: 'value',
referencedParameters: 'Type',
script: [$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: true,
script: 'return ["ERROR"]'
],
script: [
classpath: [],
sandbox: true,
script: """
def sampleMap = ${sampleMap.inspect()}
return sampleMap.get(Type)
""".stripIndent()
]
]
]

Dynamic or Conditional display of Jenkins job's parameters

I am trying to use following jenkins job to generate Active Choices user selectable params for a job.
my ask is to show/hide textbox when heartbeat_consumer checkbox is selected/unselected. I would also like to store the value of user input in heartbeat_consumer_parms, which can be accessed thru env.heartbeat_consumer_parms. I plan to use this value in downstream jobs.
pipeline {
agent any
stages {
stage('Parameters'){
steps {
script {
properties([
parameters([
text(
defaultValue: '''''',
name: 'application_servers',
description: 'Please provide semicolon delimited (;) application server list ',
),
[$class: 'CascadeChoiceParameter',
choiceType: 'PT_CHECKBOX',
description: 'Select Services',
name: 'application_services_list',
referencedParameters: 'application_servers',
script:
[$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: false,
script: "return['']"
],
script: [
classpath: [],
sandbox: false,
script: '''
if (application_servers.length() > 0){
return["heartbeat_consumer", "surgeon_cloud_login", "system_configuration"]
}
'''
]
]
]
])
])
if (application_services_list.contains('heartbeat_consumer')){
text(
defaultValue: '''''',
name: 'heartbeat_consumer_parms',
description: 'Please provide heartbeatconsumer job parms ',
)
}
}
}
}
}
}
with current implmentation I am not seeing that textbox heartbeat_consumer_parms is being displayed at all.
Pipeline script for your scenario:
properties([
parameters([
[$class: 'ChoiceParameter',
choiceType: 'PT_CHECKBOX',
description: 'Select the Application Service from the Dropdown List',
filterLength: 1,
filterable: false,
name: 'application_services_list',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: false,
script:
"return['Could not get the services list']"
],
script: [
classpath: [],
sandbox: false,
script:
"return['heartbeat_consumer', 'surgeon_cloud_login', 'system_configuration']"
]
]
],
[$class: 'DynamicReferenceParameter',
choiceType: 'ET_FORMATTED_HTML',
description: 'SAdd params',
name: 'heartbeat_consumer_parms',
omitValueField: 'true',
referencedParameters: 'application_services_list',
script:
[$class: 'GroovyScript',
script: 'return["Could not get Information"]',
script: [
script: '''
if (application_services_list.equals("heartbeat_consumer")){
inputBox="<input type ='text' id = 'myText' name='value' >"
return inputBox
}
'''
]
]
]
])
])
pipeline {
environment {
vari = ""
}
agent any
stages {
stage ("Example") {
steps {
script{
echo "${params.application_services_list}"
echo '\n'
echo "${params.heartbeat_consumer_parms}"
}
}
}
}
}
Please find the screenshot of the output:
Output of pipeline after build:
this worked for me,
pipeline {
agent any
stages {
stage('Parameters'){
steps {
script {
properties([
parameters([
text(
defaultValue: '''''',
name: 'application_servers',
description: 'Please provide semicolon delimited (;) application server list ',
),
[$class: 'CascadeChoiceParameter',
choiceType: 'PT_CHECKBOX',
description: 'Select Services',
name: 'application_services_list',
referencedParameters: 'application_servers',
script:
[$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: false,
script: "return['']"
],
script: [
classpath: [],
sandbox: false,
script: '''
if (application_servers.length() > 0){
return["heartbeat_consumer", "surgeon_cloud_login", "system_configuration"]
}
'''
]
]
],
[$class: 'DynamicReferenceParameter',
choiceType: 'ET_FORMATTED_HTML',
description: 'enter job params',
name: 'hb_job_params',
referencedParameters: 'application_services_list',
script:
[$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: false,
script: "return['']"
],
script: [
classpath: [],
sandbox: false,
script: '''
if (application_services_list.contains('heartbeat_consumer')){
return """<textarea name=\"value\" rows=\"5\" class=\"setting-input \"></textarea>"""
}
'''
]
],
omitValueField: true
],
])
])
}
}
}
}
}
I used, DynamicReferenceParameter for using HTML generated textarea however accessing entered textarea values was tricky. after a bit of researching I found that,
The trick for formatting a text input box is to format the HTML in a way that reflects the HTML Jenkins uses to display parameters in a job submission form. The easiest way to do this is to review the HTML Jenkins uses to display an existing String parameter.
src: https://github.com/biouno/uno-choice-plugin/wiki/Using-Uno-Choice-for-Dynamic-Input-Text-Box-Defaults

How to pass variables into Groovy script executed in Jenkins pipeline parameter?

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?
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
"""
]
Yes after changing ''' to """,my issue got resolved.
And also by using ${abc}
Thanks #szymon-stepniak but ${env.JOB_NAME} does not work in ChoiceParameter
Next code works well
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 build = Thread.currentThread().toString()
def regexp= ".+?/job/(.*?)/build "
def match = build =~ regexp
def jobName = match[0][1].replaceAll("/job/", "/") as String
def text = new URL('http://consul.local:8500/v1/kv/${jobName}/test-key?raw').getText()
return text.split(",").sort() as List
"""
]
],
choiceType: "PT_RADIO", //PT_SINGLE_SELECT,PT_MULTI_SELECT,PT_RADIO,PT_CHECKBOX
filterable: true,
filterLength: 1
]
])])
}

Active Choices Reactive Reference Parameter in jenkins pipeline

I'm using the Active Choices Reactive Reference Parameter plugin in a dsl job here the code
parameters {
activeChoiceParam('choice1') {
description('select your choice')
choiceType('RADIO')
groovyScript {
script("return['aaa','bbb']")
fallbackScript('return ["error"]')
}
}
activeChoiceReactiveParam('choice2') {
description('select your choice')
choiceType('RADIO')
groovyScript {
script("if(choice1.equals("aaa")){return ['a', 'b']} else {return ['aaaaaa','fffffff']}")
fallbackScript('return ["error"]')
}
referencedParameter('choice1')
}
and it work's fine what i want now is how to use the activeChoiceReactiveParam in a jenkinsFile for pipeline job i did that :
properties(
[
[
$class : 'ParametersDefinitionProperty',
parameterDefinitions: [
[
$class : 'ChoiceParameterDefinition',
choices : 'aaa\nbbb',
description: 'select your choice : ',
name : 'choice1'
]
but how can i add the choice2 parameter !!!
I was in need of the similar solution.
I did not find any related answers/examples specific to Active Choices plugin anywhere in my google search.
With some R & D, finally I was able to get this done for a pipeline project.
Here is the Jenkinsfile code
properties([
parameters([
[$class: 'ChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
description: 'Select the Env Name from the Dropdown List',
filterLength: 1,
filterable: true,
name: 'Env',
randomName: 'choice-parameter-5631314439613978',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: false,
script:
'return[\'Could not get Env\']'
],
script: [
classpath: [],
sandbox: false,
script:
'return["Dev","QA","Stage","Prod"]'
]
]
],
[$class: 'CascadeChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
description: 'Select the Server from the Dropdown List',
filterLength: 1,
filterable: true,
name: 'Server',
randomName: 'choice-parameter-5631314456178619',
referencedParameters: 'Env',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: false,
script:
'return[\'Could not get Environment from Env Param\']'
],
script: [
classpath: [],
sandbox: false,
script:
''' if (Env.equals("Dev")){
return["devaaa001","devaaa002","devbbb001","devbbb002","devccc001","devccc002"]
}
else if(Env.equals("QA")){
return["qaaaa001","qabbb002","qaccc003"]
}
else if(Env.equals("Stage")){
return["staaa001","stbbb002","stccc003"]
}
else if(Env.equals("Prod")){
return["praaa001","prbbb002","prccc003"]
}
'''
]
]
]
])
])
pipeline {
environment {
vari = ""
}
agent any
stages {
stage ("Example") {
steps {
script{
echo 'Hello'
echo "${params.Env}"
echo "${params.Server}"
if (params.Server.equals("Could not get Environment from Env Param")) {
echo "Must be the first build after Pipeline deployment. Aborting the build"
currentBuild.result = 'ABORTED'
return
}
echo "Crossed param validation"
} }
}
}
}
Even you can use "Active Choices Reactive Reference Parameter" with below definitions and rest of the code, follow as in above example.
[$class: 'DynamicReferenceParameter',
choiceType: 'ET_FORMATTED_HTML',
description: 'These are the details in HTML format',
name: 'DetailsInHTML',
omitValueField: false,
randomName: 'choice-parameter-5633384460832175',
referencedParameters: 'Env, Server',
script: [
$class: 'ScriptlerScript',
parameters: [[$class: 'org.biouno.unochoice.model.ScriptlerScriptParameter', name: '', value: '$value']],
scriptlerScriptId: 'script.groovy'
]
]
Note: Ensure you have "," delimiter between multiple parameter definition blocks.
Hope this helps someone.
Instead of using the Active Choices Reactive Reference Parameter i did below and it's working fine !!!
node('slave') {
def choice1
def choice2
stage ('Select'){
choice1 = input( id: 'userInput', message: 'Select your choice', parameters: [ [\$class: 'ChoiceParameterDefinition', choices: 'aa\nbb', description: '', name: ''] ])
if(choice1.equals("aa")){
choice2 = input( id: 'userInput', message: 'Select your choice', parameters: [ [\$class: 'ChoiceParameterDefinition', choices: 'yy\nww', description: '', name: ''] ])
}else{
choice2 = input( id: 'userInput', message: 'Select your choice', parameters: [ [\$class: 'ChoiceParameterDefinition', choices: 'gg\nkk', description: '', name: ''] ])
}
}
}
Thanks a ton #Yogeesh. It helped a lot.
In my case, the requirement was to select multiple instead of one. So, used choiceType: 'PT_CHECKBOX', and it served the purpose.
properties([
parameters([
[$class: 'ChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
description: 'Select the Env Name from the Dropdown List',
filterLength: 1,
filterable: true,
name: 'Env',
randomName: 'choice-parameter-5631314439613978',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: false,
script:
'return[\'Could not get Env\']'
],
script: [
classpath: [],
sandbox: false,
script:
'return["Dev","QA","Stage","Prod"]'
]
]
],
[$class: 'CascadeChoiceParameter',
choiceType: 'PT_CHECKBOX',
description: 'Select Servers',
filterLength: 1,
filterable: true,
name: 'Server',
randomName: 'choice-parameter-5631314456178619',
referencedParameters: 'Env',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: false,
script:
'return[\'Could not get Environment from Env Param\']'
],
script: [
classpath: [],
sandbox: false,
script:
''' if (Env.equals("Dev")){
return["devaaa001","devaaa002","devbbb001","devbbb002","devccc001","devccc002"]
}
else if(Env.equals("QA")){
return["qaaaa001","qabbb002","qaccc003"]
}
else if(Env.equals("Stage")){
return["staaa001","stbbb002","stccc003"]
}
else if(Env.equals("Prod")){
return["praaa001","prbbb002","prccc003"]
}
'''
]
]
]
])
I made the initial sample work for me.
I had to change ' for " in the return statement return ["a", "b"] and " by ' in the script statement script(' ')
job("MyJob") {
description ("This job creates ....")
//def targetEnvironment=""
parameters {
activeChoiceParam('choice1') {
description('select your choice')
choiceType('RADIO')
groovyScript {
script('return["aaa","bbb"]')
fallbackScript('return ["error"]')
}
}
activeChoiceReactiveParam('choice2') {
description('select your choice')
choiceType('RADIO')
groovyScript {
script(' if(choice1.equals("aaa")) { return ["a", "b"] } else {return ["aaaaaa","fffffff"] } ')
fallbackScript('return ["error"]')
}
referencedParameter('choice1')
}
}
}
Is there any way that we can put the script logic in a function and call
for example:
[$class: 'CascadeChoiceParameter',
choiceType: 'PT_CHECKBOX',
description: 'Select Servers',
filterLength: 1,
filterable: true,
name: 'Server',
randomName: 'choice-parameter-5631314456178619',
referencedParameters: 'Env',
script: [
$class: 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox: false,
script:
'return[\'Could not get Environment from Env Param\']'
],
script: [
classpath: [],
sandbox: false,
script:
''' if (Env.equals("Dev")){
return["devaaa001","devaaa002","devbbb001","devbbb002","devccc001","devccc002"]
}
else if(Env.equals("QA")){
return["qaaaa001","qabbb002","qaccc003"]
}
else if(Env.equals("Stage")){
return["staaa001","stbbb002","stccc003"]
}
else if(Env.equals("Prod")){
return["praaa001","prbbb002","prccc003"]
}
'''
]
]
]```
define below code in funciton and call ?
if (Env.equals("Dev")){
return["devaaa001","devaaa002","devbbb001","devbbb002","devccc001","devccc002"]
}
else if(Env.equals("QA")){ return["qaaaa001","qabbb002","qaccc003"] } else if(Env.equals("Stage")){ return["staaa001","stbbb002","stccc003"] } else if(Env.equals("Prod")){ return["praaa001","prbbb002","prccc003"]
}
Try something like that:
properties(
[
[
$class : 'ParametersDefinitionProperty',
parameterDefinitions: [
[
$class : 'ChoiceParameterDefinition',
choices : 'aaa\nbbb',
description: 'select your choice : ',
name : 'choice1'
],
[
$class : 'ChoiceParameterDefinition',
choices : 'ccc\nddd',
description: 'select another choice : ',
name : 'choice2'
]

Resources