Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I include a shared library in the Jenkins script console?

Tags:

jenkins

groovy

In a Jenkinsfile, if I have a Jenkins shared library installed under the alias my-awesome-lib, I can include it using the syntax:

@Library('my-awesome-lib')
import ...

But how can I refer to the library from the Jenkins script console?

like image 327
Roberto Aloi Avatar asked Dec 05 '18 15:12

Roberto Aloi


1 Answers

You can refer the library object from script console like this:

// get Jenkins instance
Jenkins jenkins = Jenkins.getInstance()

// get Jenkins Global Libraries
def globalLibraries = jenkins.getDescriptor("org.jenkinsci.plugins.workflow.libs.GlobalLibraries")
globalLibraries.getLibraries()

but using the shared libraries code will not be simple and might be even impossible.

In continue to the code above, let's say you do:

def lib = globalLibraries[0]

get the retriever:

def ret = lib.getRetriever()

then you need to retrieve the source code, but in order to call retrieve(), you need a few object that you don't have in the script console:

/**
     * Obtains library sources.
     * @param name the {@link LibraryConfiguration#getName}
     * @param version the version of the library, such as from {@link LibraryConfiguration#getDefaultVersion} or an override
     * @param target a directory in which to check out sources; should create {@code src/**}{@code /*.groovy} and/or {@code vars/*.groovy}, and optionally also {@code resources/}
     * @param run a build which will use the library
     * @param listener a way to report progress
     * @throws Exception if there is any problem (use {@link AbortException} for user errors)
     */
    public abstract void retrieve(@Nonnull String name, @Nonnull String version, @Nonnull FilePath target, @Nonnull Run<?,?> run, @Nonnull TaskListener listener) throws Exception;

so there might be a hacky way to do so, but IMO it doesn't worth it.

like image 134
Tidhar Klein Orbach Avatar answered Sep 22 '22 15:09

Tidhar Klein Orbach