Jenkins Pipeline: use Windows environment variable with '(' in it - jenkins

In my Jenkins pipeline I want to access the Windows environment variable named "ProgramFiles(x86)". However, I do not know what syntax I have to use to make Jenkins pipeline understand that the '(x86)' is part of the environment variable name. I keep getting an error with for example "echo env.ProgramFiles(x86)
groovy.lang.MissingPropertyException: No such property: x86 for class: groovy.lang.Binding
I also tried
echo "${ProgramFiles(x86)}"
and
echo "${env.ProgramFiles(x86)}"
but no success there either.

you can use single quotes around the variable name see below example:
echo "${env.'ProgramFiles(x86)'}"

Related

Workspace variable not printing in Jenkins Pipeline post step

i have configured a Jenkins pipeline job as follows
and env.WORKSPACE works fine
steps {
script
{
echo "${env.WORKSPACE}"
}
}
during build ouput is /home/mach1/workspace
but when i added some lines in post build stage in jenkins pipeline job.
it is returning the following error ${FILE,path="echo "${env.WORKSPACE}"/dir1/file2.html"}
script
{
echo "${env.WORKSPACE}"
}
}
post{
success{
script{
body:'${FILE,path="${env.WORKSPACE}/dir1/file2.html"}'
}
}
}
may i know where its getting wrong, or how do i correct so that in post step it takes /home/mach1/workspace/dir1/file2.html
A shell environment variable is referenced as a key within the env Map within Jenkins Pipeline Groovy, and as a string within the shell step method. In your original example, you referenced the variable as a Groovy variable, and interpolated it within the pipeline with the correct " syntax. However, in your second example, you are still referencing the variable as a Groovy variable, but attempting to interpolate it within the executed shell command from the step method. This will not work, as you will pass a literal string of the env Map variable.
You can fix this either by referencing the environment variable as a shell environment variable by removing the env Map key:
body:'${FILE,path="${WORKSPACE}/dir1/file2.html"}'
or by interpolating the Groovy variable within the pipeline:
body:"\${FILE,path=\"${env.WORKSPACE}/dir1/file2.html\"}"
where characters are properly escaped to denote a shell variable FILE as opposed to a Groovy variable, and for the embedded ".
The first correction is, of course, easier to read, and probably what you will prefer.

How to set multiple environmental variable with Jenkins Groovy Script

I am trying to use Jenkins environmental variable with groovy scripts and assign them to environment variable so I can use those variable through out each Jenkins steps. But I cannot take out Groovy map objects. Is there anything I am doing wrong?
this is simple. In groovy script I have added two keys as "repo" and "version". Environment variables are created from that name and in a shell, I can get those simply by calling their keys.
echo $repo
echo $version

Accessing environment variables in Extended Choice Parameter

I want to write a Groovy script for Extended Choice Parameter that would use access WORKSPACE variable. When I try:
List<String> artifacts = new ArrayList<String>()
artifacts.add(env.WORKSPACE)
asdf = env.WORKSPACE
println asdf
return artifacts
I get the following error:
No such property: env for class: _1775dc8d170bd01576ff2b650850017e
groovy.lang.MissingPropertyException: No such property: env for class: _1775dc8d170bd01576ff2b650850017e
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at org.codehaus.groovy.runtime.callsite.PogoGetPropertySite.getProperty(PogoGetPropertySite.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:307)
at _1775dc8d170bd01576ff2b650850017e.run(_1775dc8d170bd01576ff2b650850017e:2)
at groovy.lang.GroovyShell.evaluate(GroovyShell.java:585)
at com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition.executeGroovyScript(ExtendedChoiceParameterDefinition.java:727)
at com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition.executeGroovyScriptAndProcessGroovyValue(ExtendedChoiceParameterDefinition.java:709)
at com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition.computeValue(ExtendedChoiceParameterDefinition.java:676)
at com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition.computeEffectiveValue(ExtendedChoiceParameterDefinition.java:855)
at com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition.getParameterDefinitionInfo(ExtendedChoiceParameterDefinition.java:1451)
at jdk.internal.reflect.GeneratedMethodAccessor701.invoke(Unknown Source)
What am I doing wrong?
Also, will I be able to call a python script from this plugin, that would provide me list of parameters that I wish to use?
The env is available in the environment of a Jenkins build. The extended choice groovy script runs before your build, as you are entering the parameters. It runs in a GroovyShell environment, and all it can do is run a simple script to render the choices for the parameter. For example, if you are creating a multi select parameter, the script to generate the choices could be:
return ["DEV environment", "TEST environment", "PROD environment"]
So you can use env.WORKSPACE in your Jenkinsfile or pipeline script, but in the extended choice parameter script box, it isn't defined.
According to this this answer, you should be able to use something like
System.getEnv().get('WORKSPACE')
But I couldn't get that to do what you want.

Jenkins Pipeline accessing environment variables

I'm trying to use DSL pipelines in Jenkins. I thought it'd be nice if I could use the project name as part of my script.
git credentialsId: 'ffffffff-ffff-ffff-ffff-ffffffffffffff',\
url: "${repo_root}/${JOB_NAME}.git"
I get the error:
groovy.lang.MissingPropertyException: \
No such property: JOB_NAME for class: groovy.lang.Binding
I thought I followed these directions, and they mention JOB_NAME as one of the variables.
I decided to try:
sh 'env'
in my DSL, and this prints out:
JOB_NAME = foo-bar
which is what I expect.
Another blog mentions:
Usage of environment variables
We have two ways to get their value. The properties passed by -D= during the startup we could read as System.getProperty("key") thanks to the Groovy's strong relation with Java.
Reading normal environment variables in Java way is the System.getenv("VARIABLE")...
Let's try this:
println "JOB_NAME = " + System.getenv('JOB_NAME');
Now, I get:
java.lang.NullPointerException: Cannot get property 'System' on null object
Null object? But, I can see that JOB_NAME is an environment variable!
How do I read in the $JOB_NAME into a DSL script in a Pipeline job. I am trying a Pipeline job, and when I get that working will make this a Multibranch Pipeline with a Jenkinsfile.
All environment variables are accessible using env, e.g. ${env.JOB_NAME}.
Okay this really vexed me for a while today. Ultimately, I was being done in by a couple of things:
Single-quoted strings in Groovy mean "don't evaluate variables," just like it does in bash
Using $ interpolation is completely unnecessary if you're just referencing the variable, so you can just do env.JOB_NAME.
This SO question proved to be the one that helped me crack the code: Jenkins Workflow Checkout Accessing BRANCH_NAME and GIT_COMMIT
Indeed just use ${env.JOB_NAME} to access a known variable.
However if you need to access environment variable where name is given by another variable (dynamic access), just use env["your-env-variable"].
I had the problem where I configured 3 environment variables (in Jenkins -> Administer -> Configure System -> Environment variables), let's name them ENV_VAR_1, ENV_VAR_2, ENV_VAR_3.
Now I want to dynamically access them, I can do as such :
def envVarName = "ENV_VAR_" + count // Suppose count is initialized in a loop somewhere above...
def value = env[envVarName] // Will be resolved to env["ENV_VAR_1"] depending on count value
My environment variables in Jenkins configuration look like this :
I had an issue with this not working. The globally set properties/environment variables were only available inside a node step. It's a bug in version 2.4 of Pipeline plugin. Upgrade to 2.5 if you face this issue and your global properties will be available anywhere in the script. I've posted this to the Jenkins wiki here with the test script I used.

Parameterised build in jenkins: Not getting parameters as shell env variables

Jenkins version: 2.6, Linux
Problem: The parameterized build variables are not are not visible (as env variables) in the Execution step "shell script", They used to be visible in the older 1.x jenkins version.
Steps:
Create a parameterized build with a multi configuration project.
Add a parameter to the build (using This project is parameterized-> string parameter, {if that matters} ).
Add a build step "Execute shell" to the job.
Access these parameters in this shell script as env variables.
echo "++++++++++++ building $lib_name ($lib_version) ++++++++++++++"
To solve this, I have tried to create a groovy script in "Prepare an environment for the run" section. I created env variables using hardcoded values which are pased to shell script as env vars.
def map = ['lib_name':'lib1']
map['lib_version'] = 'master'
return map
But, without hardcoding, I cannot access these variable values even when using solution from
How to retrieve Jenkins build parameters using the Groovy API?
I dont know what else has to be done. Can some one please suggest?
---> Updating based on the comments on this question:
When I run the following lines in jenkins, I get exception:
def buildVariablesMap = Thread.currentThread().executable.buildVariables
buildVariablesMap.each{ k, v -> println "${k}:${v}" }
FATAL: No such property: executable for class: hudson.model.OneOffExecutor
groovy.lang.MissingPropertyException: No such property: executable for class: hudson.model.OneOffExecutor
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
at org.codehaus.groovy.runtime.callsite.GetEffectivePojoPropertySite.getProperty(GetEffectivePojoPropertySite.java:66)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:296)
I have had also similar problem. This is a solution which worked for me. I created a method which always takes and delivers exactly one build parameter which I need.
method:
String readingBuildParameters(VariableResolver varRes, String paramName){
return varRes.resolve(paramName)
}
the line how I use it in a code:
Build currentBuild = Executor.currentExecutor().currentExecutable
VariableResolver varResolver = currentBuild.getBuildVariableResolver()
df_parameter = readingBuildParameters(varResolver, "parameter_name")
BR,
Zoltan
To access the parameters in your shell script:
to evaluate them in echo: e.g. echo "${myParam}"
to use them in code: def myNewvalueParam = ${myOtherParam}
To retrieve build variables from groovy script as a build step:
def buildVariablesMap = Thread.currentThread().executable.buildVariables
println buildVariablesMap['BUILD_NUMBER']
But please note that for your custom/altered environment variables to be visible for the next steps you should use EnvInject plugin, with it you can define a step that will export new env variables as key-value pair just like properties file.
This was a bug in jenkins, probably in the credentials plugin:
https://issues.jenkins-ci.org/browse/JENKINS-35921
Thanks for all your help!

Resources