Loop through multi selection value of Jekins Parameter BooleanParam - jenkins

I have on-premise Jenkins node slave that are running. The value of each param is the nodename. For example the nodename I have is (value1,value2,value3)
Suppose a user select a value1 and value2 in the parameter options in the checkbox, I want to be able to loop the selected params and pass the value to the node($selected).
That means Jenkins will connect to value1 and value2 node. Any Idea how to do this?
The code is here:
#!/usr/bin/env groovy
properties([
parameters([
booleanParam(name: 'value1', defaultValue: false, description: '') ,
booleanParam(name: 'value2', defaultValue: false, description: '') ,
booleanParam(name: 'value3', defaultValue: false, description: '')
])
])
stage('stash'){
Loop here //
node('$selected'){
}
}

Do you want to do something like the below?
node {
properties([
parameters([
booleanParam(name: 'value1', defaultValue: false, description: '') ,
booleanParam(name: 'value2', defaultValue: false, description: '') ,
booleanParam(name: 'value3', defaultValue: false, description: '')
])
])
stage('Stash') {
def list = []
if("$value1" == "true") {
list.add("value1")
}
if("$value2" == "true") {
list.add("value2")
}
if("$value3" == "true") {
list.add("value3")
}
list.each { node ->
echo "$node"
node('$node'){}
}
}
}

Related

Jenkins pipeline, groovy map array as choises

How can I pass the array variable into the global variable in groovy?
It works perfectly without if-else.
choiceArray = []
if (appName == 'ms'){
['78', '99', '10'].each {
"${choiceArray}" << it
}
}
else if (appName == 'ms2'){
['12', '34', '56'].each {
"${choiceArray}" << it
}
}
pipeline {
parameters {
string (name: 'Branch', defaultValue: 'master', description: 'Select Branch')
choice(name: 'Environment', choices: choiceArray, description: 'Choose Environment')
if(...){
choiceArray.addAll(['78', '99', '10'])
}

Jenkins declarative pipeline: if-else statement inside parameters directive

I'm trying to display a choice parameter if I have options to choose from, or else display an input text, something like this (which does not work):
pipeline {
agent any
parameters {
if (someOptions) {
choice(name: 'FIELD_NAME', choices: "$someOptions", description: 'Field description')
} else {
string(name: 'FIELD_NAME', defaultValue: '', description: 'Field description')
}
}
environment {
// environment params
}
stages {
// stages
}
}
Is there a way of doing this?
To expand on #Matt Schuchard's comment, here's what this might look like:
def my_param = []
if (someOptions) {
my_param = [$class: 'ChoiceParameter',
name: 'FIELD_NAME',
choiceType: 'PT_SINGLE_SELECT',
description: 'Choose the desired option',
script:
[$class: 'GroovyScript',
fallbackScript:
[classpath: [], sandbox: false, script: 'return ""'],
script:
[classpath: [], sandbox: false, script: "return $someOptions"]
]
]
} else {
my_param = [$class: 'StringParameterDefinition',
name: 'FIELD_NAME',
defaultValue: false,
description: '']
}
properties([
parameters([my_param,
// other parameters
Don't forget to approve Groovy scripts in script approval console.

How to pass parameter value to stage build in Jenkins pipeline?

I have a pipeline created which takes the parameter value from the user. I want to trigger a jenkin job using this parameter.
How can I pass the parameter value to the build's parameter.
Here is my code:
pipeline {
agent any
parameters {
string(name: 'SYSTEM', defaultValue: '', description: 'Enter array. Example:SYS-123')
string(name: 'EMail', defaultValue: '', description: 'Enter email id')
}
stages {
stage('Example') {
steps {
echo "Hello ${params.SYSTEM}"
echo "Hello ${params.EMail}"
}
}
stage('core-rest-api-sanity') {
steps {
build job: 'xyz', parameters: [string(name: 'E-Mail', value: ${params.EMail}), string(name: 'SYSTEM', value: ${params.SYSTEM})]
}
}
}
}
In the above code, I am taking email and system details from the user. Then I want to trigger my job "xyz" which would require these parameter.
pipeline {
agent any
parameters {
string(name: 'SYSTEM', defaultValue: '', description: 'Enter array. Example:SYS-123')
string(name: 'EMail', defaultValue: '', description: 'Enter email id')
}
stages {
stage('Example') {
steps {
echo "Hello ${params.SYSTEM}"
echo "Hello ${params.EMail}"
}
}
stage('core-rest-api-sanity') {
steps {
build job: 'xyz', parameters: [string(name: 'E-Mail', value: params.EMail),
string(name: 'SYSTEM', value: params.SYSTEM)]
}
}
}
}

Extended Choice Parameter implementation

I'm setting up a new job in which we are required to select Multiple values. Need to select Service1 and Service2...
Went through link How to pass multi select value parameter in Jenkins file(Groovy)
However, I am not sure how to pass values in my Jenkinsfile
A snippet of Jenkinsfile
stage('parallel'){
parallel(
"service1": {stage('service1-deployment') {
if (params.ServiceName == 'Service1' || params.ServiceName == 'ALL'){
b = build(job: 'job name', parameters: [string(name: 'ENVIRONMENT', value: TARGET_ENVIRONMENT),string(name: 'IMAGE_TAG', value: value)], propagate: false).result
if(b=='FAILURE'){
echo "job failed"
currentBuild.result = 'UNSTABLE'
}
}
}
},
"service2": {stage('service2t') {
if (params.ServiceName == 'service2' || params.ServiceName == 'ALL'){
b = build(job: 'Job name', parameters: [string(name: 'ENVIRONMENT', value: TARGET_ENVIRONMENT),string(name: 'IMAGE_TAG', value: value)], propagate: false).result
if(b=='FAILURE'){
echo "job failed"
currentBuild.result = 'UNSTABLE'
}
}
}
},
I see that you're using declarative pipeline syntax for your job.
So, if the accepted answer for that question with booleanParam is useful for you, then you can use it inside parameters section (see the official documentation for more details):
pipeline {
agent any
parameters {
booleanParam(defaultValue: false, name: 'ALL', description: 'Process all'),
booleanParam(defaultValue: false, name: 'OPTION_1', description: 'Process option 1'),
booleanParam(defaultValue: false, name: 'OPTION_2', description: 'Process options 2'),
}
stages {
stage('Example') {
steps {
echo "All: ${params.ALL}"
echo "Option 1: ${params.OPTION_1}"
echo "Option 2: ${params.OPTION_2}"
}
}
}
}
However, if you want to use extended choice parameter with multiselect input, you need to use scripted pipeline syntax, see this example (already mentioned here).

How to run same job with different parameters in parallel using parallel[:] step

I have a pipeline script that needs to trigger a "TEST" job.
The main parameter (string) is SETUP_DESCRIPTION which I phrase from a json file I'm creating.
Each server can have different amount of outputs depends on server resources (some have 2 setups and some 3).
Code looks like this:
#!/usr/bin/env groovy
import hudson.model.Result
import hudson.model.Run
import groovy.json.JsonSlurperClassic
import jenkins.model.CauseOfInterruption.UserInterruption
import org.jenkinsci.plugins.workflow.steps.FlowInterruptedException
def projectProperties = [
buildDiscarder(
logRotator(artifactDaysToKeepStr: '', artifactNumToKeepStr: '', daysToKeepStr: '14', numToKeepStr: '')
),
parameters([
string(defaultValue: '', description: '', name: 'SERVER_NAME'),
string(defaultValue: 'Ubuntu_17.10_x86_64_kvm', description: '', name: 'KVM_TEMPLATE'),
string(defaultValue: 'test#test.com'', description: 'mailing list', name: 'SW_MAIL'),
choice(choices: ['no', 'eth', 'ib'], description: '', name: 'SIMX_SERVER'),
choice(choices: ['cib', 'cx3pro', 'cx4', 'cx4lx', 'cx5', 'cx6'], description: '', name: 'SIMX_BOARD'),
choice(choices: ['os_install', 'provision', 'add_jks_slave', 'add_to_noga', 'tests'], description: '', name: 'RUN_STAGE')
]),
[$class: 'RebuildSettings', autoRebuild: false, rebuildDisabled: false],
[$class: 'ThrottleJobProperty',
categories: [],
limitOneJobWithMatchingParams: true,
maxConcurrentPerNode: 5,
maxConcurrentTotal: 5,
paramsToUseForLimit: '',
throttleEnabled: true,
throttleOption: 'project'
],
]
properties(projectProperties)
def build_sanity (SETUP_DESCRIPTION) {
IMAGE = "linux/upstream_devel-x86_64"
CLOUD_IP = "dev-l-vrt-storage"
TAGS = "test_new_setup"
if ("$SETUP_DESCRIPTION" != "b2b x86-64 cib cloud_test") {
DATA_BASE = "b2b_eth_drivertest_mini_reg_db.json"
LINK_LAYER = "eth"
}
else {
DATA_BASE = "b2b_ib_drivertest_mini_reg_db.json"
LINK_LAYER = "ib"
}
build job: 'SANITY_TESTS/new_cloud_setup_GENERAL_SANITY_CHECK2', propagate: false
parameters:
[string(name: 'SETUP_DESCRIPTION', value: "${SETUP_DESCRIPTION}"),
string(name: 'DATA_BASE', value: "${DATA_BASE}"),
string(name: 'LINK_LAYER', value: "${LINK_LAYER}"),
string(name: 'IMAGE', value: "${IMAGE}"),
string(name: 'CLOUD_IP', value: "${CLOUD_IP}"),
string(name: 'TAGS', value: "${TAGS}")]
}
try {
ansiColor('xterm') {
timestamps {
node('cloud-slave1'){
stage('Test Setups') {
if (params.RUN_STAGE == 'os_install' || params.RUN_STAGE == 'provision' || params.RUN_STAGE == 'add_jks_slave' || params.RUN_STAGE == 'add_to_noga' || params.RUN_STAGE == 'tests') {
def stepsForParrallel = [:]
def NOGA_DESCRIPTION_LIST = sh (
script: "curl -X GET 'https://noga.mellanox.com/app/server/php/rest_api/?api_cmd=get_resources&pattern=${params.SERVER_NAME}&resource_type=Setup&group_name=Yaron&sub_group=Cloud'",
returnStdout: true
).trim()
#NonCPS
def JSON = new groovy.json.JsonSlurperClassic().parseText(NOGA_DESCRIPTION_LIST)
def DESCRIPTION_LIST = JSON.data.each{
SETUP_NAME = "${it.NAME}"
SETUP_DESCRIPTION = "${it.DESCRIPTION}"
println "${it.DESCRIPTION}" // PRINT ALL DECRIPTIONS INSIDE DATA
stepsForParrallel["${it.NAME}"] = {
build_sanity(SETUP_DESCRIPTION)
}
}
parallel stepsForParrallel
}
}
}
}
}
}catch (exc) {
def recipient = "${SW_MAIL}"
def subject = "${env.JOB_NAME} (${env.BUILD_NUMBER}) Failed"
def body = """
It appears that build ${env.BUILD_NUMBER} is failing, please check HW or network stability:
${env.BUILD_URL}
"""
mail subject: subject,
to: recipient,
replyTo: recipient,
from: 'cloud-host-provision#mellanox.com',
body: body
throw exc
1) When I run it like code above build_sanity function called once and execute (instead of 3 times as expected).
2) When I take build_sanity function content and run it inside the ech loop in the tests stage it runs 3 times as expected but not choosing different parameters as expected.
so i managed to figure it out.
1) i have println some parameters and saw my function did not received the variables ok
so i have changed the build job: part and that fixed that issue.
2) i also had issue in the stage part. i put the "run parallel" inside the each loop which cause it to ran several times. so i drop it one } down and that fixed the loop issue
here is the function code + stage if anyone encounter such issue in the future
def build_sanity (SETUP_DESCRIPTION) {
if ("$SETUP_DESCRIPTION" != "b2b x86-64 cib cloud_test") {
DATA_BASE = "b2b_eth_drivertest_mini_reg_db.json"
LINK_LAYER = "eth"
}
else {
DATA_BASE = "b2b_ib_drivertest_mini_reg_db.json"
LINK_LAYER = "ib"
}
IMAGE = "linux/upstream_devel-x86_64"
CLOUD_IP = "dev-l-vrt-storage"
TAGS = "test_new_setup"
build job: 'SANITY_TESTS/new_cloud_setup_GENERAL_SANITY_CHECK',
parameters: [
string(name: 'SETUP_DESCRIPTION', value: "${SETUP_DESCRIPTION}"),
string(name: 'DATA_BASE', value: "${DATA_BASE}"),
string(name: 'LINK_LAYER', value: "${LINK_LAYER}"),
string(name: 'IMAGE', value: "${IMAGE}"),
string(name: 'TAGS', value: "${TAGS}"),
]
}
stage('Test Setups') {
if (params.RUN_STAGE == 'os_install' || params.RUN_STAGE == 'provision' || params.RUN_STAGE == 'add_jks_slave' || params.RUN_STAGE == 'add_to_noga' || params.RUN_STAGE == 'tests') {
def stepsForParrallel = [:]
def NOGA_DESCRIPTION_LIST = sh (
script: "curl -X GET 'https://noga.mellanox.com/app/server/php/rest_api/?api_cmd=get_resources&pattern=${params.SERVER_NAME}&resource_type=Setup&group_name=Yaron&sub_group=Cloud'",
returnStdout: true
).trim()
#NonCPS
def JSON = new groovy.json.JsonSlurperClassic().parseText(NOGA_DESCRIPTION_LIST)
def DESCRIPTION_LIST = JSON.data.each{
def SETUP_NAME = "${it.NAME}"
stepsForParrallel["${it.NAME}"] = {
build_sanity("${it.DESCRIPTION}")
}
}
parallel stepsForParrallel
}
}

Resources