Jenkins pipeline input script with one prompt only - jenkins

Don't need 2 prompt in Jenkins pipeline with input script. In snippet, there is highlighted 1 and 2 where pipeline prompt 2 times for user input.
If execute this pipeline, prompt 1 will provide user to "Input requested" only, so no option to "Abort". Prompt 2 is okay as it ask to input the value and also "Abort" option.
Prompt 1 is almost useless, can we skip promt this and directly reach to prompt 2?
pipeline {
agent any
parameters {
string(defaultValue: '', description: 'Enter the Numerator', name: 'Num')
string(defaultValue: '', description: 'Enter the Denominator', name: 'Den')
}
stages {
stage("foo") {
steps {
script {
if ( "$Den".toInteger() == 0) {
echo "Denominator can't be '0', please re-enter it."
env.Den = input message: 'User input required', ok: 'Re-enter', // 1-> It will ask whether to input or not
parameters: [string(defaultValue: "", description: 'Enter the Denominator', name: 'Den')] // 2-> It will ask to input the value
}
}
sh'''#!/bin/bash +x
echo "Numerator: $Num\nDenominator: $Den"
echo "Output: $((Num/Den))"
'''
}
}
}
}

Yes, you can simplify the input by using $class: 'TextParameterDefinition'.
e.g.
pipeline {
agent any
parameters {
string(defaultValue: '', description: 'Enter the Numerator', name: 'Num')
string(defaultValue: '', description: 'Enter the Denominator', name: 'Den')
}
stages {
stage("foo") {
steps {
script {
if ( "$Den".toInteger() == 0) {
env.Den = input(
id: 'userInput', message: 'Wrong denominator, give it another try?', parameters: [
[$class: 'TextParameterDefinition', defaultValue: '', description: 'Den', name: 'den']
]
)
}
}
sh'''#!/bin/bash +x
echo "Numerator: $Num\nDenominator: $Den"
echo "Output: $((Num/Den))"
'''
}
}
}
}
If you want to go the extra mile and ask for both values:
def userInput = input(
id: 'userInput', message: 'Let\'s re-enter everything?', parameters: [
[$class: 'TextParameterDefinition', defaultValue: '', description: 'Denominator', name: 'den'],
[$class: 'TextParameterDefinition', defaultValue: '', description: 'Numerator', name: 'num']
]
)
print userInput
env.Den = userInput.den
env.Num = userInput.num

Related

How to display the selected parameter in Jenkins?

There is a job groove pipeline that asks for parameters from the user interactively. After entering, I cannot display the selected parameters.
Here is my code:
node {
stage('Input Stage') {
Tag = sh(script: "echo 123'\n'456'\n'789'\n'111", returnStdout: true).trim()
input(
id: 'userInput', message: 'Choice values: ',
parameters: [
[$class: 'ChoiceParameterDefinition', name:'Tags', choices: "${Tag}"],
[$class: 'StringParameterDefinition', defaultValue: 'default', name:'Namespace'],
]
)
}
stage('Second Stage') {
println("${ChoiceParameterDefinition(Tags)}") //does not work
println("${ChoiceParameterDefinition(Namespace)}") //does not work
}
}
How to display the selected parameter correctly?
You would need to write the input step in a script. This should work.
node {
stage('Input Stage') {
Tag = sh(script: "echo 123'\n'456'\n'789'\n'111", returnStdout: true).trim()
script {
def userInputs =
input(
id: 'userInput', message: 'Choice values: ',
parameters: [
[$class: 'ChoiceParameterDefinition', name:'Tags', choices: "${Tag}"],
[$class: 'StringParameterDefinition', defaultValue: 'default', name:'Namespace'],
]
)
env.TAGS = userInputs['Tags']
env.NAMESPACE = userInputs['Namespace']
}
}
stage('Second Stage') {
echo "${env.TAGS}"
echo "${env.NAMESPACE}"
}
}
References:
Jenkins Declarative Pipeline: How to read choice from input step?
Read interactive input in Jenkins pipeline to a variable

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

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

How to get user input data in shell (Jenkinsfile)

I am trying to take user input through Jenkinsfile but I can't use that in the shell. Here is the code:
def userInput = timeout(time:60, unit:'SECONDS') {input(
id: 'userInput', message: 'URL Required', parameters: [
[$class: 'TextParameterDefinition', defaultValue: '', description: 'URL', name: 'url'],
])
}
node{
echo "Env jsfsjaffwef:"+userInput) //this works
echo "${userInput}" //but this does not
sh '''
python test.py ${userInput}
'''
}
Be careful about string interpolation: Variables will be replaced inside double quotes ("..", or the multi-line variant """), but not inside single quotes ('..', resp. '''..'''). So the sh step shouldn't have it replaced, the echo above should have it correctly.
def userInput = timeout(time:60, unit:'SECONDS') {input(
id: 'userInput', message: 'URL Required', parameters: [
[$class: 'TextParameterDefinition', defaultValue: '', description: 'URL', name: 'url'],
])
}
node {
echo "Env jsfsjaffwef:"+userInput) //this works
echo "${userInput}" // this should have also worked before
sh """
python test.py ${userInput}
"""
}
So make sure that you exactly apply the right quotes and don't just replace them compared to what people suggest here.
The following works for me on Jenkins 2.62:
def userInput = input(
id: 'userInput', message: 'URL Required', parameters: [
[$class: 'TextParameterDefinition', defaultValue: '', description: 'URL', name: 'url'],
])
node('master') {
sh "echo userInput is: ${userInput}"
}

What's the syntax of get the user's input from jenkins's pipeline step?

I build my job throuth jenkins's pipeline and useing the Snippet Generator to create my code like this :
node {
stage 'input'
input id: 'Tt', message: 'your password:', ok: 'ok', parameters: [string(defaultValue: 'mb', description: 'vbn', name: 'PARAM'), string(defaultValue: 'hj', description: 'kkkk', name: 'PARAM2')]
// here I need get the text user input , like `PARAM` or `PARAM2`
}
As described above, what's the syntax of get parameter ?
I'm kind of limited to test the code but I think it should be like:
node {
stage 'input'
def userPasswordInput = input(
id: 'userPasswordInput', message: 'your password', parameters: [
[$class: 'TextParameterDefinition', defaultValue='mb', description: 'vbn', name: 'password']
]
)
echo ("Password was: " + userPasswordInput)
}
node {
stage 'input'
def userPasswordInput = input(
id: 'Password', message: 'input your password: ', ok: 'ok', parameters: [string(defaultValue: 'master', description: '.....', name: 'LIB_TEST')]
)
echo ("Password was: " + userPasswordInput)
}
with the idea Joschi give , the code above works well .Thanks for Joschi again very much.

Resources