How to use environment variables in groovy function using Jenkins file

I am trying to use environment variables defined outside of any node in a Jenkins file. I can bring them into scope at any stage of the pipeline in any node, but not inside the function. The only solution I can think of right now is to pass them as parameters. But I would like to refer to env variables directly inside the function, so I don't need to pass so many parameters. Here is my code. How can I get a function to output the correct BRANCH_TEST value?

  def BRANCH_TEST = "master" node { deploy() } def deploy(){ echo BRANCH_TEST } 

Jenkins console output:

 [Pipeline] [Pipeline] echo null [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline Finished: SUCCESS 
+6
source share
1 answer

Solutions

  • Use @Field annotation

  • Remove def from the declaration. See Ted answer for an explanation of using def.

Solution 1 (using @Field)

 import groovy.transform.Field @Field def BRANCH_TEST = "master" node { deploy() } def deploy(){ echo BRANCH_TEST } 

Solution 2 (def removal)

 BRANCH_TEST = "master" node { deploy() } def deploy(){ echo BRANCH_TEST } 

Explanation here

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

Also answered in how-do-i-create-and-access-the-global-variables-in-groovy

+13
source

All Articles