How to Use Environment Variables in Jenkins Pipeline
In Jenkins pipelines, use the
environment block to define environment variables accessible throughout the pipeline stages. These variables help store configuration values or secrets and can be referenced using env.VARIABLE_NAME in your pipeline script.Syntax
The environment block is placed inside the pipeline or stage block. It defines key-value pairs where keys are variable names and values are their values. Variables set here are available as env.VARIABLE_NAME in the pipeline script.
Example parts:
environment: block to declare variablesVAR_NAME = 'value': sets a variable- Access with
env.VAR_NAMEin steps
groovy
pipeline {
agent any
environment {
GREETING = 'Hello'
TARGET = 'World'
}
stages {
stage('Example') {
steps {
echo "${env.GREETING}, ${env.TARGET}!"
}
}
}
}Example
This example shows a Jenkins pipeline that sets two environment variables GREETING and TARGET. The pipeline prints a message using these variables in the echo step.
groovy
pipeline {
agent any
environment {
GREETING = 'Hello'
TARGET = 'World'
}
stages {
stage('Print Message') {
steps {
echo "${env.GREETING}, ${env.TARGET}!"
}
}
}
}Output
[Pipeline] echo
Hello, World!
[Pipeline] End of Pipeline
Common Pitfalls
Common mistakes when using environment variables in Jenkins pipelines include:
- Defining variables outside the
environmentblock, so they are not recognized as environment variables. - Trying to use variables without the
env.prefix inside steps. - Using single quotes in
echowhich prevents variable expansion. - Overwriting environment variables unintentionally in nested scopes.
groovy
pipeline {
agent any
environment {
NAME = 'Jenkins'
}
stages {
stage('Wrong Usage') {
steps {
// This will print the literal string, not the variable value
echo '$NAME'
// Correct usage with double quotes and env prefix
echo "${env.NAME}"
}
}
}
}Output
[Pipeline] echo
$NAME
[Pipeline] echo
Jenkins
[Pipeline] End of Pipeline
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Define environment variables | Use environment { VAR = 'value' } | Variables available as env.VAR |
| Access variable | Use echo "${env.VAR}" | Use double quotes for expansion |
| Scope | Defined in pipeline or stage | Stage-level overrides pipeline-level |
| Secrets | Use Jenkins credentials with credentials() | Avoid plain text in environment |
| Common mistake | Using single quotes in echo | Variables won't expand |
Key Takeaways
Use the
environment block to define variables accessible in all pipeline stages.Access environment variables with
env.VARIABLE_NAME inside pipeline steps.Always use double quotes in
echo to expand variables correctly.Define environment variables at the pipeline or stage level depending on scope needs.
Avoid putting secrets directly in
environment; use Jenkins credentials instead.