How to Set Environment Variables in Jenkins Pipeline
In Jenkins Pipeline, you set environment variables using the
environment block in declarative pipelines or by using env.VAR_NAME = 'value' in scripted pipelines. These variables are then accessible throughout the pipeline stages and steps.Syntax
In Jenkins declarative pipelines, environment variables are set inside the environment block at the top level or inside stages. In scripted pipelines, you assign variables directly to env object.
- Declarative: Use
environment { VAR_NAME = 'value' } - Scripted: Use
env.VAR_NAME = 'value'
groovy
pipeline {
agent any
environment {
MY_VAR = 'HelloWorld'
}
stages {
stage('Example') {
steps {
echo "Value is: ${env.MY_VAR}"
}
}
}
}Example
This example shows a declarative Jenkins pipeline setting an environment variable GREETING and printing it in a stage.
groovy
pipeline {
agent any
environment {
GREETING = 'Hello from Jenkins'
}
stages {
stage('Print Greeting') {
steps {
echo "Message: ${env.GREETING}"
}
}
}
}Output
[Pipeline] echo
Message: Hello from Jenkins
Common Pitfalls
Common mistakes when setting environment variables in Jenkins pipelines include:
- Trying to set variables inside
stepsblock in declarative pipelines instead ofenvironment. - Using shell syntax like
export VAR=valuewhich only affects the shell, not the Jenkins environment. - Not referencing variables with
${env.VAR_NAME}orenv.VAR_NAMEin Groovy.
groovy
pipeline {
agent any
stages {
stage('Wrong') {
steps {
// This does NOT set a Jenkins env variable
sh 'export BAD_VAR=wrong'
echo "Bad var: ${env.BAD_VAR}"
}
}
stage('Right') {
environment {
GOOD_VAR = 'right'
}
steps {
echo "Good var: ${env.GOOD_VAR}"
}
}
}
}Output
[Pipeline] sh
+ export BAD_VAR=wrong
[Pipeline] echo
Bad var:
[Pipeline] echo
Good var: right
Quick Reference
Summary tips for setting environment variables in Jenkins Pipeline:
- Use
environmentblock in declarative pipelines. - Use
env.VAR_NAME = 'value'in scripted pipelines. - Access variables with
${env.VAR_NAME}orenv.VAR_NAME. - Shell
exportcommands do not persist variables in Jenkins environment.
Key Takeaways
Set environment variables in declarative pipelines using the environment block.
In scripted pipelines, assign variables directly to the env object.
Access environment variables with ${env.VAR_NAME} syntax.
Avoid using shell export commands to set Jenkins environment variables.
Environment variables set in the pipeline are available in all stages and steps.