1
def veriableset(){ def a = "test1" def b = "test2" def c = "test3" } def echomethod(){ echo a } node{ stage('test'){ veriableset(); echomethod(); } } 

I want to call the variable I defined in the method in another method.

I get the following error.

[Pipeline] { [Pipeline] stage [Pipeline] { (test) [Pipeline] } [Pipeline] // stage [Pipeline] } [Pipeline] // node [Pipeline] End of Pipeline groovy.lang.MissingPropertyException: No such property: a for class: groovy.lang.Binding at groovy.lang.Binding.getVariable(Binding.java:63) at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:270) at org.kohsuke.groovy.sandbox.impl.Checker$6.call(Checker.java:291) at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:295) at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:29) at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20) at WorkflowScript.echomethod(WorkflowScript:7) at WorkflowScript.run(WorkflowScript:12) at ___cps.transform___(Native Method) 

What method should I use? Can you help me?

2
  • 2
    remove def in front of variable declaration: def a = 'test1' --> a = 'test1' Commented May 22, 2020 at 23:10
  • as @daggett said, def makes a variable available only in the scope of that method. You can make it a function instead by returning a value and calling it inside the other method. Commented May 25, 2020 at 8:34

1 Answer 1

1

I suggest reading up on variable scoping: https://code-maven.com/groovy-variable-scope

The comment to remove def, technically would be fine but beware using global vars everywhere.

Instead you could look at veriableset() returning the variables and passing them into echomethod.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.