18

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
Neuron
  • 5,141
  • 5
  • 38
  • 59
mdo123
  • 1,757
  • 3
  • 16
  • 34
  • Does this answer your question? [How do I create and access the global variables in Groovy?](https://stackoverflow.com/questions/6305910/how-do-i-create-and-access-the-global-variables-in-groovy) – Neuron Mar 04 '21 at 13:09

1 Answers1

33

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?

Neuron
  • 5,141
  • 5
  • 38
  • 59
mdo123
  • 1,757
  • 3
  • 16
  • 34