Jenkins file can we use the IF statement - jenkins

in Jenkins file one of the variable is having the comma separated values like below.
infra_services=[abc,def,xyz]
when I write the below code it was throwing an error.
if ("{$Infra_Services}".contains("xyz"))
then
echo "$Infra_Services"
fi

yes you can do if statements in a Jenkinsfile. However if you are using declarative pipeline you need to brace it with the step script.
Your issue comes from the fact you did not put any double quotes around "abc" and all the elements of your array
infra_services=[abc,def,xyz]
​
A second error will raise after you fix this. If infra_services is an array, to manipulate it you should not try to cast it as string. It should throw when you do "{$Infra_Services}"
here is a working example
​def Infra_Services = ["abc","def","xyz"]
if (Infra_Services.contains("xyz")) {
println "found"
}​​
My advice is to test your groovy before running it on jenkins, you will gain precious time. Here is a good online groovy console I use to test my code. running the groovy console from terminal is an alternative
https://groovyconsole.appspot.com/

Related

Expand variable inside Jenkins pipeline tool directive

I would like to be able to programmatically decide which tool will be installed in an Agent for a Jenkins pipeline.
This is something I have that's working today:
withEnv(["JAVA_HOME=${tool 'OPENJDK11'}",
"PATH+JAVA=${tool 'OPENJDK11'}"]) {
... do stuff ...
}
So I have a global tool OPENJDK11 installed, along with OPENJDK14, and now I would like to change the Groovy script to be able to decide which JDK to install.
So before the part above I have saved the name of the tool in a variable jdkToInstall, how am I able to reference this variable inside the tool directive?
I have tried:
${tool '${jdkToInstall}'} and ${tool '$jdkToInstall'}.
That doesn't expand my variable, so I get an error message saying it can't find the tool "$jdkToInstall".
I also tried with string concatenation, but that ended up with a similar error message with my plus and everything.
It is sufficient to expand (${}) the variable only once. Following works as expected:
withEnv(["JAVA_HOME=${tool jdkToInstall}", "PATH+JAVA=${tool jdkToInstall}"]) {
... do stuff ...
}

VS Code Jenkinsfile docker.withRegistry {...} brackets do not match error

I'm writing a jenkinsfile in VS Code and when I use docker.withRegistry("some.registry"){...} I get a brackets do not match error inside of code. It parses fine inside jenkins, but this error inside of code is bugging me a lot. As soon as anything goes between the {} I get the error show up on the closing bracket.
Even copying in directly from the documentation from the Jenkins website gives the same issue.
Any ideas?
Oddly enough I had the same issue when I was using a private registry with a credentials ID, when I switched away from single quotes to double quotes the error went away, you could give that a try?
docker.withRegistry("https://some.registry", "docker-registry-creds") {
def customImage = docker.build("my-image:${env.GIT_COMMIT}")
}
As mentioned by Carl here, this happens when you have the following 2 characters, in this particular order, in a single quoted string:
'/*'
So strings like the following will trigger the error:
'**/*.xml'
'/some/path/to/random/files/*.py'
Just use double quote in those strings, and all the errors will go away:
"**/*.xml"
"/some/path/to/random/files/*.py"
I noticed this also occurs when using a parenthesis in single quotes. Again fixed by putting these in double quotes.
e.g.:
def something= somethingelse.tokenize('(')
can be replaced by
def something= somethingelse.tokenize("(")

Pass Jenkins build number to Protractor for SauceLabs

I am running protractor test cases through Jenkins, and using SauceLabs as execution environment. I am using Protractor-Cucumber-Framework. I want to pass build number from Jenkins so that I can pass same to SauceLabs to organize my test execution results.
I tried params as mentioned in this post
https://moduscreate.com/blog/protractor_parameters_adding_flexibility_automation_tests/
in Config.js
params: {
buildNumber:'xyz'
}
for running protractor :
protractor config/config.js --parameters.buildNumber= 1.1 --disableChecks"
using :
browser.params.buildNumber
This gives buildnumber =xyz and not 1.1
Could you please help me here
Update:
Sorry forgot to mention that I am using browser.params.buildNumber in after hook of cucumberjs.
you should use pattern: --params.xxx in cmd line, rather than --parameters.xxx.
In your case, should be: protractor config/config.js --params.buildNumber=1.1 --disableChecks
Note: Don't insert blank space around the =, like --params.name = value, or --params.name= value.
If the parameter value has blank space, you should use double quote to wrapper it, like --params.name="I like to xxx"

Evaluate large Groovy script in in GroovyShell

I'm using GroovyConsole to evaluate scripts I get from external sources. So the code to evaluate is dynamic and I don't have control over it. Actually is written into a database and I have to read it as a String. Not perfect, but that's how it is.
What I'm doing right now:
private GroovyShell shell
def processScript( def script){
if (script) {
try{
shell.evaluate (script, 'some_random_name')
}catch( e ){
log.warn "Could not process script: $e"
}
}
}
This usually works. But now we got a large script (~3000 LOC) and it throws java.lang.RuntimeException: Method code too large! because the script is larger than 64K.
I tried to dump the script into a file and use a BufferedReader, but it throws the same Exception.
So is there a better way to evaluate dynamic Groovy code from within a Groovy method?
The problem is your script reach the java limit for a method. I think the only solution is to split your script in many scripts in some way.
See this answer

How to specify a value for a Jenkins environment variable that contains a space

I am trying to specify a value for a Jenkins environment variable (as created on the Manage Jenkins -> Configure System screen, under the heading "Global properties") which contains a space. I want to use this environment variable in an Execute Shell build step. The option that I need to appear in the command line in the build step is:
--platform="Windows 7"
The syntax I am using on the command line is --platform=${VARIABLE_NAME}
No matter how I attempt to format it, Jenkins seems to reformat it so that it is treated as two values. I have tried:
Windows 7
"Windows 7"
'Windows 7'
Windows\ 7
The corresponding results, when output during the Execute Shell build step have been:
--platform=Windows 7
'--platform="Windows' '7"'
'--platform='\''Windows' '7'\'''
--platform=Windows/ 7
I have also tried changing my command line syntax to --platform='${VARIABLE_NAME}' as well as '--platform=${VARIABLE_NAME}', but in each of those cases the ${VARIABLE_NAME} is not resolved at all and just appears as ${VARIABLE_NAME} on the resulting command.
I am hoping there is a way to make this work. Any suggestions are most appreciated.
You should be able to use spaces without any special characters in the global properties section.
For example, I set a variable "THIS_VAL" to have the value "HAS SPACES".
My test build job was the following:
#!/bin/bash
set +v
echo ${THIS_VAL}
echo "${THIS_VAL}"
echo $THIS_VAL
and the output was
[workspace] $ /bin/bash /tmp/hudson8126983335734936805.sh
HAS SPACES
HAS SPACES
HAS SPACES
Finished: SUCCESS
I think what you need to do is use the following:
--platform="${VARIABLE_NAME}"
NOTE: Use double quotes, not single quotes. Using single quotes makes the stuff inside the quotes literal, meaning that any variables will be printed as is, not parsed into the actual value. Therefore '${VARIABLE_NAME}' will be printed as is, not parsed into "Windows 7".
EDIT:
Based on #BobSilverberg comment below, use the following:
--platform="$VARIABLE_NAME"
Note: no curly brackets.

Resources