Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to use environment variables defined outside any node in a Jenkinsfile. I can bring them in scope on any pipeline step in any node but not inside of a function. The only solution I can think of for now is to pass them in as parameters. But I would like to reference the env variables directly inside the function so I don't have to pass so many parameters in. Here is my code. How can I get the function to output the correct value of BRANCH_TEST?

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
like image 496
mdo123 Avatar asked May 24 '16 22:05

mdo123


1 Answers

Solutions are

  1. Use @Field annotation

  2. Remove def from declaration. See Ted's answer for an explanation on using def.

Solution 1 (using @Field)

import groovy.transform.Field

@Field def BRANCH_TEST = "master"

   node {
       deploy()
   }

   def deploy(){
       echo BRANCH_TEST
   }

Solution 2 (removing def)

BRANCH_TEST = "master"

   node {
       deploy()
   }

   def deploy(){
       echo BRANCH_TEST
   }

Explanation is here,

also answered in this SO question: How do I create and access the global variables in Groovy?

like image 143
mdo123 Avatar answered Sep 18 '22 13:09

mdo123