Environment variables are a fundamental part of any CI/CD pipeline, enabling flexible and dynamic configurations across different build environments.
In Jenkins, environment variables play a crucial role by providing a way to customize jobs, control build processes, and pass important data across different stages of a pipeline.
Overview
Types of Jenkins Environment Variables
- Local Environment Variables
- Global Environment Variables
- Built-in Environment Variables
- Custom Environment Variables
Setting Environment Variables
Jenkins Environment Variables can be set in the following ways:
1. Through Jenkins UI (Global and Per-Job)
- Global Environment Variables
- Per-Job Environment Variables
2. In Jenkinsfiles
3. Using the Environment Directive
4. With withEnv in Scripted Pipelines
Usage of Jenkins Environment Variables:
- Using Variables in Freestyle Projects
- Using Variables in Pipeline Scripts (Declarative & Scripted)
This guide explains about environment variables and how they can significantly enhance the automation process.
What are Environment Variables in Jenkins?
Environment variables in Jenkins are key-value pairs that influence the behavior of jobs and pipelines during execution. They act as placeholders for dynamic information such as build numbers, workspace locations, branch names, and user-defined data.
These variables can be predefined by Jenkins, set globally across all jobs, or customized within specific projects.
By leveraging environment variables, Jenkins users can make jobs more flexible and reusable. Variables can dictate how scripts run, pass critical information between stages, and adapt workflows based on the build context.
Whether managing credentials, controlling deployment targets, or adjusting test configurations, environment variables form a critical backbone for continuous integration and continuous delivery (CI/CD) pipelines.
Common Use Cases of Jenkins Environment Variables
Jenkins environment variables are used across a wide range of scenarios to enhance the automation, flexibility, and control of CI/CD pipelines. Some of the most common use cases include:
- Dynamic Configuration: Environment variables allow builds to adapt dynamically based on different parameters, such as branch names, build numbers, or environment types (e.g., staging, production).
- Credential Management: Sensitive information like API keys, passwords, and tokens can be securely injected into the build environment using environment variables, avoiding the need to hardcode them into scripts.
- Cross-Stage Data Sharing: In multi-stage pipelines, environment variables enable the passing of information (such as artifact paths or status flags) from one stage to another.
- Conditional Execution: Environment variables can be used to control the flow of a pipeline, enabling or skipping stages based on specific conditions, like environment or build status.
- Integration with External Tools: Variables facilitate integration with external systems like version control platforms, cloud services, or test management tools by dynamically supplying configuration data.
- Debugging and Logging: Environment variables help capture runtime details such as workspace locations or build identifiers, making it easier to debug and track builds.
Read More: CICD with Jenkins
Types of Jenkins Environment Variables
Jenkins offers different types of environment variables that cater to various scopes and use cases. Recognizing these types helps configure jobs and pipelines efficiently.
Local Environment Variables
Local environment variables are defined and used within a single build or script execution. They are temporary and accessible only during the job’s runtime. For example, a variable declared inside a pipeline script or a shell step exists only for that job instance.
Global Environment Variables
Global environment variables are configured at the system level through the Jenkins UI or global configuration files. Once defined, they are accessible to all jobs and pipelines across the Jenkins server. Common examples include variables like JAVA_HOME or MAVEN_HOME, which point to important tools required during builds.
Built-in Environment Variables
Jenkins automatically provides a set of built-in environment variables during every build. These include important information such as:
- BUILD_NUMBER: The unique number of the build.
- JOB_NAME: The name of the project.
- WORKSPACE: The absolute path to the build workspace.
- GIT_COMMIT: The commit ID being built (if using Git).
These built-in variables help dynamically control and report on the build process.
Custom Environment Variables
Custom environment variables are user-defined variables created to meet specific job requirements. They can be set through the Jenkins UI, within pipeline scripts, or by using plugins. Examples include variables for deployment environments, API endpoints, or feature flags needed during builds.
Setting Environment Variables
In Jenkins, environment variables are essential for managing configurations, passing data, and controlling various aspects of builds and pipelines.
There are several ways to set environment variables depending on the scope and requirements of the project. Here are some of them:
1. Through Jenkins UI (Global and Per-Job)
Global Environment Variables
Global environment variables are set in the Jenkins system and apply to all jobs across the entire Jenkins instance. These are useful for setting values that need to be consistent for all jobs, such as paths to essential tools (e.g., JAVA_HOME) or version control configurations.
Steps:
- Go to Manage Jenkins > System Configuration.
- Scroll to Global properties, check Environment variables.
- Add required key-value pairs (e.g., JAVA_HOME=C:\Program Files\Java\jdk-17)
Pipeline usage:
pipeline { agent any environment { JAVA_HOME = "${JAVA_HOME}" // refers to the globally‑set var } stages { stage('Show Java Path') { steps { echo "Java is installed at: ${env.JAVA_HOME}" } } } }
Console Output:
When a job accesses the global environment variable, the console will print its value.
Per-Job Environment Variables
Per-job environment variables are defined within the configuration of a specific Jenkins job, providing job-specific values that may differ from global settings. This allows for greater flexibility, as each job can have its own unique environment configuration.
Read More: Jenkins vs Bamboo: Core Differences
Steps:
- Open a specific Freestyle job.
- Go to Configure > Build Step
- Enable Inject environment variables (this requires the EnvInject plugin).
- Define the environment variables (e.g., CUSTOM_ENV=Development).
Console Output:
During job execution, the custom variable will be available, and its value can be echoed.
2. In Jenkinsfiles
Jenkinsfiles are used to define and manage pipelines, and they provide a way to declare environment variables within the script itself. This allows variables to be used dynamically across the entire pipeline or within specific stages.
In a Declarative Pipeline, the environment directive is used to declare environment variables at the pipeline or stage level.
Example (Declarative Pipeline):
pipeline { agent any environment { ENVIRONMENT = 'production' VERSION = '1.0.0' } stages { stage('Print Variables') { steps { echo "Deploying to ${ENVIRONMENT} environment, version ${VERSION}" } } } }
Console Output:
The console output will show the values of the environment variables that were set in the Jenkinsfile.
For example, the variables ENVIRONMENT and VERSION will be displayed as part of the echo command.
Read More: How to set up Jenkins Docker Agent?
3. Using the Environmental Directive
The environment directive allows environment variables to be scoped to specific stages within a pipeline. This is useful when different stages require different configurations or when you want to override global settings temporarily within a stage.
Example (Declarative Pipeline):
pipeline { agent any stages { stage('Setup') { environment { REGION = 'us-east-1' } steps { echo "Deploying in region: ${REGION}" } } } }
Console Output:
During execution, the REGION variable will be printed in the console output for the relevant stage.
4. With withEnv in Scripted Pipelines
In Scripted Pipelines, environment variables can be set dynamically using the withEnv block. This method allows environment variables to be scoped to a specific block of code and provides greater flexibility, especially when working with scripted pipelines.
Example (Declarative Pipeline):
node { withEnv(['LANGUAGE=python', 'VERSION=3.9']) { stage('Setup') { echo "Using ${LANGUAGE} version ${VERSION}" } } }
Console Output:
The LANGUAGE and VERSION variables will be printed as part of the pipeline execution.
Read More: What are Agents in Jenkins?
Understanding Environment Variables in Jenkins: Usage and Examples
Jenkins environment variables provide important runtime information such as job names, build numbers, workspace paths, and more.
These variables can be read and used to configure steps dynamically, pass data between stages, or control build logic based on the environment.
The method of accessing environment variables depends on the type of Jenkins job being configured.
Using Variables in Freestyle Projects
In Freestyle jobs, environment variables are accessed directly in shell or batch build steps. They are available to all script executions within the job.
Shell (Linux/macOS):
echo "The build number is $BUILD_NUMBER" echo "Workspace is located at $WORKSPACE"
Batch (Windows):
echo The build number is %BUILD_NUMBER% echo Workspace is located at %WORKSPACE%
Expected Output:
The Console Output will show the echoed environment variable values.
Using Variables in Pipeline Scripts (Declarative & Scripted)
In Pipeline jobs, environment variables are accessed through the env object provided by Jenkins. This approach is consistent across Declarative and Scripted pipelines.
Declarative Pipeline Example
pipeline { agent any stages { stage('Access Env Vars') { steps { echo "Job: ${env.JOB_NAME}" echo "Build ID: ${env.BUILD_ID}" } } } }
Expected Output:
The values for both environment variables will be printed in the console.
Scripted Pipeline Example:
node { stage('Access Env Vars') { echo "Running on Node: ${env.NODE_NAME}" echo "Workspace Path: ${env.WORKSPACE}" } }
Expected Output:
How to Override Jenkins Environment Variables
Sometimes, there is a need to override existing environment variables in Jenkins — either to adjust values for specific jobs, customize the pipeline behavior, or simulate different environments. Jenkins provides several ways to override environment variables, depending on how the job is configured.
1. Overriding in Freestyle Jobs
In Freestyle projects, environment variables can be manually overridden by adding key-value pairs in the job’s configuration.
Steps:
- Go to the Freestyle Job Configuration.
- Under Build Environment, select Inject environment variables.
- Specify new or updated variable values.
Example: Setting BUILD_NUMBER to a custom value:
Output: The overridden value will be used during the job execution instead of the default system-generated one.
2. Overriding in Pipeline Jobs
In Jenkins Pipeline jobs, environment variables can be overridden using the environment block or withEnv step.
Using environment Directive (Declarative Pipeline):
pipeline { agent any environment { BUILD_NUMBER = "999" CUSTOM_VAR = "OverrideExample" } stages { stage('Check Variables') { steps { echo "Build Number: ${env.BUILD_NUMBER}" echo "Custom Var: ${env.CUSTOM_VAR}" } } } }
Using withEnv Step (Scripted Pipeline):
node { withEnv(['BUILD_NUMBER=999', 'CUSTOM_VAR=OverrideExample']) { stage('Check Variables') { echo "Build Number: ${env.BUILD_NUMBER}" echo "Custom Var: ${env.CUSTOM_VAR}" } } }
Output: Console Output showing overridden environment variable values inside the pipeline.
Best Practices when Using Jenkins Environment Variables
Following best practices while using environment variables ensures Jenkins pipelines are secure, maintainable, and error-free.
- Use Clear Names: Always create descriptive variable names (e.g., DEPLOY_ENVIRONMENT, DB_PASSWORD) for better readability.
- Protect Secrets: Avoid hardcoding sensitive values. Use Jenkins Credentials Plugin to inject secrets safely into environment variables.
- Override Carefully: Only override built-in variables like BUILD_NUMBER if absolutely necessary. Prefer creating custom variables.
- Limit Scope: To avoid accidental conflicts, define environment variables close to where they are needed, such as within specific stages or blocks.
- Validate Before Use: Check if critical environment variables are available before using them to prevent runtime errors.
Well-structured environment variable usage makes Jenkins pipelines more reliable across teams and environments.
How does BrowserStack help with Jenkins Integration?
BrowserStack offers seamless integration with Jenkins, helping teams automate cross-browser testing and manage test execution reports efficiently.
BrowserStack Automate Integration
- Automated Cross-Browser Testing: Easily configure Jenkins jobs or pipelines to trigger Selenium WebDriver tests on real devices and browsers hosted on BrowserStack.
- Parallel Test Execution: Run tests in parallel across multiple device-browser combinations, reducing build and feedback time.
- Easy Setup: Install the BrowserStack Jenkins plugin and configure credentials once to authenticate all builds automatically.
Refer to this documentation for more details.
BrowserStack Test Management Integration
- Centralized Reporting: Automatically sync Jenkins test results with BrowserStack Test Management for easy tracking and analysis.
- Customizable Insights: Get visibility into pass/fail trends, flaky tests, and test coverage directly linked to Jenkins builds.
- One-Click Integration: Use the BrowserStack Test Management Jenkins plugin to push results during CI/CD execution effortlessly.
Refer to this documentation for Test Management Integrations.
Conclusion
Environment variables are an essential part of Jenkins, allowing dynamic configuration, better pipeline control, and easier environment management.
By understanding how to define, access, and override environment variables, teams can build more flexible and efficient CI/CD pipelines.
For advanced testing and reporting needs, integrating Jenkins with tools like BrowserStack can further enhance automation workflows, offering real device coverage and centralized test management.