Environment variable in Jenkins Pipeline - jenkins

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.

Related

Get variables set in build.gradle in Jenkins pipeline build

I have a Jenkins pipeline job that builds my project using gradle. As part of the build i would like to use a global variable I have set in the build.gradle file
project.ext.set("MyVar", "My Value")
How can i access this variable in the pipeline build, so
myVar = varSetInGradleBuild
Hope that makes sense
Thanks
Well, usually dependency is reverse, Jenkins sets variables for build to control behavior with -P key.
For your use case you can define variables in gradle.properties file and read it in Jenkins pipeline.

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.

Using parameterized credentials in Jenkins

Say I've got dev, qa, and stable server environments for some web app, with corresponding git branches. Each environment should be continuously integrated. Each of these environments has a separate username/password pair used to publish the app. I would like to make a Jenkins multiconfiguration (matrix) job to publish to all of these environments. The publishing almost certainly must be done with a shell script.
My failed attempt consisted of using the Jenkins Credentials and Credentials Binding plugins. Credentials Binding provides a way to inject credentials as environment variables using a parameter. However, setting this parameter dynamically (i.e., something like if ENV == dev: CREDS = CREDS_dev) doesn't appear to be possible. Build scripts happen afterwards, and even using the Environment Script plugin doesn't work.
Is there any way for this to happen?
Had similar situation and used groovy script with parameterized build (https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin). In my case I had a choice parameter defined as "DEPLOY" and had different values, like "Test", "Release", then in the following groovy script (Evaluated Groovy script):
if ("Test".equals(DEPLOY)) {def map = [DEPLOY_URL: "http://someurl", DEPLOY_STORAGE: "testaccount"]; return map }
You should be able to specify your credentials in here or copy env variables. After that you can access these variables in windows batch command using:
echo %DEPLOY_URL%
echo %DEPLOY_STORAGE%
I also had another choice parameter defined "Deploy.Branch", with values of "dev" and "master". And used it as a parameter to Branches to Build, the value was set to (if you want to dynamically specify branch based on parameters):
*/${Deploy.Branch}
Hope this helps.
Here's what I ended up doing. It's kind of a workaround for what I would argue is a flawed design or missing use case in Jenkins.
Redid my creds so they have standard IDs (this is in the Advanced part and you can't set it after creation)
Matrix job runs a trivial script to figure out what env maps to what creds ID, then triggers...
The main job that does the deployment

Jenkins plugin cannot see variables set using the withEnv workflow step

I want the gradle plugin to pick up environment variables that are set in a withEnv step (or other wrapper-types). When I invoke gradle using a sh step the variable is found, but when I use the gradle plugin it is not.
The gradle plugin performs the equivalent of this:
EnvVars env = run.getEnvironment(taskListener);
launcher.launch().cmds(args).envs(env).stdout(gca)
.pwd(rootLauncher).join();
The javadoc for run.getEnvironment() states:
Returns the map that contains environmental variables to be used for
launching processes for this build. BuildSteps that invoke external
processes should use this. This allows BuildWrappers and other project
configurations (such as JDK selection) to take effect.
Unlike earlier getEnvVars(), this map contains the whole environment,
not just the overrides, so one can introspect values to change its
behavior.
If I debug the plugin I see that there are less than a dozen variables in the environment passed to the gradle invocation, none of which are the variables withEnv should be providing. To the best I could tell, the sh step uses a completely different extension point, and is straight up given an instance of EnvVars that appears to be much more complete. I'm fairly certain the problem isn't in withEnv, but I don't see how to fix the gradle plugin.
Am I using the wrong call? Or perhaps the wrong extension point?
Do not call Run.getEnvironment. Rather use the EnvVars passed to SimpleBuildStep.perform.

Up to what extent can I use environment variables in Jenkins jobs?

I have a lot of jobs that contain very similiar configuration values.
Then I had the idea to use the EnvInject Plugin to read a generated Properties file, which contains most of my configuration.
However, I don't know up to what extent I can use environment variables in a Jenkins job configuration.
For instance, in a Maven job, I can specify the Root POM to be ${JOB_NAME}/pom.xml. Jenkins will tell me it can't find the file, but the job actually works.
Configuring other parts (like the number of builds to keep) fails miserably (the variable is simply removed).
So does anyone have experience in using environment variables to cut down the copy/paste configuration in Jenkins?
If your objective is to cut down on cut and paste then the job dsl plugin might suit your needs better.
You can build a template job (using statement) then use that to build your main jobs.
Modified from the tutorial
job {
name 'DSL-Tutorial-1-Test'
using 'seed-job'
scm {
git('git://github.com/jgritman/aws-sdk-test.git')
}
triggers {
scm('*/15 * * * *')
}
steps {
maven('-e clean test')
}
}
In addition if you need to change all the jobs you can change your template and rebuild the main jobs

Resources