2

I have a Jenkins parent groovy file which consumes the child groovy file

Parent grooy file:

...
def child = load 'child-groovy-file';
child.execute();

Child groovy file:

a = "first letter";
b = "second letter;
def execute
{
echo "a is "+a;
...
}

But this is not working. Unable to access variables, which are defined in Child Groovy file, when trying to access from Parent groovy file. When I create a node block and trying to consume directly the child groovy file, It is working.

Is the Environment variables only the solution to access globally?

3 Answers 3

0

try this one

static void main(String[] args) { 
      // Initializing 2 variables 
      def x = 5; 
      def y = 10;

      //Performing addition of 2 operands 
      println(x+y);
 }

}

check this URL

0

It just could be that:

import groovy.transform.Field

@Field public a = "first letter"
@Field public b = "second letter"

works (I got hint from https://stackoverflow.com/questions/37800195/)

When referencing (environment variables) I saw the format did not exactly work, but the following did:

@Field public c; c = 'prefix ' + VAR + ' suffix'

(probably "prefix ${VAR} suffix" worked but did not try that (either))

0

Your example code has a typo: b = "second letter; is missing the closing quote. Even if you fix that typo your code still won't work.

If you print the child variable it will be null?

That is because you are missing return this at the bottom of child-groovy-file.

It's mentioned in the Jenkins load documentation:

Where pipeline.groovy defines functionA and functionB functions (among others) before ending with return this;

I fixed your code and ran this POC:

Example code

This resulted in:

results of example code

While loading scripts like this might have some use cases, they are not very common. If you are looking to have reusable code you should use Jenkins Shared Libraries feature. If you want to see an example of what can be done with a shared-library see The Jenkins Standard Library, which can do things like run Github Actions! I also happen to be the author of that library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.