Jenkinsfile Groovy Pipeline Text Parameter Whitespace - jenkins

currently I wish to added a multliline text parmeter to a groovy pipeline. If the text parameter is not left column alighed (no space before paramter), then whitespace is injected into the text parameter list.
Any ideas on how to resolve this?
Here is the code
#!/usr/bin/env groovy
node {
def startTime = new Date()
println "Build start time : " + startTime
// Load system parameters
def projectProperties = [
[$class: 'EnvInjectJobProperty', info: [loadFilesFromMaster: false, secureGroovyScript: [classpath: [], sandbox: false, script: '']], keepBuildVariables: true, keepJenkinsSystemVariables: true, on: true]
]
// Set project parameters
projectProperties.add(parameters([
string(name: 'infraRepo', description: 'Repo Name', defaultValue: 'my-infrastructure' ),
string(name: 'infraBranch', description: 'Repo Branch', defaultValue: 'develop' ),
string(name: 'projectName', description: 'Project name', defaultValue: 'think-more' ),
// Text field not left side aligned now whitespace will be injected
text(name: 'ecrRepoAndVersion', description: 'ECR Docker name and version number',
defaultValue:'''address=3.0.1
address-details=3.0.1
auth=3.2.1'''),
choice(name: 'clusterName', description: 'Ecs cluster name', choices: '---Select---\nblue-ci\ngreen-ci', defaultValue: '---Select---'),
]))
properties(projectProperties)
// Print system variables
sh 'env | sort'
}
And here is an image of how the Jenkins Job UI looks after this pipeline is executed. Note the whitespace in the ecrRepoAndVersion field.

Thank you - that worked perfectly.
text(name: 'ecrRepoAndVersion', description: 'ECR Docker name and
version number',defaultValue:"""address=3.0.7-RC\n
address-details=3.0.3-RC\nauth=3.2.3-RC""")

Setting aside the need for this logic, I would add a bit more readability and ease of maintenance by joining a list of items, instead of verbatim specification:
def ecrRepoAndVersionItemsDefault = [
"address=3.0.7-RC",
"address-details=3.0.3-RC",
"auth=3.2.3-RC",
]
...
// then construct an ArrayList
def jobParams = []
jobParams << ...
...
jobParams << text(
name: 'ecrRepoAndVersion',
description: 'ECR Docker name and version number',
defaultValue: ecrRepoAndVersionItemsDefault.join('\n')
)
// then add the properties
...
projectProperties.add(parameters(jobParams))
...
properties(projectProperties)
...
// etc.

Related

How to deal with pipe delimited files with Groovy?

Help please! I just had this groovy scripted dropped on me and it does not do a very good job a parsing pipe delimited files.
Here's the bit of Groovy code:
def runAnsibleAction(String line) {
println("runAnsibleAction called with line = ${line}")
def (ACTION, PATTERN, INVENTORY, LIMIT, MODULE, DASH_A, EXTRA_PARAMS) = line.tokenize('|')
build job: 'run_ansible', propagate: true, wait: true, parameters: [
[$class: 'StringParameterValue', name: 'PATTERN', value: PATTERN],
[$class: 'StringParameterValue', name: 'INVENTORY', value: INVENTORY],
[$class: 'StringParameterValue', name: 'LIMIT', value: LIMIT],
[$class: 'StringParameterValue', name: 'MODULE', value: MODULE],
[$class: 'StringParameterValue', name: 'DASH_A', value: DASH_A],
[$class: 'StringParameterValue', name: 'EXTRA_PARAMS', value: EXTRA_PARAMS]]
}
The bug occurs whenever someone specifies DASH_A as bash command line with pipe in it. Like netstat | grep 8080.

How to compare a map in groovy

In a groovy script for Jenkins Pipeline, I have a map and few strings separated by comma. I want to compare each string with the keys of map and if the string is not present as key in map, then remove the entry from the map
Here is my code:
node=node1,node2
map=[
node1: [ name: "node1", property: "1234"],
node2: [ name: "node2", property: "2345"]
node3: [ name: "node3", property: "3456"]
]
Here only node1 and node2 are in node variable. So in my map, I need to only have node1 and node2.
I tried something like this in my Jenkins DSL pipeline but it didn't work:
stages {
stage('Build nodes') {
steps {
script{
"${node}".tokenize( ',' ).each
{n ->
echo "Node Selected ${n}"
new_map1=add_nodes("${n}")
}
}
}
}
}
def new_map=[:]
def add_nodes(n){
"${new_map}" << map."${node}"
return "${new_map}"
}
Error I'm getting is:
groovy.lang.MissingPropertyException: No such property: new_map for class: groovy.lang.Binding
def nodeArray = ['node1', 'node2']
def map=[
node1: [ name: "node1", property: "1234"],
node2: [ name: "node2", property: "2345"],
node3: [ name: "node3", property: "3456"]
]
def map2=map.findAll{k,v-> v.name in nodeArray}

Jenkins Pipeline Choice Input with List of Map in groovy not working

I have the following input in one of my Jenkins Pipeline Scripts:
def IMAGE_TAG = input message: 'Please select a Version', ok: 'Next',
parameters: [choice(name: 'IMAGE_TAG', choices: imageTags, description: 'Available Versions')]
imageTags is a List of map e.g. :
imageTags : [
[targetSuffix: "", sourceSuffix: "v2.17.1"],
]
When I run the script, I can select only [targetSuffix: "", sourceSuffix: "v2.17.1"] from the dropdown choice as expected.
In my script I can also see the value that gets selected:
echo "Selected Version = ${env.SELECTED_IMAGE_TAG}"
[Pipeline] echo Selected Version = {targetSuffix=, sourceSuffix=v2.17.1}
Now I wanted to find out which item from the original imageTags List got selected, but my script does not work as expected:
def selectedImageTag = imageTags.find { it.targetSuffix == "${env.SELECTED_IMAGE_TAG.targetSuffix}" }
I end up with the following exception:
groovy.lang.MissingPropertyException: No such property: targetSuffix for class: java.lang.String
My question is: How do I get the selected item of my choice out of the original List of maps?
The input step returns a string, so you can't write env.SELECTED_IMAGE_TAG.targetSuffix. You have to extract the substring, e. g. using a regular expression like this:
def match = ( env.SELECTED_IMAGE_TAG =~ /\{targetSuffix=(.*?), sourceSuffix=(.*?)\}/ )
if( match ) {
def selectedTargetSuffix = match[0][1]
def selectedImageTag = imageTags.find { it.targetSuffix == selectedTargetSuffix }
}

Problems passing boolean param to a pipeline child job

I have this pipeline job that needs to call a validation job like this:
isHardReleaseAllowed= true
def versionOk = build(job: "/validateMVNVersion", parameters: [[$class: 'StringParameterValue', name: 'version', value: params.version],
[$class: 'BooleanParameterValue', name: 'isHardReleaseAllowed', value: isHardReleaseAllowed]], propagate: true)
The validate job is defined as follows :
string(name: 'version', description: 'The new version to set')
booleanParam(name: 'isReleaseTagAllowed',defaultValue: false , description: 'is hard release tag allowed?')
These are my values before calling my job (from the output console) :
echo ➡ validating version 1.12.14 tag on branch ➡release/testRelease with isHardReleaseAllowed= true
But when I echo these in my validateMVNVersion job ,
echo "isReleaseTagAllowed class : \u27A1" + isReleaseTagAllowed.getClass().toString() + " value :" + isReleaseTagAllowed
echo "env.isReleaseTagAllowed \u27A1" + env.isReleaseTagAllowed.getClass().toString() + " value :" + env.isReleaseTagAllowed
echo "params.isReleaseTagAllowed \u27A1" + params.isReleaseTagAllowed.getClass().toString() + " value :" + params.isReleaseTagAllowed
boolean isReleaseBranchAllowedBoolean = params.isReleaseTagAllowed == "true"
echo "Boolean asboolean value is " + isReleaseBranchAllowedBoolean
I get these values :
isReleaseTagAllowed class : ➡class java.lang.String value :false
[Pipeline] echo
env.isReleaseTagAllowed ➡class java.lang.String value :false
[Pipeline] echo
params.isReleaseTagAllowed ➡class java.lang.Boolean value :false
[Pipeline] echo
Boolean asboolean value is false
All of them are false... What am I not getting?
A good way of getting the value is by setting the right variable name ;)

How to get input steps ouput in jenkins-pipeline

I used in my pipeline a input steps as you can see below :
input(
message : "some message",
parameters: [
[$class: 'ChoiceParameterDefinition',
choices: string ,
description: 'description',
name:'input'
]
]
)
I wanted to use the name input that I configure to get the value put in the input like this ${input}, but it didn't work. I also tried to put it in a var like this :
def reg = input : messages : "", paramaters: [...]
But It doesn't work either, so I don't understand how I can get the param that the user chose and didn't find how to do in the do.
Regards,
When using ChoiceParameterDefinition remember to define choices as string delimited with \n. You can assign value returned by input(...) step to a variable and use it later on. Take a look at following example:
node {
stage('Test') {
def reg = input(
message: 'What is the reg value?',
parameters: [
[$class: 'ChoiceParameterDefinition',
choices: 'Choice 1\nChoice 2\nChoice 3',
name: 'input',
description: 'A select box option']
])
echo "Reg is ${reg}"
}
}
In this example I define a single select with 3 options. When I run this pipeline, I get this popup to select one of three options:
I pick the first one and pipeline finishes with following console output:
[Pipeline] node
Running on Jenkins in /var/jenkins_home/workspace/test-pipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Test)
[Pipeline] input
Input requested
Approved by admin
[Pipeline] echo
Reg is Choice 1
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Try use this code:
def userInput = input(id: 'userInput', message: 'some message', parameters: [
[$class: 'ChoiceParameterDefinition', choices: string, description: 'description', name:'input'],
])
VARAIBLE = userInput
It's work For me.
If you need add more ChoiceParameterDefinition code should look like that:
def userInput = input(id: 'userInput', message: 'some message', parameters: [
[$class: 'ChoiceParameterDefinition', choices: string, description: 'description1', name:'input1'],
[$class: 'ChoiceParameterDefinition', choices: string, description: 'description2', name:'input2'],
])
VARAIBLE1 = userInput['input1']
VARAIBLE2 = userInput['input2']

Resources