Environment variables in Jenkins are global key-value pairs that can be accessed and injected into a project. They are a valuable tool for automating different parts of the software development life cycle (SDLC).
Here are some of the roles of environment variables in Jenkins:
Storing sensitive data: Environment variables can be used to store sensitive data, such as passwords or API keys. This data can then be accessed by build scripts or other tools without having to hard code it into the project code.
Configuring the build environment: Environment variables can be used to configure the build environment, such as the path to the source code or the location of the build artifacts.
Passing data to build steps: Environment variables can be passed to build steps, such as Maven or Gradle commands. This can help to make build steps more reusable and flexible.
There are several ways to set environment variables in Jenkins. Here are some of the most common methods:
Go to your Jenkins dashboard and click on "Manage Jenkins" on the left-hand side.
Click on "Configure System" to access the global configuration settings.
Scroll down to the "Global properties" section and check the box that says, "Environment variables".
Here, you can define environment variables by adding key-value pairs.
You can also set environment variables in a pipeline script. To do this, you can use the environment
block to define the environment variables. For example, the following code defines an environment variable named MY_SECRET_KEY
with the value !@#hello#@!
:
pipeline {agent anyenvironment {MY_SECRET_KEY = "!@#hello#@!"}stages {stage('Build') {steps {script {env.ANOTHER_VARIABLE = "another_value"echo "Setting environment variables"sh 'export ADDITIONAL_VARIABLE="additional_value"'}}}}}
To inject environment variables during the build startup in Jenkins, you can utilize the EnvInject plugin. Follow these steps:
Open the build configuration window for your Jenkins job.
In the "Add build step" combo box, select the option for "Inject environment variables."
This will enable the usage of the EnvInject plugin. In the subsequent "properties content" text box, you can specify the environment variables you want to inject.
Add the required environment variables by specifying their key-value pairs in the properties content text box.
Save the build configuration.