8

I have Jenkinsfile like this:

def globalVariable = "my variable"

def myFunction() {
    def myString = "my String and ${globalVariable}
    .....
}

pipeline {
    ...
    < The globalVariable can be accessed inside the pipeline >  
}

I receives a runtime error, complaining globalVariable cannot be accessed inside the myFunction.

I thought globalVariable is global and can be accessed anywhere from the file.

Is there anyway I can reference it inside function?

ZZZ
  • 645
  • 4
  • 17
  • 3
    The variable is global to the scope of the pipeline. Your function's scope is completely distinct from the pipeline. There is no "file scope" in Jenkins Pipeline. Although the variable is initialized outside the `pipeline` directive, it is still considered part of the directive (which can be confusing). – Matthew Schuchard Oct 11 '21 at 17:34
  • For use inside the function, you can pass-by-value as a function argument. Does that work for your usage with your code? – Matthew Schuchard Oct 11 '21 at 17:36
  • 3
    You will probably need an @Field annotation as described in [this answer](https://stackoverflow.com/a/50573082/13215866). – Sebastian Westemeyer Oct 11 '21 at 17:39
  • 1
    Does this answer your question? [Strange variable scoping behavior in Jenkinsfile](https://stackoverflow.com/questions/50571316/strange-variable-scoping-behavior-in-jenkinsfile) – Hcorg Jan 20 '23 at 14:32

1 Answers1

1

You can add @Field to your def, then the function will be able to read it:

import groovy.transform.Field

@Field def globalVariable = "my variable"

def myFunction() {
    def myString = "my String and ${globalVariable}
    .....
}

pipeline {
    ...
    < The globalVariable can be accessed inside the pipeline >  
}
nitsanzo
  • 146
  • 7