Run Jenkins job with different environment variable - jenkins

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.

Related

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.

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.

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

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?

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

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.

Resources