Skip to content
Latchkey

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 the environment {} block - it binds a credential without printing it.
  • Values in environment {} are evaluated once at the top; for runtime-computed values assign from a sh(returnStdout: true) call.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →