How to Use the environment Block in a Jenkins Pipeline
The environment{} block declares variables that Jenkins exports into the shell for every step in its scope.
Add an environment {} block at pipeline level for globals, or inside a stage for stage-local values. Each KEY = value becomes a real environment variable visible to sh and to ${KEY} interpolation.
Steps
- Add
environment { }directly underpipeline {for global vars. - Add another
environment { }inside astagefor stage-only vars. - Reference values as
$KEYinshor${env.KEY}in Groovy.
Jenkinsfile
Jenkinsfile
pipeline {
agent any
environment {
APP_NAME = 'billing-api'
BUILD_TAG = "${env.BRANCH_NAME}-${env.BUILD_NUMBER}"
}
stages {
stage('Build') {
environment { NODE_ENV = 'production' }
steps {
sh 'echo Building $APP_NAME at $BUILD_TAG in $NODE_ENV'
}
}
}
}Gotchas
- Values are strings; reference other vars with double quotes so Groovy interpolates them.
- Stage-level environment overrides a same-named pipeline-level variable inside that stage only.
Related guides
How to Bind a Credential in the environment Block in JenkinsInject a stored Jenkins credential into an environment variable with the credentials() helper, so secrets sta…
How to Move Files Between Agents With stash and unstash in JenkinsCarry build output from one Jenkins agent to another with stash and unstash, since parallel stages and differ…