Jenkins Environment Variables
#90DaysOfDevOps
#Day25
What are Environment Variables in Jenkins?
Environment variables are global key-value pairs that Jenkins can access and inject into a project.
If different projects require using the same value then we do that by using the Global environment variable. Environment variables also help us to keep our user credentials secure.
How to list all the environmental variables in Jenkins?
pipeline{ agent any stages{ stage("Env Variables"){ steps{ sh "printenv" } } } }
Click Save
Click on Build Now on the left-hand side
Click on the build id > Console Output
How to create Jenkins Global Environment Variables?
Go to Jenkins Dashboard > Manage Jenkins
Click on System
Scroll down and select the Environment Variables option
Click Add and enter the environmental variable and its value and Save.
Now you can use this NAME environment variable in any file.
Jenkins Local Environment Variables
Jenkins local environment variables are variables that are set and used within a Jenkins job or pipeline. These variables can be used to store and access information that is specific to the current execution of the job or pipeline.
There are different ways to set local variables:
Using the withEnv Step: This step is used within a Jenkins pipeline to set environment variables for a specific stage or step.
withEnv(["variable name= variable value"])
Using the environment{} Block: This block can be used in a Jenkinsfile to define environment variables that are used throughout the pipeline.
environment { variable name = variable value }
Here DATE and TIME are global scope variables , therefore they can be used inside any Stage but TEST_VARIABLE has a local scope as it is created inside the stage
using the EnvInject Plugin: Environment variables can also be injected using EnvInject Plugin.
Inject environment variable using EnvInject
You can set local environment variables in Jenkins using the EnvInject Plugin by following these steps:
Go to Jenkins dashboard and click on "Manage Jenkins" > "Plugins".
In the "Available Plugins" tab, search for "EnvInject Plugin" and install it.
Navigate to the job that you want to set environment variables for, and either create a new job or edit an existing one.
Under the "Build Steps" section Click "Add build step" and select Inject environment variable
Now type enter your variable and its value in Properties Content and add your command in another shell.
Click on Save > Build Now
NOTE :
In Jenkins, the environment variables created using the EnvInject Plugin are not directly available as properties of the env
object. So ${env.MY_VARIABLE} was not used in the above code.
Thank you for reading!!