The environment Directive

The environment directive defines environment variables available to your steps, including secrets from credentials.

Syntaxenvironment { APP_ENV = 'production' TOKEN = credentials('api-token') }

The environment directive sets environment variables for your pipeline or a single stage. Your shell steps can then read them like any other variable.

Two ways to set values

  • Plain valuesAPP_ENV = 'production'.
  • From credentialsAPI_KEY = credentials('my-api-key') pulls a secret from the credentials store safely.

Built-in variables

Jenkins also provides many variables automatically, such as BUILD_NUMBER, JOB_NAME, WORKSPACE, and GIT_COMMIT.

Example

Example · bash
pipeline {
    agent any
    environment {
        APP_ENV    = 'production'
        BUILD_TAG  = "v${BUILD_NUMBER}"
        DOCKER_CRED = credentials('dockerhub-login')
    }
    stages {
        stage('Info') {
            steps {
                sh 'echo "Environment: $APP_ENV"'
                sh 'echo "Build tag: $BUILD_TAG"'
                sh 'echo "Job: $JOB_NAME  #$BUILD_NUMBER"'
            }
        }
    }
}

When to use it

  • A pipeline-level environment block defines the image name and registry URL used consistently by both the build and push stages.
  • A credentials() binding in the environment block injects a Nexus password as an env var so Maven can authenticate.
  • A stage overrides one environment variable from the global block to deploy to production instead of staging.

More examples

Pipeline-level environment variables

Declares shared environment variables at pipeline level and composes IMAGE from REGISTRY and BUILD_NUMBER.

Example · groovy
pipeline {
  agent any
  environment {
    REGISTRY = 'registry.example.com'
    IMAGE    = "${REGISTRY}/myapp:${BUILD_NUMBER}"
  }
  stages {
    stage('Build') {
      steps { sh "docker build -t ${IMAGE} ." }
    }
  }
}

Inject credentials as env var

Binds a username/password credential to two env vars (_USR and _PSW) for Docker Hub login.

Example · groovy
pipeline {
  agent any
  environment {
    DOCKER_CREDS = credentials('docker-hub-creds')
  }
  stages {
    stage('Push') {
      steps {
        sh 'echo $DOCKER_CREDS_PSW | docker login -u $DOCKER_CREDS_USR --password-stdin'
      }
    }
  }
}

Stage-level environment override

Overrides the global TARGET_ENV variable in the production stage only, without changing it for other stages.

Example · groovy
pipeline {
  agent any
  environment { TARGET_ENV = 'staging' }
  stages {
    stage('Deploy Staging') {
      steps { sh "./deploy.sh ${TARGET_ENV}" }
    }
    stage('Deploy Production') {
      environment { TARGET_ENV = 'production' }
      steps { sh "./deploy.sh ${TARGET_ENV}" }
    }
  }
}

Discussion

  • Be the first to comment on this lesson.