How to put JOB_NAME excluding folder into an environment variable in Jenkins? - 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}"

Related

Jenkins: Passing a variable between scripts, and accessing it on a post build actions

I have a Jenkins job, with SCM from bitbucket, two shell scripts, and a post build action publishing the result to Slack.
Naively I want to pass a concluded variable in the first shell script to the second, add some information to that variable in the second shell script, and then to append that variable to the Slack custom message.
I was expecting this to be a built in feature, and now spending few days on and off at it. I've tired the EnvInject, Environment Inject, Global Variable String Parameter plugins, but in any configuration I've tried it didn't work.
In some cases I got this error:
21:01:08 [EnvInject] - [ERROR] - The given properties file path 'build.properties' doesn't exist.
I know this file does not exist.. I expected the plugin to create it, so I can add new content to it in first shell script, and to be loaded in every other step of the job.
Am I missing something or misusing these plugins?
So like I've seen it happens too often, after asking the question, I was able to solve it like this:
First we create a shell script to create the file, I've already added a value:
Then we tell Jenkins to inject the variables from the build.properties file:
Then we change the value of the variable in the file:
Then AGAIN we tell Jenkins to inject the variables from the same file:
Then we can observe the value changes in the next shell:
Also in the post build action:
And success:

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!

modify PATH variable in jenkins master

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.

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