obtaining groovy value from map given computed key for jenkins? - jenkins

Given the map:
def mymap = ["first":"aaa", "second":"bbb", "third":"ccc"]
I would like to get the value for a key where the key is a parameter of the Jenkins job that runs this Groovy script.
I have tried a number of methods similar to
sh "echo the value is ${mymap.${paramValue}}"
but this is throwing the error
" unclassified method java.util.LinkedHashMap"

the way to fix this was to separate out getting the value from the map and feeding that value into the next step.
def value = mymap."${paramValue}"
sh "echo the value is ${value}"

You can use the get method:
sh "echo the value is ${mymap.get(paramValue)}"

Related

Jenkins scripted pipeline nested environment variable

I'm using the Jenkins scripted pipeline and having trouble understanding how to nest environment variables within each other, here is a MWE:
// FROM https://jenkins.io/doc/pipeline/examples/#parallel-multiple-nodes
def labels = []
if (HOST == 'true') {
labels.add(<HOSTNAME>)
}
def builders = [:]
for (x in labels) {
def label = x
builders[label] = {
ansiColor('xterm') {
node(label) {
stage('cleanup') {
deleteDir()
}
stage('build') {
env.test = "TESTA"
env.intern = '''
TEST = "${env.test}"
'''
sh '''
echo $intern
printenv
'''
}
}
}
}
}
parallel builders
The idea here is that env.test contains the value TESTA, which sets env.intern to TEST = TESTA this is what I want to happen. After this the code is just to print out the values.
Sadly the result is TEST = "${env.test}".
How can I use nested string environment variables in Jenkins scripted pipeline?
The syntax difference here is literal strings versus interpolated strings in Groovy versus shell interpreters within shell step methods.
": interpolated string in Groovy
': literal string in Groovy and interpolated string in shell interpreter
Essentially, a Groovy variable is interpolated within " in the pipeline execution, and an environment variable is interpolated within " in the pipeline execution and within ' in the shell interpreter (and within the pipeline must also be accessed within the env object, but is a first class variable expression in the shell step method).
Therefore, we can fix the assigned value of env.intern with:
env.intern = "TEST = ${env.test}"
where the assigned value of env.test will be interpolated within the Groovy string and assigned to the env pipeline object at the intern key. This will then also be accessible to the shell interpreter within shell step methods, and the rest of your pipeline is already correct and will behave as expected.
Try the following:
env.intern = "TEST = ${env.test}"
As you're setting it now, the actual result of env.intern will be "TEST= ${env.test}". So long as you set env.test before you set env.intern you should be good. Also, good to note that if you change the value of env.test then you need to reset the value of env.intern or it's going to hold the original value of env.test that it was set to.

How to pass Value inserted in text box of Active choice reactive parameter to job

When I'm in "build with parameters" before starting job, I want to pass the value entered in a textbox to the Job. I´m using Active choice and Active choice reactive parameter like this:
This is the groovy script which I then use to run job and show output. But I´m getting NULL on echo command.
node {
def commit = params.val
stage ('Pulling code from Bitbucket') {
git branch: 'master',
credentialsId: '2bbc73c4-254e-45bd-85f4-6a169699310c',
url: 'git#bitbucket.org:repo/test.git'
sh (""" echo ${commit}""")
}
}
Which is the correct way to pass parameter into build ?
From your output, you have defined a parameter named ID1 that references some other parameter named OPTIONS. The correct way to reference these parameters is params.ID1 and params.OPTIONS. I can't see a parameter named val that can be addressed by params.val.

Passing parameter from for loop to multiline sh in jenkins pipeline

I have groovy jenkins pipeline step and I want to pass for loop value as parameter to multiline sh script in loop. But parameter is not getting passed.
Or if theres a better way to add step in jenkins stage?
for (int i = 0; i < elements.size(); i++) {
sh '''
cd terraform/
terraform init
terraform workspace select ${elements[i]}-${envtype}
terraform plan -var-file="./configs/${elements[i]}/var.tf"
'''
}
It seems that you should use """ instead of '''. ''' is triple single quoted String and doesn't support interpolation.
You need a triple double quoted string. You are using a triple single quoted string. Any single quoted string in Groovy does not feature String interpolation, so '''${i}''' prints ${i}, while """${i}""" prints 3 (if i = 3).

I have a Jenkins global variable in a string - how do I evaluate it?

I need to accept all kinds of global Jenkins variables as strings (basically as parameters to ansible like system - a template stored in \vars).
def proof = "\"${params.REPOSITORY_NAME}\""
echo proof
def before = "\"\${params.REPOSITORY_NAME}\""
echo before
def after = Eval.me(before)
echo after
The result is:
[Pipeline] echo
"asfd"
[Pipeline] echo
"${params.REPOSITORY_NAME}"
groovy.lang.MissingPropertyException: No such property: params for class: Script1
the first echo proves that the param value actually exists.
the second echo is the what the input actually looks like.
the third echo should have emitted asdf instead I get the exception.
Any ideas? I'm hours into this :-(
You may want to check:
groovy: Have a field name, need to set value and don't want to use switch
1st Variant
In case you have: xyz="REPOSITORY_NAME" and want the value of the parameter REPOSITORY_NAME you can simply use:
def xyz = "REPOSITORY_NAME"
echo params."$xyz" // will print the value of params.REPOSITORY_NAME
In case if your variable xyz must hold the full string including params. you could use the following solution
#NonCPS
def split(string) {
string.split(/\./)
}
def xyz = "params.REPOSITORY_NAME"
def splitString = split(xyz)
echo this."${splitString[0]}"."${splitString[1]}" // will print the value of params.REPOSITORY_NAME
2nd Variant
In case you want to specify an environment variable name as parameter you can use:
env.“${params.REPOSITORY_NAME}”
In plain groovy env[params.REPOSITORY_NAME] would work but in pipeline this one would not work inside the sandbox.
That way you first retrieve the value of REPOSITORY_NAME and than use it as key to a environment variable.
Using directly env.REPOSITORY_NAME will not be the same as it would try to use REPOSITORY_NAME itself as the key.
E.g. say you have a job named MyJob with the following script:
assert(params.MyParameter == "JOB_NAME")
echo env."${params.MyParameter}"
assert(env."${params.MyParameter}" == 'MyJob')
This will print the name of the job (MyJob) to the console assuming you did set the MyParameter parameter to JOB_NAME. Both asserts will pass.
Please don’t forget to open a node{} block first in case you want to retrieve the environment of that very node.
After trying all those solutions, found out that this works for my problem (which sounds VERY similar to the question asked - not exactly sure though):
${env[REPOSITORY_NAME]}

Dynamic variable in Jenkins pipeline with groovy method variable

I have a Jenkinsfile in Groovy for a declarative pipeline and two created Jenkins variables with names OCP_TOKEN_VALUE_ONE and OCP_TOKEN_VALUE_TWO and the corresponding values. The problem comes when I try to pass a method variable and use it in an sh command.
I have the next code:
private def deployToOpenShift(projectProps, environment, openshiftNamespaceGroupToken) {
sh """/opt/ose/oc login ${OCP_URL} --token=${openshiftNamespaceGroupToken} --namespace=${projectProps.namespace}-${environment}"""
}
The problem is, the method deployToOpenShift has in the openshiftNamespaceGroupToken variable, a value that is the name of variable that has been set in Jenkins. It needs to be dynamic and the problem is that Jenkins don't resolve the Jenkins variable value, just the one passed as String, I mean, the result is:
--token=OCP_TOKEN_VALUE_ONE
If I put in the code
private def deployToOpenShift(projectProps, environment, openshiftNamespaceGroupToken) {
sh """/opt/ose/oc login ${OCP_URL} --token=${OCP_TOKEN_VALUE_ONE} --namespace=${projectProps.namespace}-${environment}"""
}
works perfect but is not dynamic that is the point of the method variable. I have tried with the """ stuff as you can see, but not working.
Any extra idea?
Edited with the code that calls the method:
...
projectProps = readProperties file: './gradle.properties'
openShiftTokenByGroup = 'OCP_TOKEN_' + projectProps.namespace.toUpperCase()
...
stage ('Deploy-Dev') {
agent any
steps {
milestone ordinal : 10, label: "Deploy-Dev Milestone"
deployToOpenShift(projectProps, 'dev', openShiftTokenByGroup)
}
}
I have got two different ways to do that. One is using evaluate from groovy like this:
def openShiftTokenByGroup = 'OCP_TOKEN_' + projectProps.namespace.toUpperCase()
evaluate("${openShiftTokenByGroup}") //This will resolve the configured value in Jenkins
The second one is the same approach but in the sh command with eval escaping the $ character:
sh """
eval \$$openShiftTokenByGroup
echo "Token: $openShiftTokenByGroup
"""
This will do the magic too and you'll get the Jenkins configured value.

Resources