String parameter passing in jenkins pipeline - jenkins

I am developing a pipeline where in when triggered it should display the parameters and below is the code
node {
stage('preparation') {
timeout(time:15, unit:'MINUTES') {
id: 'userInput', message: 'preparation',
parameters: [
[$class: 'TextParameterDefinition', defaultValue: 'cicd', description: 'dev env', name: 'DEV_PROJECT'],
[$class: 'TextParameterDefinition', defaultValue: 'test', description: 'stage env', name: 'STAGE_PROJECT'],
[$class: 'TextParameterDefinition', defaultValue: 'jboss', description: 'Image Name', name: 'IMAGE_NAME'],
] )
input message: "Is the PARAMETERS(can be visible on leftside) are correctly set for deployment?", ok: "Promote" }
echo "${DEV_PROJECT}"
echo "${STAGE_PROJECT}"
echo "${IMAGE_NAME}"
}
When i do echo its not populating the values of user input.
Iam getting below error. My requirement is the user can input the DEV_PROJECT,STAGE_PROJECT and IMAGE_NAME and the values entered by him should be used in the pipeline scripts down the line in build and deploy stages.Iam getting below error
groovy.lang.MissingPropertyException: No such property: DEV_PROJECT for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:242)
at org.kohsuke.groovy.sandbox.impl.Checker$6.call(Checker.java:284)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:288)
could anyone let me know how to proceed?

If you have configured your pipeline to accept parameters when it is built — Build with Parameters — they are accessible as Groovy variables inside params.
Example: Using isFoo parameter defined as a boolean parameter (checkbox in the GUI):
node {
sh "isFoo is ${params.isFoo}"
sh 'isFoo is ' + params.isFoo
if (params.isFoo) {
// do something
}
Reference: https://jenkins.io/doc/book/pipeline/getting-started/#global-variable-reference

Related

How to add radio buttons in Jenkins using groovy when building a job using "Build with parameters"?

I am trying to add radio buttons in Jenkins instead of checkboxes when running Build with Parameters. In my existing code, I am getting checkboxes. What changes should I make in my existing code to get the radio buttons. Below is my groovy code:
def call(Map config = [:]) {
paramsList = []
paramsList << booleanParam(name: 'deployToDev', defaultValue: false, description: 'Set to true to deploy to Dev K8s Environment')
paramsList << booleanParam(name: 'deployToTest', defaultValue: false, description: 'Set to true to deploy to Test K8s Environment')
paramsList << booleanParam(name: 'deployToStage', defaultValue: false, description: 'Set to true to deploy to Stage K8s Environment')
properties([parameters(paramsList)])
}
Please find the below screenshot:
You can achieve that easily using the Extended Choice Parameter which has a built in support for all kinds of selection options including radio buttons.
You can use it as follows:
def call(Map config = [:]) {
paramsList = []
// You can also set the default value using the 'defaultValue' option
paramsList << extendedChoice(name: 'DeployTo', description: 'Select the environment to deploy to', type: 'PT_RADIO', value: 'Dev,Test,Stage', visibleItemCount: 5)
properties([parameters(paramsList)])
}
The result will look like:
You can also use the Active Choices plugin, which is a bit more complicated but has more configuration options, it will also allow you to generate the values from a groovy script.
For example:
properties([parameters(
[[$class: 'ChoiceParameter', name: 'DeployTo', choiceType: 'PT_RADIO', description: 'Select the environment to deploy to', script: [$class: 'GroovyScript', script: [classpath: [], sandbox: false, script: "return ['Dev','Test','Stage']"]]]]
)])

How to add a build selector as a parameter?

I have two jobs:
Build job
Deployment job
I copy the artifacts (jars) generated in the first job to the second job and deploy them to an environment.
properties([
parameters(
[
string(
name: 'buildnumber',
description: 'Buildnumber to deploy'
),
choice(
name: 'env',
choices: ['qa', 'stage', 'prod'],
description: 'Environment where the app should be deployed'
)
]
)
])
node{
stage('Copy artifacts'){
copyArtifacts(projectName: 'my-demo-build-job/master', selector: specific(params.buildnumber))
}
stage('Deploy'){
sh 'Deploying to the specified environment '
}
}
With this I have to manually check the latest/successful builds and put that as a parameter. Is there a way so that we can get a dropdown with all the successful build sorted by build number as a selector from the other job?
You can use the Extended Choice Parameter Plugin for achieving what you want with the help of a groovy script.
You will need to define an extended choice parameter of type Single Select, as a Source for Value choose Groovy Script, and as a groovy script use something like the following:
def job = jenkins.model.Jenkins.instance.getItemByFullName('my-demo-build-job/master')
return job.builds.findResults{
it.result == hudson.model.Result.SUCCESS ? it.getNumber().toInteger() : null
}
This script will go over all the build of the configured job and filter out only the successful builds - which will be returned as the select-list options for the parameter.
The configuration in the pipeline will look like:
properties([
parameters([
extendedChoice(name: 'buildnumber', type: 'PT_SINGLE_SELECT', description: 'Buildnumber to deploy', visibleItemCount: 10, groovyScript:
'''def job = jenkins.model.Jenkins.instance.getItemByFullName('my-demo-build-job/master')
return job.builds.findResults { it.result == hudson.model.Result.SUCCESS ? it.getNumber().toInteger() : null }''',
choice(name: 'env', choices: ['qa', 'stage', 'prod'], description: 'Environment where the app should be deployed'),
])
])

How to pass choice parameter to call a job inside jenkins pipeline

How can I pass choice parameters for the downstream job when called inside a stage in the jenkins pipeline?
I tried the below solutions but none worked:
stage('build job') {
steps{
script{
build job: 'test',
parameters: [
choice(choices: "option1\noption2\noption3\n", description: '', name: 'choiceParam')
]
}
}
}
fails with java.lang.UnsupportedOperationException: no known implementation of class hudson.model.ParameterValue is using symbol ‘choice’
Tried these as well:
parameters:
[
[$class: 'ChoiceParameterValue', name: 'choiceParam', value: "1\n\2\n3\n"],
]
fails with java.lang.UnsupportedOperationException: no known implementation of class hudson.model.ParameterValue is named ChoiceParameterValue
I actually want to pass the choice parameter as a build parameter like "$choiceParam" for value so that I can just update the jenkins job configuration instead of always updating the values in the pipeline script
Can someone please help me with this
Thanks
When you are building a job via the Build step, you are kicking it off so you need to have "selected" a value.
In this instance you would pass in the desired 'String' choice. Not a list of choices. i.e. "1"
We create our list of params and then pass that in. So: our current job has these input params:
choice(name: 'ENV', choices: product, description: 'Env'),
choice(name: 'ENV_NO', choices: envParams(product), description: 'Env No'),
We pass these downstream by setting them:
List<ParameterValue> newParams = [
new StringParameterValue('ENV', params.ENV),
new StringParameterValue('ENV_NO', params.ENV_NO),
]
build(job: "job", parameters: newParams, propagate: false)

Capturing results of Jenkins input step

I am playing around with the Jenkins Pipeline and I have some issues at the time of capturing the results of an input step. When I declare the input step as follows ...
stage('approval'){
steps{
input(id: 'Proceed1', message: 'Was this successful?',
parameters: [[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']])
}
}
... everything seems to be working fine. However, as soon as I try to get the results from the capture (i.e. the answer given to the question), the script does not work. For example, an script like the following:
pipeline {
agent { label 'master' }
stages {
stage('approval'){
steps{
def result=input(id: 'Proceed1', message: 'Was this successful?', parameters: [[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']])
echo 'echo Se ha obtenido aprobacion! (como usar los datos capturados?)'
}
}
}
}
... results in the following error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 6: Expected a step # line 6, column 13.
result=input(id: 'Proceed1', message: 'Was this successful?', parameters: [[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']])
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1073)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:591)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:569)
...
at hudson.model.Executor.run(Executor.java:404)
Finished: FAILURE
Something quite interesting is that if I moved the input outside the pipeline{}, it works perfectly fine. I noticed that same behaviour occurs with 'def' statement (I can define and use a variable outside pipeline{} but I cannot define it inside).
I think I must be missing something quite basic here but after few hours trying different configurations, I could not manage to make it work. Is it just that the logic to be used within pipeline{} is limited to very few commands? How people then build complex pipelines?
Any help would be highly appreciated.
The script block allows using the Scripted Pipeline syntax aka almost all Groovy functionality within a Declarative pipeline.
See https://jenkins.io/doc/book/pipeline/syntax/ for syntax comparision and restrictions of the declarative pipeline.
pipeline {
agent any
...
stages {
stage("Stage with input") {
steps {
script {
def result = input(id: 'Proceed1', message: 'Was this successful?', parameters: [[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']])
echo 'result: ' + result
}
}
}
}
}
I finally managed to make it work but I had to completely change the syntax to avoid pipeline, stages & steps tags as used above. Instead, I implemented something like:
#!/usr/bin/env groovy
node('master'){
// --------------------------------------------
// Approval
// -------------------------------------------
stage 'Approval'
def result=input(id: 'Proceed1', message: 'Was this successful?', parameters: [[$class: 'BooleanParameterDefinition', defaultValue: true, description: '', name: 'Please confirm you agree with this']])
echo 'Se ha obtenido aprobacion! '+result
}

jenkins pipeline def new string parameter

I have a parameterized job with pipeline.
for example: Predefined String Parameter: IP
I'm trying to define a new String in the pipeline in order to use it as a new parameter when I'm calling to another "build job"
I have tried the following method:
import hudson.model.*
node('master'){
if(ipaddr =='192.168.1.1'){
def parameter = new StringParameterValue("subnet", '255.255.255.0') //not working
echo parameter //not working
}
stage ('Stage A'){
build job: 'jobA', parameters:
[
[$class: 'StringParameterValue', name: 'ip', value: ip],
[$class: 'StringParameterValue', name: 'subnet', value: subnet] //not working
]
}
}
this way it's not working and I get the error:
Scripts not permitted to use new hudson.model.StringParameterValue
after changing the line:
def parameter = new StringParameterValue("subnet", '255.255.255.0')
to:
subnet = '255.255.255.0'
I got the error:
groovy.lang.MissingPropertyException: No such property: subnetmask for
class: groovy.lang.Binding.
I can't call to a new job with the predefined parameter ip and the new parameter subnet
without the subnet it's working
any idea of how can I define new String parameter in the pipeline?
jenkins version: 2.19.4
You can have it working if you just avoid instantiating StringParameterValue because as David M. Karr mentionned pipelines sandbox is pretty restrictive. Instead, just use your simple variable when calling your job, like this :
def subnet = ""
if(ipaddr == '192.168.1.1') {
subnet = '255.255.255.0'
echo subnet
}
stage ('Stage A'){
build job: 'jobA', parameters:
[
[$class: 'StringParameterValue', name: 'ip', value: ipaddr],
[$class: 'StringParameterValue', name: 'subnet', value: subnet]
]
}
It's pretty simple, StringParameterValue params expect String to be passed, so as long as you pass string values you should be just fine !
By default, the sandbox the pipeline job executes in is very restricted. You have to override the security restrictions when you find them. Go to "Manage Jenkins" and "In-process Script Approval". You should see in the list the last violation that occurred. Select it for approval and rerun your script.

Resources