Interview Prep/Jenkins/Scripted pipeline, Groovy & CPS

How do you share a variable between stages in declarative?

IntermediateConceptScripted pipeline, Groovy & CPS
Answer

Options, from cleanest to messiest:

  1. env.IMAGE_TAG = "..." inside script {}; env vars are strings only.
  2. A variable declared outside the pipeline {} block (def tag) and assigned in script {}; works but is global mutable state.
  3. Return values from a shared library step.
def releaseTag
pipeline {
  agent any
  stages {
    stage('Version') { steps { script { releaseTag = sh(script: 'git describe --tags', returnStdout: true).trim() } } }
    stage('Show')    { steps { echo "Tag: ${releaseTag}" } }
  }
}
All Jenkins questions Roadmap: Jenkins

More on Scripted pipeline, Groovy & CPS