Jenkins Pipeline accessing environment variables - jenkins

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.

Related

access ENV_INJECT variables in Jenkins job DSL

I am unable to access any Jenkins environment Variables inside the groovy script of a JobDSL. I can see values of system environment variables.
Here is the groovy script I am running:
println(System.getenv("HOME"))
println(System.getenv("WORKSPACE"))
Here is the output:
/users/s051464
null
I have tried setting environment variables using Environment Injection and that doesn't work either (all set variables are null).
You should be able to use ${VAR_NAME}, more info here. One exception is node specific variables such as WORKSPACE, in those cases you need to do the following (from here):
hudson.FilePath workspace = hudson.model.Executor.currentExecutor().getCurrentWorkspace()

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}"

Environment variable in Jenkins Pipeline

Is there any environment variable available for getting the Jenkins Pipeline Title?
I know we can use $JOB_NAME to get title for a freestyle job,
but is there anything that can be used for getting Pipeline name?
You can access the same environment variables from groovy using the same names (e.g. JOB_NAME or env.JOB_NAME).
From the documentation:
Environment variables are accessible from Groovy code as env.VARNAME or simply as VARNAME. You can write to such properties as well (only using the env. prefix):
env.MYTOOL_VERSION = '1.33'
node {
sh '/usr/local/mytool-$MYTOOL_VERSION/bin/start'
}
These definitions will also be available via the REST API during the build or after its completion, and from upstream Pipeline builds using the build step.
For the rest of the documentation, click the "Pipeline Syntax" link from any Pipeline job
To avoid problems of side effects after changing env, especially using multiple nodes, it is better to set a temporary context.
One safe way to alter the environment is:
withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
sh '$MYTOOL_HOME/bin/start'
}
This approach does not poison the env after the command execution.

Run Jenkins job with different environment variable

I'm using jenkins 1.651. We have a Job which contains a shell. The shell contains:
echo ${VAR}
We are using the EnvInject plugin to define the content of our environment variable:
VAR=10
But sometimes we want to use another value for our env var:
VAR=20
Our env var must ben 10 in 50% of the cases, and 20 in the other 50%.
Is there a way or plugin which can help us to define easily how we want to run our job? With VAR=10 or VAR=20?
We don't want to put VAR=10 in comment, every time we want to run VAR=20 and vice versa. So preferably a way which works withouth going inside our job configuration.
See Use Jenkins > Parameterized Build:
The parameter are available as environment parameters. So e.g. a shell ($FOO, %FOO%) or Ant ( ${env.FOO} ) can access these values.
or the more sophisticated Extensible Choice Parameter plugin and Active Choices Plugin.

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