Pass variable from one Jenkins stage to others in sh

You can output the variables to same file in stage, then read back and assign to env at the beginning of each stage as following:

stage('a') {
  steps {
    script {
       loadEnvs('env.props')
    }  
    sh """
      echo var1 = a >> env.props
    """
  }
}

stage('b') {
  steps {
    script {
      loadEnvs('env.props')
    }
    sh """
      echo $env.var1

      echo var2 = b >> env.props
    """
  }
}

def loadEnvs(propFile) {
  props = readProperties(propFile)
  props.each { key, val ->
    env[key] = val
  }
}

Leave a Comment