How to get user input data in shell (Jenkinsfile) - jenkins

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

Related

Looping over parameters added by Jenkins extended choice parameters

I've added an extendedChoice param on my .groovy file as below
extendedChoice(name: 'Subscription', defaultValue: 'demo_standard', description: 'Check mark on subscription/Part number', multiSelectDelimiter: ',', quoteValue: false, saveJSONParameterToFile: false, type: 'PT_CHECKBOX', value: 'demo_standard,demo_advanced,trial_standard,trial_advanced,standard,advanced', visibleItemCount: 6),
for calling this param I have below line.
sh "./create.js ${params.Username} ${params.Subscription} "
From the above line what I want to do is. If I select 2 | 3 | 4 | till 6 checks for subscriptions in params then above sh line should run those multiple times.
Example:
If I select "demo_advanced,trial_standard" then it should call sh command twice with both subscriptions.
sh "./create.js ${params.Username} ${params.Subscription} -->(demo_advanced will replace)"
sh "./create.js ${params.Username} ${params.Subscription} -->(trial_standard will replace)"
How can I write this on my .groovy file??
Here is a full sample of how you can do this in your Pipeline.
properties([
parameters([
extendedChoice(name: 'Subscription', defaultValue: 'demo_standard', description: 'Check mark on subscription/Part number', multiSelectDelimiter: ',', quoteValue: false, saveJSONParameterToFile: false, type: 'PT_CHECKBOX', value: 'demo_standard,demo_advanced,trial_standard,trial_advanced,standard,advanced', visibleItemCount: 6)
])
])
pipeline {
agent any
stages {
stage ("Example") {
steps {
script{
script {
echo "${params.Subscription}"
for(def sub : params.Subscription.split(',')) {
sh "./create.js ${params.Username} ${sub}"
}
}
}
}
}
}
}

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

groovy: MissingPropertyException: No such property:

I am facing an issue when shell command is returning non existent value because output produces no value as env.version == '1.0.0.232'-->false, does not exist in pypy server.
but when env.version == '1.0.0.23'--> true, does exist in pypy server, code proceed as normal.
Jenkins code:
pipeline {
agent { label 'master' }
parameters {
string(defaultValue: 'DEV', description: '', name: 'ENV', trim: true)
string(defaultValue: 'sys', description: '', name: 'platform_type', trim: true)
string(defaultValue: 'server2', description: '', name: 'dev_app_host', trim: true)
string(defaultValue: 'server1', description: '', name: 'dev_xbar_host', trim: true)
string(defaultValue: '1.0.0.23', description: '', name: 'VERSION', trim: true)
booleanParam(defaultValue: false, description: 'force build if possible', name: 'force_build')
}
environment {
}
stages {
stage('build') {
steps {
script {
try{
try{
def version_exists = sh(script: "ssh -o StrictHostKeyChecking=no ansible#pip_server ls /var/pypi/packages/dev/ | grep ${env.app_module_name} | grep ${env.VERSION}" , returnStdout: true) ?: 'no_files_found'
echo version_exists
echo version_exists.inspect()
echo version_exists.dump()
} catch(e){
echo "inner exception: ${e}"
}
} catch (e) {
echo "outer exception: ${e}"
currentBuild.result = 'FAILURE'
}
}
}
}
}
}
Jenkins relevant long:
+ grep 1.0.0.232
+ grep dvmt_event_processor
+ ssh -o StrictHostKeyChecking=no ansible#pip_server ls /var/pypi/packages/dev/
[Pipeline] echo
inner exception: hudson.AbortException: script returned exit code 1
[Pipeline] echo
outer exception: groovy.lang.MissingPropertyException: No such property: version_exists for class: groovy.lang.Binding
PS: can the shell command be improved upon?
grep returns status code 1 when it finds no matching lines. Jenkins interprets a non-0 status as the script failing, so it throws a hudson.AbortException rather than assigning the output to version_exists.
Try something like this:
def version_exists = sh( " ... | grep ${env.VERSION} || echo not_found", returnStdout: true)

Jenkins pipeline input script with one prompt only

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

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