Jenkins: How to use choice parameter in declarative pipeline? - jenkins-pipeline

My example:
pipeline {
agent any
parameters {
choice(
name: 'myParameter',
choices: "Option1\Option2",
description: 'interesting stuff' )
}
}
outputs with error:
" unexpected char: '\' " on the line with "choices" "
Following these instructions: https://github.com/jenkinsci/pipeline-model-definition-plugin/wiki/Parametrized-pipelines
Any idea or advice on what I do wrong?

The documentation for declarative jenkins pipelines says:
A choice parameter, for example:
pipeline {
.....
parameters {
choice(name: 'CHOICES', choices: ['one', 'two', 'three'], description: '') }
First one is the default value

You need to use \n instead of \.
See this code:
pipeline {
agent any
parameters {
choice(
name: 'myParameter',
choices: "Option1\nOption2",
description: 'interesting stuff' )
}
}

The arguably most elegant way to separate choices is by using an array like so:
pipeline {
agent any
parameters {
choice(
name: 'Env',
choices: ['DEV', 'QA', 'UAT', 'PROD'],
description: 'Passing the Environment'
)
}
stages {
stage('Environment') {
steps {
echo " The environment is ${params.Env}"
}
}
}
}

Related

Using Function in JenkinsFile Parameter Description

I am trying to add a function in JenkinsFile Declarative pipelines parameter's description but struggling to make it work.
Idea is to have a Jenkins Job specific for the environment. and would like to see the choice parameter to show environment name in the description of the variable.
My pipeline looks like this
def check_env = app_env(ENVS, env.JOB_NAME)
pipeline {
agent { label 'master' }
options {
disableConcurrentBuilds()
buildDiscarder(logRotator(numToKeepStr: '20'))
timestamps()
}
parameters{
string(name: 'myVariable', defaultValue: "/", description: 'Enter Path To App e.g / OR /dummy_path for ' {check_env} )
}
stages{
stage('Running App') {
agent {
docker {
image 'myApp:latest'
}
}
steps{
script{
sh label: 'App', script: "echo "App is running in ${check_env} "
}
}
}
}
}
}
I have tried multiple combinations for check_env e.g check_env, check_env(), ${check_env} function but none of them worked.
String Interpolation
I believe this is simply a String Interpolation issue. Notice my use of double quotes below
parameters{
string(name: 'myVariable', defaultValue: "/", description: "Enter Path To App e.g / OR /dummy_path for ${check_env}")
}
Your build page should then interpolate your variable
To test I simply set def check_env = 'live' since I do not have the code for your method

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

For loop in Jenkins Pipeline

I stuck with for loop condition in Pipeline
pipeline {
agent any
stages{
stage ('Showing Working Space') {
when {
anyOf {
environment name: 'Test', value: 'ALL'
environment name: 'Test', value: 'IMAGE'
}
}
steps {
sh "echo Display ${Var1}"
script{
sh 'for service in (echo "$Var1"|sed "s/,/ /g");do echo $service; done'
}
}
}
}
}
Getting error like " syntax error near unexpected token `('"
Var1 = has multiple values
Need to execute the "For loop" to pass the values to another script
Please help on this
I believe what you want is
pipeline {
agent any
stages {
stage('Showing Working Space') {
when {
anyOf {
environment name: 'Test', value: 'ALL'
environment name: 'Test', value: 'IMAGE'
}
}
steps {
sh "echo Display ${Var1}"
script {
sh 'for service in $(echo "$Var1"|sed "s/,/ /g"); do echo $service; done'
}
}
}
}
}
In essence, replace service in (echo with service in $(echo (note the $).

environmentDashboard-Jenkinsfile

I have installed the following plugin in Jenkins environmentDashboard(https://plugins.jenkins.io/environment-dashboard/)
Need to incorporate the feature in Jenkinsfile, Sample Jenkinsfile
pipeline {
agent any
parameters {
string(name: "branch_name", defaultValue: "master", description: "Enter the branch name")
string(name: "project_name", defaultValue: "TestAutomation" , description:"BuildWorkspace")
choice(name: "mach_name", choices: ["LINUX" , "WINDOWS"], description: "OS Selection")
string(name: "build_suffix", defaultValue:"", description: "Provide a build suffix name")
}
environment{
TARBALL_PATH = ""
}
Wrappers{
environmentDashboard {
environmentName('Testing')
componentName('GCC_COMPILER')
buildNumber({BUILD_ID})
buildJob({JOB_NAME})
packageName('TARBALL')
addColumns(true)
columns('RESULT', 'PASS')
}
}
stages {
stage('TARBALL GENERATION') {
steps {
script{
buildName "${mach_name}#${BUILD_NUMBER}"
buildDescription "${mach_name} Test Execution on ${NODE_NAME}"
}
echo "Branch name is ${params.branch_name}"
echo "Preferred MACH: ${params.mach_name}"
echo "Reached Here after printing selected parameters"
sh """
#!/bin/bash
echo "Multiline shell steps execution"
printenv | sort
"""
} //steps
} //stage
}//Stages
}//pipeline
Getting the error as follows:
Running in Durability level: MAX_SURVIVABILITY
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 13: Undefined section "Wrappers" # line 13, column 5.
Wrappers{
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.doParse(CpsGroovyShell.java:142)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:127)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:561)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:522)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:327)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:427)
Finished: FAILURE
You need to write wrappers in lowercase.
Like wrappers{}
Not Wrappers{}
For pipeline job you need to use the following code:
environmentDashboard(addColumns: false, buildJob: '', buildNumber: 'Version-1', componentName: 'WebApp-1', data: [], nameOfEnv: 'Environment-1', packageName: '') {
// some block
}
In fact, you can skip // some block and just use {}. That worked for me.

How to skip a stage in Jenkinsfile pipeline when pipeline name ends with deliver?

I have 2 pipelines one for review and one for deploy. So when the pipeline ends with review, I want to skip Jenkinsfile execution. However, when it ends with deploy, it should execute the stage or the Jenkinsfile.
I tried to use if, but this is a declarative pipeline, so when should be used. I want to avoid execution of stage using when condition if I encounter deploy pipeline end.
#!/usr/bin/env groovy
final boolean Deploy = (env.JOB_NAME as String).endsWith("-deploy")
pipeline {
agent any
parameters {
choice(
choices: ['greeting' , 'silence'],
description: '',
name: 'REQUESTED_ACTION')
}
stages {
//how to ouse when here to use deploy vairable to avoide execution of stage below
stage ('Speak') {
steps {
echo "Hello, bitwiseman!"
}
}
}
}
You can skip stages in declarative pipelines using when, so the following should work.
stages {
stage('Deploy') {
when { equals expected: true, actual: Deploy }
steps {
// ...
}
}
}
An alternative to #StephenKing’s answer, which is also correct, you can rewrite the when block when evaluating Booleans as follows:
stages {
stage('Deploy') {
when {
expression {
return Deploy
}
}
steps {
echo "Hello, bitwiseman!" // Step executes only when Deploy is true
}
}
}
This will execute the stage Deploy only when the variable Deploy evaluates to true, else the stage will be skipped.
I've got quite a hard time to find it too, but finally:
stage('Speak') {
when {
expression { params.REQUESTED_ACTION != 'SILENCE' }
}
steps {
echo "Hello, bitwiseman!"
}
}
Jenkins docs with examples here: https://jenkins.io/doc/book/pipeline/syntax/#when-example
Here is an example for a Jenkins scripted pipeline:
stage('Input of Scratch instance and Access token') {
timeout(time: 60, unit: 'SECONDS') {
script {
try {
env.SCRATCH_INSTANCE_URL = input message: 'Please enter the SCRATCH_INSTANCE_URL',
parameters: [string(defaultValue: '',
description: '',
name: 'SCRATCH_INSTANCE_URL')]
env.SCRATCH_ACCESS_TOKEN = input message: 'Please enter the SCRATCH_ACCESS_TOKEN',
parameters: [string(defaultValue: '',
description: '',
name: 'SCRATCH_ACCESS_TOKEN')]
} catch (Throwable e) {
echo "Caught ${e.toString()}"
currentBuild.result = "SUCCESS"
}
}
}
}
// -------------------------------------------------------------------------
// Logout from Dev Hub.
// -------------------------------------------------------------------------
stage('Logout from DevHub') {
if (env.SCRATCH_INSTANCE_URL == null) {
rc = command '''export SFDX_USE_GENERIC_UNIX_KEYCHAIN=true
sfdx force:auth:logout --targetusername ${DEV_HUB_USERNAME} -p
echo ${SCRATCH_INSTANCE_URL}
echo ${SCRATCH_ACCESS_TOKEN}
'''
} else {
echo "Skipping this stage"
}
}
Even you can skip some parts of the steps using below code. Let's say REQUIRED_UPLOAD_INSTALL is a parameter.
stage('Checking Mail List') {
steps {
script {
if(!(env.REQUIRED_UPLOAD_INSTALL.toBoolean())) {
env.mail_list = 'test#testg.com'
}
}
}
}
But it doesn't support in post steps, not even in the when syntax.

Resources