jenkinsgroovycicdjenkins-shared-libraries

Can a Groovy source file in Jenkins' Shared Library access a method from a global variable?


Can a Groovy source file in Jenkins' Shared Library access a method from a global variable?

my Shared Library structure is:

(root)
+- src                     # Groovy source files
|   +- org
|       +- foo
|           +- CallMethodFromVars.groovy  # for org.foo.CallMethodFromGlobalVars.groovy class
+- vars
|   +- foo.groovy          # for global 'foo' variable

In my class src.org.foo.CallMethodFromVars I would like to access a method call(arg) in vars.foo.groovy

src.org.foo.CallMethodFromVars:

class CallMethodFromVars  {
    String run(){
         //TODO call method vars.foo.groovy.call() here
    }
}

vars.foo.groovy:

def call(arg) {
   doSomething()
}

My research and attempts at solving this so far have failed. Some of the things I tried:


Solution

  • Yes, you can. As stated in the first answer, the question is somehow addressed already but let me give here very simple example basing on your code. To be more precise: we have 2 kinds of libraries here: objective library written as class and static library written like method. You want to call static library from inside objective library.

    The key to solve the problem is to pass script object from pipeline itself. I name it parentScript here:

    class CallMethodFromVars  {
    
        def parentScript
    
        CallMethodFromVars(parentScript) {
            this.parentScript = parentScript
        }
    
        String run(arg){
            parentScript.foo(arg)
        }
    }
    

    After this, you need to call the objective library from the pipeline, for example like this (you need to configure library in Jenkins to be accessible under specific name e.g. 'objective-lib'):

    def lib = library('objective-lib').org.foo
    def instance = lib.CallMethodFromVars.new(this) // 'this' becomes parentScript inside objective library
    instance.run('some args')
    

    Objective library is called from pipeline by creating the instance and then calling method of that instance which in turn calls static library.