How do you share a variable between stages in declarative?
IntermediateConceptScripted pipeline, Groovy & CPS
Answer
Options, from cleanest to messiest:
env.IMAGE_TAG = "..."insidescript {}; env vars are strings only.- A variable declared outside the
pipeline {}block (def tag) and assigned inscript {}; works but is global mutable state. - 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}" } }
}
}
More on Scripted pipeline, Groovy & CPS
What does a scripted pipeline look like and when would you still write one?IntermediateWhat is CPS and why does Jenkins transform pipeline Groovy?AdvancedWhy does `java.io.NotSerializableException` happen in pipelines?AdvancedWhat does `@NonCPS` do and what are its rules?AdvancedWhy do some Groovy closures behave unexpectedly in pipelines, for example `list.each { }` or `sort`?AdvancedWhat is the `script` block in declarative, and what are its limits?Beginner