Skip to content
Latchkey

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 under pipeline { for global vars.
  • Add another environment { } inside a stage for stage-only vars.
  • Reference values as $KEY in sh or ${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

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