如何使用Jenkinsfile在groovy函数中使用环境变量

mdo*_*123 12 groovy jenkins jenkins-pipeline

我正在尝试使用Jenkinsfile中任何节点外部定义的环境变量.我可以将它们放在任何节点中的任何管道步骤的范围内,但不能在函数内部.我现在能想到的唯一解决方案是将它们作为参数传递.但我想直接在函数内部引用env变量,所以我不必传递这么多参数.这是我的代码.如何让函数输出正确的值BRANCH_TEST

   def BRANCH_TEST = "master"

   node {
       deploy()
   }

   def deploy(){
       echo BRANCH_TEST
   }
Run Code Online (Sandbox Code Playgroud)

Jenkins控制台输出:

[Pipeline]
[Pipeline] echo
null
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
Run Code Online (Sandbox Code Playgroud)

mdo*_*123 22

解决方案是

  1. 使用@Field注释

  2. 从声明中删除def.有关使用def的解释,请参阅Ted的答案.

解决方案1(使用@Field)

import groovy.transform.Field

@Field def BRANCH_TEST = "master"

   node {
       deploy()
   }

   def deploy(){
       echo BRANCH_TEST
   }
Run Code Online (Sandbox Code Playgroud)

解决方案2(删除def)

BRANCH_TEST = "master"

   node {
       deploy()
   }

   def deploy(){
       echo BRANCH_TEST
   }
Run Code Online (Sandbox Code Playgroud)

解释在这里,

https://groups.google.com/d/msg/jenkinsci-users/P7VMQQuMdsY/bHfBDSn9GgAJ

还在how-do-do-do-do-create-and-access-the-global-variables-in-groovy中回答