Jenkins declarative pipeline - User input parameters - jenkins-pipeline

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.

Related

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

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".

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 trigger a multiple run in a single pipeline job of jenkins?

I have a pipeline job which run with below pipeline groovy script,
pipeline {
parameters{
string(name: 'Unique_Number', defaultValue: '', description: 'Enter Unique Number')
}
stages {
stage('Build') {
agent { node { label 'Build' } }
steps {
script {
sh build.sh
}
}
stage('Deploy') {
agent { node { label 'Deploy' } }
steps {
script {
sh deploy.sh
}
}
stage('Test') {
agent { node { label 'Test' } }
steps {
script {
sh test.sh
}
}
}
}
I just trigger this job multiple times with different unique ID number as input parameter. So as a result i will have multiple run/build for this job at different stages.
With this, i need to trigger a multiple run/build to be promote to next stage (i.e., from build to deploy or from deploy to test) in this pipeline job as a one single build instead of triggering each and every single run/build to next stage. Is there any possibility?
I was also trying to do the same thing and found no relevant answers. May this help to someone.
This will read a file that contains the Jenkins Job name and run them iteratively from one single job.
Please change below code accordingly in your Jenkins.
pipeline {
agent any
stages {
stage('Hello') {
steps {
script{
git branch: 'Your Branch name', credentialsId: 'Your crendiatails', url: ' Your BitBucket Repo URL '
##To read file from workspace which will contain the Jenkins Job Name ###
def filePath = readFile "${WORKSPACE}/ Your File Location"
##To read file line by line ###
def lines = filePath.readLines()
##To iterate and run Jenkins Jobs one by one ####
for (line in lines) {
build(job: "$line/branchName",
parameters:
[string(name: 'vertical', value: "${params.vertical}"),
string(name: 'environment', value: "${params.environment}"),
string(name: 'branch', value: "${params.aerdevops_branch}"),
string(name: 'project', value: "${params.host_project}")
]
)
}
}
}
}
}
}
You can start multiple jobs from one pipeline if you run something as:
build job:"One", wait: false
build job:"Two", wait: false
Your main job starts children pipelines and children pipelines will run in parallel.
You can read PipeLine Build Step documentation for more information.
Also, you can read about the parallel run in declarative pipeline
Here you can find a lot of examples for parallel running

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}"
}
}
}

Resources