Use multi-method global variables in Jenkins Shared Libraries

1.5k views Asked by At

Consider this groovy file in a repo that is loaded as shared library in Jenkins:

/ vars
|
--- Utility.groovy

// Utility.groovy

def funcA() { ... }

def funcB() { ... }

And in the Jenkinsfile:

// Jenkinsfile

@Library('LibName') _

pipeline {
...
steps {
   script {
      def util = new Utility()
      util.funcA()
   }
 }
}

This works fine. But if i try to load the library dynamically:

// Jenkinsfile

pipeline {
   ...
   steps {
       script {
          library 'LibName'
          def util = new Utility()
       }

    }


}

That doesn't work...

Can someone explain this with respect to this quote from the documentation:

The documentation of Shared Libraries in Jenkins says:

Internally, scripts in the vars directory are instantiated on-demand as singletons. This allows multiple methods to be defined in a single .groovy file for convenience.

1

There are 1 answers

0
Samit Kumar Patel On

Loading a Jenkins Shared Library dynamically has some limitation and challenges because of:

Using classes from the src/ directory is also possible, but trickier. Whereas the @Library annotation prepares the “classpath” of the script prior to compilation, by the time a library step is encountered the script has already been compiled. Therefore you cannot import or otherwise “statically” refer to types from the library. which is explained here

And it seems this question is kind of similar to this one.