How to set environment variables in Jenkins?

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:

Global properties

  1. Go to your Jenkins dashboard and click on "Manage Jenkins" on the left-hand side.

  2. Click on "Configure System" to access the global configuration settings.

  3. Scroll down to the "Global properties" section and check the box that says, "Environment variables".

  4. Here, you can define environment variables by adding key-value pairs.

widget

Pipeline script

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 any
environment {
MY_SECRET_KEY = "!@#hello#@!"
}
stages {
stage('Build') {
steps {
script {
env.ANOTHER_VARIABLE = "another_value"
echo "Setting environment variables"
sh 'export ADDITIONAL_VARIABLE="additional_value"'
}
}
}
}
}

EnvInject Plugin

To inject environment variables during the build startup in Jenkins, you can utilize the EnvInject plugin. Follow these steps:

  1. Open the build configuration window for your Jenkins job.

  2. In the "Add build step" combo box, select the option for "Inject environment variables."

  3. 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.

  4. Add the required environment variables by specifying their key-value pairs in the properties content text box.

  5. Save the build configuration.

widget
Copyright ©2024 Educative, Inc. All rights reserved