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

How to use environment variables in a groovy function using a Jenkinsfile

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

def BRANCH_TEST = "master"

node {
    deploy()
}

def deploy(){
    echo BRANCH_TEST
}

Jenkins 控制台输出:

[Pipeline]
[Pipeline] echo
null
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

解决方案是

  1. 使用@Field注解

  2. 从声明中删除 def。有关使用 def.

    的说明,请参阅 Ted's answer

解决方案 1(使用 @Field

import groovy.transform.Field

@Field def BRANCH_TEST = "master"

   node {
       deploy()
   }

   def deploy(){
       echo BRANCH_TEST
   }

解决方案 2(删除 def)

BRANCH_TEST = "master"

   node {
       deploy()
   }

   def deploy(){
       echo BRANCH_TEST
   }

解释为here,

也在这个 SO 问题中回答: How do I create and access the global variables in Groovy?