How to capture POST content parameters in Jenkins declarative syntax? - jenkins

How do you capture POST content parameters in code in Jenkins declarative syntax pipeline script?
This is an example of how to do it with scripted syntax:
node {
properties([
pipelineTriggers([
[$class: 'GenericTrigger',
genericVariables: [
[ key: 'committer_name', value: '$.actor.name' ],
[ key: 'committer_email', value: '$.actor.emailAddress' ],
[ key: 'ref', value: '$.changes[0].refId'],
[ key: 'tag', value: '$.changes[0].ref.id', regexpFilter: 'refs/tags/'],
[ key: 'commit', value: '$.changes[0].toHash' ],
[ key: 'repo_slug', value: '$.repository.slug' ],
[ key: 'project_key', value: '$.repository.project.key' ],
[ key: 'clone_url', value: '$.repository.links.clone[0].href' ]
],
causeString: '$committer_name pushed tag $tag to $clone_url referencing $commit',
token: 'my_token',
printContributedVariables: true,
printPostContent: true,
regexpFilterText: '$ref',
regexpFilterExpression: '^refs/tags/.*'
]
])
])
stage("Test") {
deleteDir()
def msg = "hello, world!"
emailext (subject: "Hello", \
mimeType: "text/html",\
body: "${msg} <br> \
committer_name ${committer_name} <br> \
committer_email ${committer_email} <br> \
ref ${ref} <br> \
tag ${tag} <br> \
commit ${commit} <br> \
repo_slug ${repo_slug} <br> \
project_key ${project_key} <br> \
clone_url ${clone_url} <br> \
",
from: "Jenkins#company.com", \
to: "${committer_email}")
This article claims that equivalent scripted syntax would be:
pipeline {
agent any
triggers {
GenericTrigger {
genericVariables {
genericVariable {
key( "committer_name" )
value( "\$.actor.name" )
expressionType( "JSONPath" )
}
}
token( "my_token" )
printContributedVariables(true)
printPostContent(true)
regexpFilterText( "\$ref" )
regexpFilterExpression( "^refs/tags/.*" )
}
}
stages {
stage( "Test" ) {
steps {
deleteDir()
}
}
}
(I stripped down the Test stage to reduced sources of error -- it should be inconsequential to this question).
...whereas in reality, it produces this error:
WorkflowScript: 4: Triggers definitions cannot have blocks # line 4, column 5.
GenericTrigger {
^
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:337)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:428)
Finished: FAILURE
What is correct declarative syntax "equivalent" to the working scripted syntax -- i.e. how can I capture POST content parameters with declarative syntax?
I'd specifically like to learn how to do this "in code", i.e. not using the Varianble/Expression fields of Post content parameters in the Jenkins GUI.

pipeline {
agent any
triggers {
GenericTrigger (
genericVariables: [
[ key: "committer_name", value: "\$.actor.name" ],
[ key: "committer_email", value: "\$.actor.emailAddress" ],
[ key: "ref", value: "\$.changes[0].refId" ],
[ key: "tag", value: "\$.changes[0].ref.id" ],
[ key: "commit", value: "\$.changes[0].toHash" ],
[ key: "repo_slug", value: "\$.repository.slug" ],
[ key: "project_key", value: "\$.repository.project.key" ],
[ key: "clone_url", value: "\$.repository.links.clone[0].href" ],
],
causeString: '$committer_name pushed tag $tag to $clone_url referencing $commit',
token: "my_token",
printContributedVariables: true,
printPostContent: true,
regexpFilterText: "\$ref",
regexpFilterExpression: "^refs/tags/.*"
)
}
stages {
stage( "Build" ) {
steps {
deleteDir()
}
}
}
post {
always {
emailext( subject: "Hello",
from: "jenkins#company.com",
to: "\${committer_email}",
mimeType: "text/html",
body: "hello world <br> \
committer_name ${committer_name} <br> \
committer_email ${committer_email} <br> \
ref ${ref} <br> \
tag ${tag} <br> \
commit ${commit} <br> \
repo_slug ${repo_slug} <br> \
project_key ${project_key} <br> \
clone_url ${clone_url} <br> \
" )
}
}
}

Related

How to make Jenkins rememeber the varaiable and its value when restarting jenkins pipeline?

I'm running the following Jenkinsfile
This Jenkins file allow the user to select values like version and quality of the build
This Jenkins file allow the user to select values like applications to be selected during the installation of the product (MSI file with features to select inside it)
pipeline {
agent any
parameters {
choice(
name: 'version_choice',
choices: 'Trunk\nV25.0.0\nV24.0.0',
description: 'Select a version (Trunk or Release No.)')
choice(
name: 'quality_choice',
choices: 'latestGreen\nHotfix\nReleased\nInternal',
description: 'Select a quality')
choice(
name: 'protocol_choice',
choices: 'HTTPS',
description: 'Select Protocol, HTTPS (Secured) or HTTP (Non-Secured)')
booleanParam(
name: 'fuel',
defaultValue: false,
description: '')
booleanParam(
name: 'aloha_kitchen',
defaultValue: false,
description: '')
booleanParam(
name: 'data_event_publisher',
defaultValue: false,
description: '')
booleanParam(
name: 'catalog_exporter',
defaultValue: false,
description: '')
booleanParam(
name: 'signal_r',
defaultValue: false,
description: '')
booleanParam(
name: 'fiscal',
defaultValue: false,
description: '')
booleanParam(
name: 'notification_server',
defaultValue: false,
description: '')
choice(
name: 'eft_simulator_choice',
choices: ['MTX', 'EPS'],
description: 'Select EFT Simulator')
booleanParam(
name: 'external_services',
defaultValue: false,
description: 'Ext. Services Simulator')
}
stages {
stage('Initial') {
steps {
script {
APPLICATIONS = "";
if ("${params.fuel}" == "true") {
APPLICATIONS += ',Fuel';
}
if ("${params.aloha_kitchen}" == "true") {
APPLICATIONS += ',AlohaKitchen';
}
if ("${params.data_event_publisher}" == "true") {
APPLICATIONS += ',DataEventPublisher';
}
if ("${params.catalog_exporter}" == "true") {
APPLICATIONS += ',CatalogExporter';
}
if ("${params.signal_r}" == "true") {
APPLICATIONS += ',SignalR';
}
if ("${params.fiscal}" == "true") {
APPLICATIONS += ',Fiscal';
}
return APPLICATIONS;
}
}
}
stage('Revert Lab') {
steps {
dir("ansible") {
ansiblePlaybook (
[
inventory: '.../lab_r_mf.yml',
playbook: '.../ansible/playbooks/revert_vcenter_lab.yml',
installation: 'ansible',
colorized : true,
]
)
}
}
}
stage('Copy Files') {
stage('Copy Files') {
steps {
dir("ansible") {
ansiblePlaybook (
[
inventory: '.../lab_r_mf.yml',
playbook: '.../ansible/playbooks/copy_tfs_builds.yml',
installation: 'ansible',
colorized : true,
extraVars : [
version_choice: '${version_choice}',
quality_choice: '${quality_choice}'
]
]
)
}
}
}
stage('Center APP') {
steps {
dir("ansible") {
ansiblePlaybook (
[
inventory: '.../lab_r_mf.yml',
playbook: '.../ansible/playbooks/install_secured_center_primary_appserver.yml',
installation: 'ansible',
colorized : true,
extraVars : [
applications: "${APPLICATIONS}",
]
]
)
}
}
}
stage('Gateway') {
steps {
dir("ansible") {
ansiblePlaybook (
[
inventory: '.../lab_r_mf.yml',
playbook: '.../ansible/playbooks/install_secured_gateway.yml',
installation: 'ansible',
colorized : true,
extraVars : [
protocol_choice: '${protocol_choice}',
version_choice: '${version_choice}',
quality_choice: '${quality_choice}',
]
]
)
}
}
}
stage('app') {
steps {
dir("ansible") {
ansiblePlaybook (
[
inventory: '.../lab_r_mf.yml',
playbook: '.../ansible/playbooks/install_secured_app.yml',
installation: 'ansible',
colorized : true,
extraVars : [
applications: "${APPLICATIONS}",
]
]
)
}
}
}
stage('EFT. Sim.') {
parallel {
stage('MTX') {
when {
expression {
params.eft_simulator_choice == 'MTX'
}
}
steps {
dir("ansible") {
ansiblePlaybook (
[
inventory: '.../lab_r_mf.yml',
playbook: '.../ansible/playbooks/deploy_mtx_simulator.yml',
installation: 'ansible',
colorized : true,
extraVars : [
protocol_choice: '${protocol_choice}',
]
]
)
}
}
}
stage('EPS') {
when {
expression {
params.eft_simulator_choice == 'EPS'
}
}
steps {
dir("ansible") {
ansiblePlaybook (
[
inventory: '.../lab_r_mf.yml',
playbook: '.../ansible/playbooks/deploy_eps_simulator.yml',
installation: 'ansible',
colorized : true,
extraVars : [
version_choice: '${version_choice}',
quality_choice: '${quality_choice}',
protocol_choice: '${protocol_choice}',
]
]
)
}
}
}
}
}
}
}
It often happens that the pipeline falls because of a network issuesor any unexpected behaviour
Trying to restart the pipline based on this Jenkins, shows error message like:
groovy.lang.MissingPropertyException: No such property: APPLICATIONS for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:251)
at org.kohsuke.groovy.sandbox.impl.Checker$7.call(Checker.java:353)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:357)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:333)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:333)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:333)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:29)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
at WorkflowScript.run(WorkflowScript:277)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.get(PropertyishBlock.java:74)
at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30)
at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.fixName(PropertyishBlock.java:66)
at jdk.internal.reflect.GeneratedMethodAccessor304.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
at com.cloudbees.groovy.cps.Next.step(Next.java:83)
at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:136)
at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:275)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:18)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:51)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:187)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:420)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$400(CpsThreadGroup.java:95)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:330)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:294)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:67)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:139)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:30)
at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:70)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)
Finished: FAILURE
This failure means that Jenkins doesn't know APPLICATIONS varaiable.
How do I take care of this varaiable and others (like $protocol_choice) in a way that in any phase Jenkinsfile "know" the varaiable and its selected value?
What you're looking for is the Rebuilder plugin. When you set parameters, it will remember what those parameters are. When you want to rerun a job, you can select the job and there will be a new "Rebuild" button in the left hand pane which will start the job with all the parameters you used previously.

Jenkins File - Execute shell command in active choice script

everyone, I'm using plugin "Active Choices" in my Jenkins, I try to do something condition, and the return based on environment host that will be executed in shell command in my Jenkins file. the command like "echo ${BUILD_ENVIRONMENT}, echo ${BUILD_VERSION}..etc".
Already doing this but the list is still empty. now, what do I have to do to make this work? thank you.
JenkinsFile:
properties([
parameters([
[$class: 'ChoiceParameter',
choiceType: 'PT_SINGLE_SELECT',
name: 'ENVIRONMENT',
description: 'Select Environment',
script: [
$class: 'GroovyScript',
script: [
classpath: [],
sandbox: true,
script: '''
def getEnvVar(String name) {
return sh(script: "echo \${$name}", returnStdout: true).trim()
}
def env = getEnvVar("ENVIRONMENT")
if (envs != "testing") {
return ["stage", "dev", "prod"]
}else{
return ["testing"]
}
''',
],
]
]
])
])
Output:
im fix it with another solution, but maybe isnt the best option.
1st create a method to load the env file (i set the values on it), then define to jenkins global variable.
getEnvHosts = { ->
node {
script {
// Get the environment hosts file
def props = readProperties file: '/var/lib/jenkins/env/dast-service-env'
//define to jenkins global variable
env.BUILD_ENVIRONMENT = props['BUILD_ENVIRONMENT']
}
}
}
and then i call the "BUILD_ENVIRONMENT" with ${env.BUILD_ENVIRONMENT} like this in active choice parameter:
getEnvHosts()
properties([
parameters([
[$class : 'ChoiceParameter',
choiceType : 'PT_SINGLE_SELECT',
name : 'BUILD_ENVIRONMENT',
description: "Select Environment default is ${env.BUILD_ENVIRONMENT}",
script : [
$class: 'GroovyScript',
script: [
classpath: [],
sandbox : true,
script : """
def envs = "${env.BUILD_ENVIRONMENT}"
if (envs == "stage") {
choices = ["stage", "dev", "prod", "testing"]
}else if (envs == "dev") {
choices = ["dev", "prod", "stage", "testing"]
}else if (envs == "prod") {
choices = ["prod", "dev", "stage", "testing"]
}else{
choices = ["testing", "stage", "dev", "prod"]
}
return choices
""",
],
]
],
])
])

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

Resources