根据another answer如果您在没有 def
的情况下定义一个变量,它将变为“全局”,因此您可以从脚本中的任何位置访问它。如何使用方法来做到这一点(因为没有 def
AFAIK 就没有定义)?
郑重声明:我正在定义 Jenkins 管道,并希望在各个阶段之外访问一些“全局”方法
最佳答案
您可以在 Jenkinsfile
中定义任何方法外 pipeline {}
,例如
@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'
}
}
}
}
}
这里是一些示例脚本,它定义了 pomVersion()
从 pom.xml
读取版本的方法文件。它可以在管道的任何阶段和任何步骤中访问。
关于你的陈述:
if you define a variable without def it becomes "global" and thus you can access it from anywhere in the script
其实不是这样的。 Groovy 脚本编译为扩展 groovy.lang.Script
的类类(class)。它使用 bindings
存储脚本中使用的所有变量的结构(将其视为 Map<String,Object>
)。这种机制允许例如如果它们使用相同的 GroovyShell
运行,则在两个单独的脚本之间共享相同的绑定(bind)实例。
关于groovy - Groovy 脚本中的全局方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48319642/