I am extracting the username/password from credential store and I am assigning it to a variable. I want to write this value in a file.
I am using the below code:
for (creds in jenkinsCredentials) {
if(creds.id == "credential"){
def password = creds.password
println(creds.username)
println(password)
writeFile file: '\\Jenkins_Home\\workspace\\test\\test.properties', text: 'pass=${password}'
It prints the value of password.
But it just writes pass=${password}, not the value of the password.
How can I write the values of the variable in the file?
Try the double quotes as mentioned by Sriram. He is correct that pipeline groovy script does have issue with single quotes.
Also found sometimes that double quotes can also be an issue and that they have to be escaped (\"). See how you go!
I also have another solution, where you can define the text going into the file as a variable and enclosing the writeFile arguments in brackets, see below:
in jenkinsCredentials) {
if(creds.id == "credential"){
def password = creds.password
println(creds.username)
println(password)
def pass = "pass=" + password
writeFile (file: '\\Jenkins_Home\\workspace\\test\\test.properties', text: pass)
Use double quotes (") instead of single quotes (') as below:
writeFile file: "\\Jenkins_Home\\workspace\\test\\test.properties", text: "pass=${password}"
For some reason, pipeline groovy script has some issue with single quotes(')
Related
I have a Jenkinsfile which I want to load variables into from a file during execution of the build, I also want to concatenate the variable into one line and print it out.
pipeline {
agent any
stages {
stage("foo") {
steps {
script {
env.name = readFile 'name.txt'
env.tag = readFile 'tag.txt'
}
echo "${env.name}:${env.tag}"
}
}
}
}
name.txt contains Uzodimma
path.txt contains latest
When I run the pipeline, I get
Uzodimma
:latest
I expected
Uzodimma:latest
Is there a way I can do this in Jenkinsfile?
The issue here is that your files have newline characters in them, so they are assigned to your variables as part of the String. You can remove the newlines with the trim method since readFile returns a String:
env.name = readFile('name.txt').trim()
env.tag = readFile('tag.txt').trim()
and the returned standard out will be as you expect.
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 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]}
def a = "a string"
def b = 'another'
Is there any difference? Or just like javascript to let's input ' and " easier in strings?
Single quotes are a standard java String
Double quotes are a templatable String, which will either return a GString if it is templated, or else a standard Java String. For example:
println 'hi'.class.name // prints java.lang.String
println "hi".class.name // prints java.lang.String
def a = 'Freewind'
println "hi $a" // prints "hi Freewind"
println "hi $a".class.name // prints org.codehaus.groovy.runtime.GStringImpl
If you try templating with single quoted strings, it doesn't do anything, so:
println 'hi $a' // prints "hi $a"
Also, the link given by julx in their answer is worth reading (esp. the part about GStrings not being Strings about 2/3 of the way down.
My understanding is that double-quoted string may contain embedded references to variables and other expressions. For example: "Hello $name", "Hello ${some-expression-here}". In this case a GString will be instantiated instead of a regular String. On the other hand single-quoted strings do not support this syntax and always result in a plain String. More on the topic here:
http://docs.groovy-lang.org/latest/html/documentation/index.html#all-strings
I know this is a very old question, but I wanted to add a caveat.
While it is correct that single (or triple single) quotes prevent interpolation in groovy, if you pass a shell command a single quoted string, the shell will perform parameter substitution, if the variable is an environment variable. Local variables or params will yield a bad substitution.
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.