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}
Related
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 }
}
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 ;)
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']
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.
To begin i'm writing the pipeline entirely as groovy to be checked in to git. Please do not provide any gui necessary solutions. My Problem statement is:
Extract a variable from a file and set it equal to a groovy object.
What i've tried
def SERVICE_MAJOR_VERSION
node {
runGitClone(GIT_REPO_URL, GIT_HASH)
def conf = readFile("gradle.properties")
echo conf
//THE BELOW COMMENT DOESN'T WORK
//SERVICE_MAJOR_VERSION = loadEnvFromFile("SERVICE_VERSION_MAJOR", "gradle.properties", true, SERVICE_VERSION_MAJOR)
}
def runGitClone(git_repo_url, git_hash) {
checkout changelog: false, poll: false, scm: [$class: 'GitSCM', branches: [[name: git_hash]], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'WipeWorkspace']], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '85572032-4284-4095-9eec-4df70ddfdb68', url: git_repo_url]]]
}
def loadEnvFromFile(string_name, file_path, should_print_load) {
def par1 = null
def content = readFile file_path
def matcher = content =~ /${string_name}\=(.+)/
if (matcher) {
par1 = string_name + "='" + matcher[0][1] + "'"
new GroovyShell(this.binding).evaluate(par1)
if (should_print_load) {
println par1
}
}
return par1
}
I've tried other suggestions to no avail. Particularly the below two.
Get values from properties file using Groovy
Parsing string as properties
If you have a working example of extracting a variable from a file and setting it equal to a groovy object it would solve my problem.
SOLVED:
def content = readFile 'gradle.properties'
Properties properties = new Properties()
InputStream is = new ByteArrayInputStream(content.getBytes());
properties.load(is)
def runtimeString = 'SERVICE_VERSION_MINOR'
echo properties."$runtimeString"
SERVICE_VERSION_MINOR = properties."$runtimeString"
echo SERVICE_VERSION_MINOR