AG6*_*6HQ 3 pipeline jenkins cloudbees jenkins-pipeline
我想在 Jenkins 脚本管道中定义一个全局变量,可以在管道中的任何位置访问该变量。即任何阶段、任何方法。如果我在管道顶部定义 var,它可以在声明node和stage声明中工作,但不能在被调用的方法中工作。我不想使用 env.XXX 和 withEnv([]) 因为我可能必须从不同的地方调用这些方法,这意味着有时会使用 env,而不是其他的。
这是我用于脚本化管道的简单 JenkinsFile:
def jenkinsNode = 'linux'
def DEBUG = 1
node(jenkinsNode){
echo ">> node($jenkinsNode)"
echo "DEBUG = $DEBUG"
if (DEBUG) {
echo "DEBUG is On"}
else {
echo "DEBUG is Off"
}
stage('test-this') {
if (DEBUG) {
echo "DEBUG is On"}
else {
echo "DEBUG is Off"
}
testMethod()
}
echo "<< node($jenkinsNode)"
}
def testMethod() {
echo ">> testMethod()"
if (DEBUG) {
echo "DEBUG is On"}
else {
echo "DEBUG is Off"
}
echo "<< testMethod()"
}
Run Code Online (Sandbox Code Playgroud)
当我运行这个时,我得到:
Running on rh6-a01 in /jenkins_home/jenkins-rh6-a01/a98289de/workspace/test/test/test-global
[Pipeline] {
[Pipeline] echo
>> node(linux)
[Pipeline] echo
DEBUG = 1
[Pipeline] echo
DEBUG is On
[Pipeline] stage
[Pipeline] { (test-this)
[Pipeline] echo
DEBUG is Off
[Pipeline] echo
>> testMethod()
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
hudson.remoting.ProxyException: groovy.lang.MissingPropertyException: No such property: DEBUG for class: WorkflowScript
[...snip...]
Run Code Online (Sandbox Code Playgroud)
我该如何编写这个 Jenkinsfile 以允许任何方法访问 DEBUG 变量?
apr*_*985 10
def从顶部的声明中删除可以解决此问题。
def jenkinsNode = 'linux'
DEBUG = 1
node(jenkinsNode){
echo ">> node($jenkinsNode)"
echo "DEBUG = $DEBUG"
if (DEBUG) {
.....
Run Code Online (Sandbox Code Playgroud)
给出输出
>> node(linux)
[Pipeline] echo
DEBUG = 1
[Pipeline] echo
DEBUG is On
[Pipeline] stage
[Pipeline] { (test-this)
[Pipeline] echo
DEBUG is On
[Pipeline] echo
>> testMethod()
[Pipeline] echo
DEBUG is On
[Pipeline] echo
<< testMethod()
[Pipeline] }
[Pipeline] // stage
[Pipeline] echo
<< node(docker)
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Run Code Online (Sandbox Code Playgroud)
这是因为 usingdef将变量绑定到当前范围(方法内容不在其中)。不使用def不会绑定范围,允许它在脚本中的任何地方使用。
请注意,Groovy 不会阻止您在def其他地方使用该变量,这可能会导致意外结果,例如def DEBUG = 0在方法中添加 a
def testMethod() {
echo ">> testMethod()"
def DEBUG = 0
if (DEBUG) {
echo "DEBUG is On"}
else {
echo "DEBUG is Off"
}
Run Code Online (Sandbox Code Playgroud)
仍然可以正常运行,但会关闭该方法中的调试。
| 归档时间: |
|
| 查看次数: |
13462 次 |
| 最近记录: |