Jenkins - How to read the environment variables in groovy post build step - jenkins

I am trying to read the environment variables in Groovy Postbuild step. I am able to read the values of parameters passed to builds but unable to read the values of parameters which are set in one of my Execute Windows batch command.
In one example of my Execute Windows batch command I do this:
SET custom_param=myValue
if I use ${custom_param} in other jenkins steps/jobs, it gets my value. So I am sure it has the value. I just can't get it in groovy script
I have tried followings to do so, none of them have worked:
manager.envVars['custom_param']
build.buildVariableResolver.resolve('custom_param')
build.getEnvironment(listener).get('custom_param')
Any help here would be great

(Assuming you're not running your script in groovy sandbox)
Try the bellow:
build = Thread.currentThread().executable
String jobName = build.project.getName()
job = Hudson.instance.getJob(jobName)
my_env_var = job.getLastBuild().getEnvironment()["YOUR_ENV_VAR"]

Groovy Post build step run as separate process. It has access to environment as normal JVM process.
You could use EnvInject plugin as a a build step. Subsequent steps in build will able to read this via normal environment access (System.env in your groovy script)

When you set some custom variables in your "Windows command batch" step, these variables are available only during this Jenkins step.
Once Jenkins move on the next step, your variables are lost...
If you want to set some variables permanently, you can try to use the SETX command:
What is the difference between setx and set in environment variables in Windows?

Related

Accessing Jenkins-set environment variables from a Jenkins Plugin

If there is a Jenkins shell script build step, environment variables are set so that, for example, if you echo $WORKSPACE you see the current working directory. I am writing a custom plugin which also can execute shell commands but WORKSPACE is not set when this plugin executes.
I could see that Jenkins sets all those env variables prior to executing the shell commands the Jenkins project specifies so that they would not be already set for a custom plugin. If that is the case, it would seem like there is no way to access those env variables.
But if there is a way to obtain the values of the env variables that would be useful.

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!

setting Environment from a file in Jenkins

My question is there any way to set up environment variables from a file during Jenkins build. I have a file called .xyz which has env variables.
I know there is a jenkins plugin but can we do it inside the execute shell box in jenkins??
I tried . .xyz but that doesn't work!
Thanks in advance
If you want to do it from inside Execute Shell step, you've got to write a shell script that will read the file line by line and add them to environment variables.
Assuming your properties file is of format:
var=value
A very basic version of the script would be:
while read line; do
export $line
done <your_props_file_name
The problem is, these variables will only be retained for the duration of that "Execute Shell" build step. Once you move to a different Build step or Post-build step (within the same job), they will be gone. This is Jenkins's cleanup by design.
That's why there is that EnvInject plugin, it takes care of maintaining the environment variables between the build steps.

Environment variable retrieve from NAnt script is not recognize in Jenkins nant build step

In my nant script I retrieve my environment variable in this way:
property name="ProjectSolutionPath" value="${environment::get-variable('MAIN_PROJECT_PATH')}"
but when I run it through jenkins using nant as build step I got an error like this.
Expression: ${environment::get-variable('MAIN_PROJECT_PATH')}
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Environment variable "MAIN_PROJECT_PATH" does not exist.
Is there configuration for this? so that Jenkins will recognize environment variables access by my nant script?
Help is greatly appreciated.
Make sure you define this environment variable in "System variables".
Since the Jenkins process usually runs as "NT AUTHORITY\SYSTEM" user, the environment variables associated with your user account do not get appended to the env-vars of the process.
I've seen this answer on how to add env-vars to a Jenkins build (though I don't like spawning a cmd line process), if you do not want to use sys-env-vars.

Preserve environment variables in Jenkins between Windows build commands

I am trying to set up Jenkins to continually check out and build code and verify that the code is compilable.
Our build system works like this: we have several different .bat files that set up environment variables for different build configurations, and then we execute gmake to actually build the code.
When I created Jenkins job, in Build part of the job I set up two "Execute windows batch command" commands: one that calls the script to set up env. variables, and gmake to build it.
Problem is, when gmake step runs, all environment variables are forgotten. How can I prevent env. variables from being cleared?
Tx
What if you set it up to call only one bat file instead? That one file can then call the two you're currently calling with Jenkins.

Resources