Dynamically update values in input parameter boxes in Jenkins pipeline based on user choice - jenkins-pipeline

My Jenkins pipeline script has two presets of parameter values.
I want to create a drop-down list on the job page that would fill in default values of these parameters, while allowing users to edit them.
I've tried many variants of calls to functions of the ActiveChoices plugin but still haven't succeeded.
I have also read many similar questions here and in the Internet and have tried recipes provided in them, nothing helps.
Here is the pipeline I've got now.
properties([
parameters([
choice(
choices: ['D4', 'D5'],
description: 'Reference preset',
name: 'reference_preset'
),
[
$class: 'DynamicReferenceParameter',
choiceType: 'ET_TEXT_BOX',
description: 'Path to dataset for processing',
name: 'image_source_path',
referencedParameters: 'reference_preset',
script: [
$class: 'GroovyScript',
fallbackScript: [ classpath: [], sandbox: false, script: '' ],
script: [
classpath: [],
sandbox: false,
script: """
if (reference_preset.equals("D4")) {
return 'D:\\data\\D4\\images'
} else if (reference_camera.equals("D5")) {
return 'D:\\data\\D5\\images'
} else {
return 'unknown'
}
"""
]
]
]
])
])
pipeline {
options {
ansiColor('xterm')
}
stages {
stage('Build') {
steps {
echo "${params.image_source_path}"
}
}
}
}
Screenshot of the result:
image_source_path does not contain D:\\data\\D4\\images, and is not editable.
When I switch Reference preset from D4 to D5, its value doesn't change.
My goal is to provide editable input box having default value, based on selection from the "Reference preset".

Related

Change the parameter values in a Jenkins Pipeline

How to map the parameter values to a different value and then execute it inside the pipeline.
parameters {
choice(name: 'SIMULATION_ID',
choices: 'GatlingDemoblaze\nFrontlineSampleBasic\nGatlingDemoStoreNormalLoadTest',
description: 'Simulations')
}
How to map the value of 'GatlingDemoblaze' to '438740439023874' so that the it will be the latter which goes inside the ${params.SIMULATION_ID}? Can we do this with a simple groovy code?
gatlingFrontLineLauncherStep credentialId: '', simulationId:"${params.SIMULATION_ID}"
Thanks for the help.
As suggested in the comments the best approach will be to use the Extensible Choice Parameter Plugin and define the needed key-value pairs, however if you don't want to use the plugin you can create the mapping using groovy in the pipeline script and use it.
For that you have several options:
If you need it for a single stage you can define the map inside a script block and use it in that stage:
pipeline {
agent any
parameters {
choice(name: 'SIMULATION_ID', description: 'Simulations',
choices: ['GatlingDemoblaze', 'FrontlineSampleBasic', 'GatlingDemoStoreNormalLoadTest'])
}
stages {
stage('Build') {
steps {
script {
def mappings = ['GatlingDemoblaze': '111', 'FrontlineSampleBasic': '222', 'GatlingDemoStoreNormalLoadTest': '333']
gatlingFrontLineLauncherStep credentialId: '', simulationId: mappings[params.SIMULATION_ID]
}
}
}
}
}
You can also define it as a global parameter that will be available in all stages (and then you don't need the script directive):
mappings = ['GatlingDemoblaze': '111', 'FrontlineSampleBasic': '222', 'GatlingDemoStoreNormalLoadTest': '333']
pipeline {
agent any
parameters {
choice(name: 'SIMULATION_ID', description: 'Simulations',
choices: ['GatlingDemoblaze', 'FrontlineSampleBasic', 'GatlingDemoStoreNormalLoadTest'])
}
stages {
stage('Build') {
steps {
gatlingFrontLineLauncherStep credentialId: '', simulationId: mappings[params.SIMULATION_ID]
}
}
}
}
and another options is to set these values in the environment directive:
pipeline {
agent any
parameters {
choice(name: 'SIMULATION_ID', description: 'Simulations',
choices: ['GatlingDemoblaze', 'FrontlineSampleBasic', 'GatlingDemoStoreNormalLoadTest'])
}
environment{
GatlingDemoblaze = '111'
FrontlineSampleBasic = '222'
GatlingDemoStoreNormalLoadTest = '333'
}
stages {
stage('Build') {
steps {
gatlingFrontLineLauncherStep credentialId: '', simulationId: env[params.SIMULATION_ID]
}
}
}
}

how to create loop inside jenkinsfile

i have created a jenkinsfile
inside i have created a text parameter with 10 server names.
i want to create a loop within a stage to echo each server name.
// ######################################################################### PROPERTIES ###########################################################################
properties([
parameters([
text(defaultValue: '', description: 'EXAMPLE: lsch3-123', name: 'SERVERS')])])
// ######################################################################### START PIPELINE ###########################################################################
pipeline {
agent none
options {
skipDefaultCheckout true
}
stages {
stage('GIT & PREP') {
agent {label "${params.DC}-ansible01"}
steps {
cleanWs()
run loop here
}
}
}
}
Please see below code/reference example which will loop within the stage.
// Define list which would contain all servers in an array. Initialising it as empty
def SERVERS = []
pipeline {
agent none
options {
skipDefaultCheckout true
}
parameters
{
// Adding below as example string which is passed from paramters . this can be changed based on your need
// Example: Pass server list as ; separated string in your project. This can be changed
string(name: 'SERVERS', defaultValue:'server1;server2', description: 'Enter ; separated SERVERS in your project e.g. server1;server2')
}
stages {
stage('GIT & PREP') {
agent {label "${params.DC}-ansible01"}
steps {
cleanWs()
// run loop here under script
script
{
// Update SERVERS list.Fill SERVERS list with server names by splitting the string.
SERVERS = params.SERVERS.split(";")
// Run loop below : execute below part for each server listed in SERVERS list
for (server in SERVERS)
{
println ("server is : ${server}")
}
}
}
}
}
}
Regards.

Jenkins scripted pipeline

write a simple Jenkins scripted pipeline.
it should have 2 parameters(one checkbox, one textbox).
include 2 stages in the pipeline, the first stage will be called based on whether the checkbox is check or not.
A more targeted question I think would provide more benefit. However to directly answer your request:
#!groovy
properties([
buildDiscarder(logRotator(numToKeepStr: '20')),
parameters([
booleanParam(name: 'CHECKBOX', defaultValue: true, description: 'Tick a checkbox'),
string(name: 'STRING', defaultValue: 'stringhere', description: 'Enter a string'),
])
])
node {
try {
if (params.CHECKBOX) {
stage('Stage 1') {
//do something conditionally
echo("${params.CHECKBOX}")
}
}
stage('Stage 2') {
// do someting else always
echo(params.STRING)
}
}
catch (err) {
// catch an error and do something else
throw err
}
finally {
// Finish with final mandatory tasks regardless of success/failure
deleteDir()
}
}
This starts off with Jenkins pipeline parameter syntax: https://jenkins.io/doc/book/pipeline/syntax/#parameters
and using some basic pipeline steps: https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/ such as echo and shell
interspersed with standard groovy for your conditional logic.

How to ask user input only when branch matches master in Jenkinsfile pipeline?

I tried to use the following Jenkinsfile to ask input only on master branch and can't get the groovy grammer pass validation:
pipeline {
stage('Deploy') {
when {
branch 'master'
}
steps {
input(message: "Please input", parameters: [string(name: "VERSION", defaultValue="", description="")]
}
}
}
The error is:
java.lang.IllegalArgumentException: Expected named arguments but got [{name=VERSION, description=""}, null]
I searched a lot but didn't find a single one example about using input step in the Jenkinsfile with parameters.
Can anyone shed some light on this? Thanks in advance!
Finally find a way to do this, we should wrap the input with the script keyword.
stage('Deploy to k8s prod') {
when {
branch 'release-prod'
}
steps {
script {
env.VERSION = input message: '请输入参数', ok: '确定', parameters: [
string(name:'VERSION', description: "版本号")]
}
sh "echo ${env.VERSION}"
}
}
}

Jenkins declarative pipeline - User input parameters

I've looked for some example of user input parameters using Jenkins declarative pipeline, however all the examples are using the scripted pipelines. Here is a sample of code I'm trying to get working:
pipeline {
agent any
stages {
stage('Stage 1') {
steps {
input id: 'test', message: 'Hello', parameters: [string(defaultValue: '', description: '', name: 'myparam')]
sh "echo ${env}"
}
}
}
}
I can't seem to work out how I can access the myparam variable, it would be great if someone could help me out.
Thanks
When using input, it is very important to use agent none on the global pipeline level, and assign agents to individual stages. Put the input procedures in a separate stage that also uses agent none. If you allocate an agent node for the input stage, that agent executor will remain reserved by this build until a user continues or aborts the build process.
This example should help with using the Input:
def approvalMap // collect data from approval step
pipeline {
agent none
stages {
stage('Stage 1') {
agent none
steps {
timeout(60) { // timeout waiting for input after 60 minutes
script {
// capture the approval details in approvalMap.
approvalMap = input
id: 'test',
message: 'Hello',
ok: 'Proceed?',
parameters: [
choice(
choices: 'apple\npear\norange',
description: 'Select a fruit for this build',
name: 'FRUIT'
),
string(
defaultValue: '',
description: '',
name: 'myparam'
)
],
submitter: 'user1,user2,group1',
submitterParameter: 'APPROVER'
}
}
}
}
stage('Stage 2') {
agent any
steps {
// print the details gathered from the approval
echo "This build was approved by: ${approvalMap['APPROVER']}"
echo "This build is brought to you today by the fruit: ${approvalMap['FRUIT']}"
echo "This is myparam: ${approvalMap['myparam']}"
}
}
}
}
When the input function returns, if it only has a single parameter to return, it returns that value directly. If there are multiple parameters in the input, it returns a map (hash, dictionary), of the values. To capture this value we have to drop to groovy scripting.
It is good practice to wrap your input code in a timeout step so that build don't remain in an unresolved state for an extended time.

Resources