How to Set a Pipeline-Wide Variable in a Jenkins Pipeline
A top-level environment {} block sets variables visible to every stage in a Jenkins declarative pipeline.
Declare variables in the pipeline-level environment {} block to make them global. A stage-level environment {} overrides them for that stage only.
Global env with a stage override
The pipeline-level block applies everywhere; the stage block overrides LOG_LEVEL for that stage.
Jenkinsfile
pipeline {
agent any
environment {
APP_ENV = 'production'
LOG_LEVEL = 'info'
}
stages {
stage('Build') {
steps {
sh 'echo "env=$APP_ENV level=$LOG_LEVEL"'
}
}
stage('Debug') {
environment {
LOG_LEVEL = 'debug'
}
steps {
sh 'echo "level=$LOG_LEVEL"'
}
}
}
}Gotchas
- The pipeline-level
environment {}block is the global scope; a stage-level block shadows it only inside that stage. - For secrets, use
credentials("id")in theenvironment {}block - it binds a credential without printing it. - Values in
environment {}are evaluated once at the top; for runtime-computed values assign from ash(returnStdout: true)call.
Related guides
How to Set an Environment Variable in a Jenkins PipelineSet environment variables in a Jenkins declarative pipeline with the environment block at pipeline and stage…
How to Pass Data Between Stages in a Jenkins PipelinePass data between Jenkins pipeline stages with environment variables, script-scoped variables, and stash/unst…