Jenkins parameters using groovy script - jenkins

UPDATE
I have a simple pipeline where I want to receive in parameters multiple choices from a file.
In my file I have
#Test1,Accounts
#Test2,Services
#Test3,Accesses
and I want to have all of "#Test1", "#Test2" and "#Test3" in checkboxes as parameters so I would run only the tests selected.
But I'm not understanding what I'm doing wrong.
Pipeline
def code = """tests = getChoices()
return tests
def getChoices() {
def filecontent = readFile "/var/jenkins_home/test.txt"
def stringList = []
for (line in filecontent.readLines()) {stringList.add(line.split(",")[0].toString())}
List modifiedList = stringList.collect{'"' + it + '"'}
return modifiedList
}""".stripIndent()
properties([
parameters([
[$class : 'CascadeChoiceParameter',
choiceType : 'PT_CHECKBOX',
description : 'Select a choice',
filterLength : 1,
filterable : false,
name : 'choice1',
referencedParameters: 'role',
script : [$class : 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox : true,
script : 'return ["ERROR"]'
],
script : [
classpath: [],
sandbox : true,
script : code
]
]
]
])
])
pipeline {
agent {
docker { image 'node:latest' }
}
stages {
stage('Tags') {
steps {
getChoices()
}
}
}
}
def getChoices() {
def filecontent = readFile "/var/jenkins_home/test.txt"
def stringList = []
for (line in filecontent.readLines()) {
stringList.add(line.split(',')[0].toString())
}
List modifiedList = stringList.collect { '"' + it + '"' }
echo "$modifiedList"
return modifiedList
}
With this approach I know I can use multi-select checkboxes because I tried to substitute
def code = """ tests = ["Test1", "Test2", "Test3"]
return tests""".stripIndent()
and I get the output that I wanted.
But when I run my pipeline I get build SUCCESS but always get fallbackScript in my Build parameters checkbox. Can anyone help me out understand what is causing fallbackScript to run always? Thanks :)

If you want to auto-populate build parameters you have to return a list of parameters from your function. When you execute the pipeline the build with parameters will be populated. Note in this was only from the second execution of the pipeline the new parameters will be available. Refer following.
pipeline {
agent any
parameters{
choice(name: 'TESTES', choices: tests() , description: 'example')
}
stages {
stage('Hello') {
steps {
echo 'Hello World'
}
}
}
}
def tests() {
return ["Test01", "Test2", "Test4"]
}
If you want to get user input each time you execute a build you should move your choice parameter into a stage. Please refer to the following.
pipeline {
agent any
stages {
stage('Get Parameters') {
steps {
script{
def choice = input message: 'Please select', ok: 'Next',
parameters: [choice(name: 'PRODUCT', choices: tests(), description: 'Please select the test')]
echo '$choice'
}
}
}
}
}
def tests() {
return ["Test01", "Test2", "Test4"]
}
Update 02
Following is how to read from a file and dynamically create the choice list.
pipeline {
agent any
stages {
stage('Get Parameters') {
steps {
script{
sh'''
echo "#Test1,Accounts" >> test.txt
echo "#Test2,Services" >> test.txt
'''
def choice = input message: 'Please select', ok: 'Next',
parameters: [choice(name: 'PRODUCT', choices: getChoices(), description: 'Please select the test')]
}
}
}
}
}
def getChoices() {
def filecontent = readFile "test.txt"
def choices = []
for(line in filecontent.readLines()) {
echo "$line"
choices.add(line.split(',')[0].split('#')[1])
}
return choices
}

Related

How can I return file values in Jenkins choice parameter dropdown list?

I have this output.txt file:
cg-123456
cg-456789
cg-987654
cg-087431
Is it possible to get these values into a jenkins dropdown, like by using choice-parameter or active-choice-reactive parameter?
You can do something like the below.
pipeline {
agent any
stages {
stage ("Get Inputs") {
steps {
script{
script {
def input = input message: 'Please select the choice', ok: 'Ok',
parameters: [
choice(name: 'CHOICE', choices: getChoices(), description: 'Please select')]
}
}
}
}
}
}
def getChoices() {
filePath = "/path/to/file/output.txt"
def choices = []
def content = readFile(file: filePath)
for(def line : content.split('\n')) {
if(!line.allWhitespace){
choices.add(line.trim())
}
}
return choices
}

Is it possible to pass variable from steps to script in jenkinsfile

I have one pipeline and I want to pass one Arraylist that I get from a groovy method into the script that is running in Master Jenkins.
stages {
stage('Get Tests Parameter') {
steps {
code = returnList()
script {
properties([
parameters([
[$class : 'CascadeChoiceParameter',
choiceType : 'PT_CHECKBOX',
description : 'Select a choice',
defaultValue : '',
filterLength : 1,
filterable : false,
name : 'Tests',
referencedParameters: 'role',
script : [$class : 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox : true,
script : 'return ["ERROR"]'
],
script : [
classpath: [],
sandbox : false,
script : code
]
]
]
])
])
}
}
}
}
...
def returnList() {
def stringList = []
def fileContent = readFile "/var/jenkins_home/example.txt"
for (line in fileContent.readLines()) {
stringList.add(line.split(",")[0] + ":selected");
}
return stringList
}
That stages are running in a slave, so I couldn't execute that method returnList() inside the script because the script is running in Master. So I'm trying to get returnList ArrayList to a variable and use that variable in the script part.
Is that possible?
If you want to execute a specific step in a specific node then you can specify the agent within the stage block. So what you can do is execute the file reading logic on the master in the initial stage and then use it in consecutive stages. Check the example below.
def code
pipeline {
agent none
stages {
stage('LoadParameters') {
agent { label 'master' }
steps {
scipt {
code = returnList()
}
}
}
stage('Get Tests Parameter') {
steps {
script {
properties([
parameters([
[$class : 'CascadeChoiceParameter',
choiceType : 'PT_CHECKBOX',
description : 'Select a choice',
defaultValue : '',
filterLength : 1,
filterable : false,
name : 'Tests',
referencedParameters: 'role',
script : [$class : 'GroovyScript',
fallbackScript: [
classpath: [],
sandbox : true,
script : 'return ["ERROR"]'
],
script : [
classpath: [],
sandbox : false,
script : code
]
]
]
])
])
}
}
}
}
}
def returnList() {
def stringList = []
def fileContent = readFile "/var/jenkins_home/example.txt"
for (line in fileContent.readLines()) {
stringList.add(line.split(",")[0] + ":selected");
}
return stringList
}

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

Jenkinsfile with list of all parameter values or single value from parameter list

I want to run jenkins job using jenkinsfile with list of all parameters value or with individual value from parameter list.
def deploy(env) {
step([$class: 'UCDeployPublisher',
siteName: siteName,
deploy: [
$class: 'com.urbancode.jenkins.plugins.ucdeploy.DeployHelper$DeployBlock',
deployApp: appName,
deployEnv: 'DEV',
deployVersions: "${compName}:${version}",
deployProc: simpleDeploy,
deployOnlyChanged: false,
deployReqProps: "ID=${params.ID}"
]])
CHOICES = [ 'id1', 'id2', 'id3', 'id4', 'id5' ]
PARAMETERS = CHOICES + "all"
parameters {
choice(
name: 'ID',
choices: PARAMETERS,
)
stage (DEV') {
steps {
script {
if (params.ID == "all"){
CHOICES.each {
echo "$it"
}
deploy('devl') ===> this will call my deploy function
}
else {
echo "$params.ID"
deploy('devl') ===> this will call my deploy function
}
}
}
}
I was able to run job using bye selecting each value from droplist. But I also want to the run the job with all values from ID list. I tried with all but it is not taking all the the values 'id1', 'id2', 'id3', 'id4', 'id5'
You would need to define the choices in a var outside of the parameter and then use that as choices e.g.
CHOICES = [ 'id1', 'id2', 'id3', 'id4', 'id5' ]
PARAMETERS = CHOICES + "all"
pipeline {
agent any
parameters {
choice(name: "ID", choices: PARAMETERS )
}
stages {
stage('Test') {
steps {
script {
if (params.ID == "all"){
CHOICES.each {
echo "$it"
}
}
else {
echo "$params.ID"
}
}
}
}
}
}

Load declarative pipeline from inline function

I've seen this example on how to load declarative piplines form a shared Library:
https://jenkins.io/doc/book/pipeline/shared-libraries/#defining-declarative-pipelines
But I would like to have the pipeline as inline functions:
def linux_platform = "U1604_x64_gcc54"
def windows_platform = "WIN10_x64_vc141"
properties(
[
parameters(
[
choice(name: 'platform', choices: [linux_platform, windows_platform], description: 'Platform'),
string(defaultValue: "-1", description: 'Upsteam Project build number', name: 'upsteam_project_build_number')
]
)
]
)
if(params.platform == windows_platform) {
windows(params.upsteam_project_build_number)
}
def windows(upsteam_project_build_number) {
pipeline {
agent {
label windows_platform
}
environment {
WINDOWS_ENV = "C:/my_path"
}
stages {
stage('Do stuff') {
steps{
echo "Doing stuff"
}
}
}
post {
failure {
job_status_mail(currentBuild.currentResult, JOB_NAME, BUILD_NUMBER, BUILD_URL)
}
fixed {
job_status_mail("fixed", JOB_NAME, BUILD_NUMBER, BUILD_URL)
}
}
}
}
Im getting the following error:
java.lang.NoSuchMethodError: No such DSL method 'agent' found among steps
Is my syntax some how wrong or is it not possible to load a pipeline from a inlne function?
I'm running:
Jenkins ver. 2.138.4
Declarative Pipeline Plugin ver. 1.3.8

Resources