27
Nov

Variable scope in Jenkins (declarative pipeline)

pipeline {
  agent any

  environment {
    // FOO will be available in entire pipeline
    FOO = "PIPELINE"
  }

  stages {
    stage("local") {
      environment {
        // BAR will only be available in this stage
        BAR = "STAGE"
      }
      steps {
        sh 'echo "FOO is $FOO and BAR is $BAR"'
      }
    }
    stage("global") {
      steps {
        sh 'echo "FOO is $FOO and BAR is $BAR"'
      }
    }
  }
}

Console output:

Started by user Administrator
Running in Durability level: MAX_SURVIVABILITY
..
Running on Jenkins in C:\Users\xxx\.jenkins\workspace\ScriptedPipeline
....
+ echo 'FOO is PIPELINE and BAR is STAGE'
FOO is PIPELINE and BAR is STAGE
.....
+ echo 'FOO is PIPELINE and BAR is '
FOO is PIPELINE and BAR is 
...
[Pipeline] End of Pipeline
Finished: SUCCESS