user3270760 user3270760 - 4 years ago 210
Groovy Question

Jenkinsfile variable used in two separate stages

I have a pipeline job that uses two separate nodes (one for build, one for test), and I'd like to share a variable between two of these blocks of code in my Jenkinsfile. I assume it's possible, but I'm very new to groovy and the jenkinsfile concept. Here is the relevant code so far:

node('build') {
stage('Checkout') {
checkout scm
}
stage('Build') {
bat(script: 'build')
def rev = readFile('result')
}
}

node('test') {
stage('Test') {
def SDK_VERSION = "5.0.0001.${rev}"
bat "test.cmd ${env.BUILD_URL} ${SDK_VERSION}"
archiveArtifacts artifacts: 'artifacts/**/*.xml'
junit 'artifacts/**/*.xml'
}
}


I want to assign the "rev" variable in the build stage, but then concatenate it to the SDK_VERSION variable in the Test stage. My error is:

groovy.lang.MissingPropertyException: No such property: rev for class: groovy.lang.Binding

Answer Source

Just define the variable before your node block:

def rev = ''
node('build') {
  stage('Checkout') {
    checkout scm
  }
  stage('Build') {
    bat(script: 'build')
    rev = readFile('result')
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download