Issue
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
Solution
Solutions are
Use
@Field
annotationRemove 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?
Answered By - mdo123
Answer Checked By - Mildred Charles (JavaFixing Admin)