modify PATH variable in jenkins master - jenkins

I am trying to modify PATH in jenkins master node (i have no slaves).From "Global Properties -> Environment Variables" i add 2 entries: "PATH" with value "$PATH:/opt/foo" and "FOO" with value "BAR". Now when i run my free style job with execute shell build step being "echo $PATH;
echo $FOO" i see that PATH was not modified whereby FOO is displayed correctly.
Why is that?
Is there any way to modify PATH from jenkins global configuration ?
I managed to modify PATH on a job level via EnvInject plugin but what i am really looking for is to modify PATH for all jobs.

You are doing it right. The same Manage Jenkins => Global Properties => Environment variables works for me.
Please note that if you have the EnvInject plugin installed, it seems to mask the environment variables from Jenkins global configuration. So uninstall EnvInject and try again.

Jenkins also supports the format PATH+<name> to prepend to any variable, not only PATH:
This is also supported in the pipeline step withEnv:
node {
withEnv(['PATH+JAVA=/path/to/java/bin']) {
...
}
}
Just take note, it prepends to the variable. If it must be appended you need to do what the other answers show.
See the pipeline steps document here.
You may also use the syntax PATH+WHATEVER=/something to prepend /something to $PATH
Or the java docs on EnvVars here.

Running Jenkins 2.150.1 on Mac OS X installed with homebrew. I couldn't get the PATH environment to change by updating the PATH environment variable as described in some of the other answers here and on similar questions. In the end I updated the Jenkins installation's plist. I added the following to /usr/local/Cellar/jenkins-lts/2.150.1/homebrew.mxcl.jenkins-lts.plist:
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin</string>
</dict>
And then restarted the service:
brew services restart jenkins-lts

I was facing the same problem as my wsimport command was not being picked up by Jenkins master. This comes with Java, so I waned to append JAVA_HOME/bin to the PATH variable in jenkins master.
Environment name should be Path and not PATH. Please see attached image for the same, where I have ammeneded JAVA_HOME/bin to PATH variable

When appending to PATH variable through Jenkins (Manage Jenkins => Global Properties => Environment variables), use "Path", not "PATH" for the variable name.

Related

Unable to determine what the withEnv is doing in Jenkinsfile

I have just started writing Jenkinsfile. I was viewing the following two URLs to learn how to build a Java application, push it to Nexus and then invoke Ansible to deploy.
Redhat Jenkinsfile description
Actual Jenkinsfile
In the second link the following is mentioned several times whose function I am unable to understand:
withEnv(["PATH+MAVEN=${tool 'm3'}/bin"])
What I can find from net is that withEnv is used to create/override a environment variables. But what is ${tool 'm3'}/bin doing? Normally the syntax of withEnv is VARIABLE_NAME=value/expression.
The ${} is substituting a command/variable into the GString. See groovy docs on string Interpolation
From the looks of it, it would be safe to assume tool 'm3' is returning the install path which then gets /bin appended.
So the end result would be
PATH+MAVEN=/my/path/to/m3/etc/bin
Additionally to #metalisticpain's answer, there's some background configuration to the tools directive on the Jenkins server itself that configures the installation paths to be used.
Let's say you have jdk-1.8.0 installed as a tool name on the Jenkins server, then it can be used in the Jenkinsfile as such in your example:
withEnv(["PATH+JDK=${tool 'jdk-1.8.0'}/bin"])
Taken from the documentation linked above:
The tool name must be pre-configured in Jenkins under Manage Jenkins → Global Tool → Configuration.

How to put JOB_NAME excluding folder into an environment variable in Jenkins?

I want to put the name of the currently executing Jenkins job into an environment variable for use later in my pipeline, without the folder name. I'm assuming I need something like :
withEnv(['JOB_BASE_NAME=JOB_NAME.split('/').last()']) {
echo "Job base name: ${JOB_BASE_NAME}"
}
but I get an error:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException:
unclassified method java.lang.String div java.lang.String
In Jenkins documentation, you have the §Using environment variables section which mentions:
The full list of environment variables accessible from within Jenkins Pipeline is documented at localhost:8080/pipeline-syntax/globals#env, assuming a Jenkins master is running on localhost:8080
If you follow the link you can find that JOB_BASE_NAME is already provided OOTB by Jenkins so this is exactly what you want.
JOB_BASE_NAME -
Short Name of the project of this build stripping off folder paths, such as "foo" for "bar/foo".
I worked it out. In case anyone finds it useful:
def jobBaseName = "${env.JOB_NAME}".split('/').last()
echo "Job Name (excl. path): ${jobBaseName}"
might be too late, but thought would help someone in need for a simpler solution using bash.
${JOB_NAME%%/*}
Example:
I have a project created with name: poc_jenkins_pipeline
If i try accessing default jenkins variable ${JOB_NAME}
it returns value poc_jenkins_pipeline/develop i.e. <project name>/<branch name>
By using % operator in bash ${JOB_NAME%%/*} returns value poc_jenkins_pipeline
Reference Link - https://qa.nuxeo.org/jenkins/pipeline-syntax/globals
If you want the name of Jenkins job without the folder name you can use:
def job = "${JOB_BASE_NAME}"

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.

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.

How to get the jobname from jenkins

Is there a way to get the jobname for the current build in jenkins and pass it as a parameter to an ant build script?
Jenkins sets some environment variables such as JOB_NAME (see here) for more details on the variables set.
You can then access these in ant via ${env.JOB_NAME}.
Edit: There's also a little howto for environment variables on the same page here.
A similar issue, I was looking for job name for shell script.
In the 'Execute shell' > 'Command' textbox,
both the below worked for me:
echo $JOB_NAME
echo "$JOB_NAME"
You may set special variable for that based on global variable. Simple:
THEJOB="${JOB_NAME.substring(JOB_NAME.lastIndexOf('/') + 1, JOB_NAME.length())}"
Now $THEJOB is your job name
If you can run any Job, you can easily go to the Build section of that job and go to environment variables and see all the information there.
Nowadays there is an environment variable JOB_BASE_NAME which contains the last component of JOB_NAME.
For example: if JOB_NAME contains Cool_Jobs/Very_Cool_Jobs/The_Coolest then JOB_BASE_NAME will just contain The_Coolest

Resources