You can define any method in your Jenkinsfile
outside pipeline {}
, e.g.
@NonCPS
def pomVersion() {
def matcher = readFile('pom.xml') =~ '<version>(.+)</version>'
return matcher ? matcher[1][1] : null
}
pipeline {
agent any
stages {
stage('Build') {
steps {
sh "sed -i.bak -e 's|\${appVersion}|'${pomVersion()}'|g' dep_pom.xml"
sh 'mvn clean -U install -DdeploymentContext=test -f dep_pom.xml'
}
post {
success {
junit '**/target/**/*.xml'
}
}
}
}
}
Here is some exemplary script that defines pomVersion()
method that reads version from pom.xml
file. It can be accessed in any stage and any step of the pipeline.
Regarding your statement that:
if you define a variable without def it becomes "global" and thus you can access it from anywhere in the script
it's not like that actually. Groovy script is compiled to a class that extends groovy.lang.Script
class. It uses bindings
structure (think of it as a Map<String,Object>
) that stores all variables used in the script. This mechanism allows e.g. to share same bindings between two separate scripts if they are run using same GroovyShell
instance.