Change the parameter values in a Jenkins Pipeline - 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]
}
}
}
}

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

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.

exit declarative pipeline prematurely based on script output

While I am aware of this question clean way to exit declarative Jenkins pipeline as success I am to green to understand how to put it to use (from where does the skipBuild variable come?).
I have a script that determines whether the pipeline should continue or not but I am unsure how to piece it together (I am free to construct the script as needed).
pipeline {
agent {
docker { image 'python:3-alpine' }
}
stage('Should I continue') {
steps {
python should_i_continue.py
}
when { ? == true }
stages {
...
}
}
}
I am aware that the capabilities increase tenfold if I use a scripted pipeline but I wonder if it is possible to do what I want with a declarative one?
You can use any custom variable, which you will set as true|false based on some condition in the steps of your pipeline and all stages that need to be executed based on that condition have to have following format:
stage('Should Continue?') {
setBuildStatus("Build complete", "SUCCESS");
when {
expression {skipBuild == true }
}
}
In other words to provide you a bit clean picture, check this abstract example:
node {
skipBuild = false
stage('Checkout') {
...
your checkout code here
...
}
stage('Build something') {
...
some code goes here
skipBuild = true
...
}
stage('Should Continue?') {
setBuildStatus("Build complete", "SUCCESS");
when {
expression {skipBuild == true }
}
}
}

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