kotlinjenkinsjenkins-groovyjenkins-shared-libraries

Jenkins shared libraries with kotlin


I have to add some kotlin-written classes at groovy-written shared library to use it in my jenkins pipeline. However, these classes aren't available:

WorkflowScript: 19: unable to resolve class package.name.KotlinClass

And i don't have the same problem with groovy classes. I think the problem is i don't declare any tasks like compileKotlin, but where should i declare it? What drives the building of sources from shared plugin libraries and is this process configurable?


Solution

  • If I understand the problem correctly, you have a shared library in Jenkins, which a pipeline makes use of. Within that shared library, you would like your groovy to call onto classes compiled from kotlin.

    The best approach to this would be to have a separate process compile the kotlin and publish a JAR into a maven repository. Once that is done, your groovy shared library can fetch the JAR using @Grab. This is covered in https://www.jenkins.io/doc/book/pipeline/shared-libraries/#using-third-party-libraries and broadly works like so:

    @Grab('org.apache.commons:commons-math3:3.4.1')
    import org.apache.commons.math3.primes.Primes
    void parallelize(int count) {
      if (!Primes.isPrime(count)) {
        error "${count} was not prime"
      }
      // …
    }
    

    If you want to resolve that JAR from your own private maven repository as opposed to Maven Central, you can also add the @GrabResolver annotation as documented here https://docs.groovy-lang.org/latest/html/documentation/grape.html#Grape-SpecifyAdditionalRepositories

    @GrabResolver(name='restlet', root='http://maven.restlet.org/')
    @Grab('org.apache.commons:commons-math3:3.4.1')
    

    A problem you will run into here is that you cannot add credentials into that @GrabResolver and I am not aware of a way to get credentials into the groovy sandbox to make that work for Jenkins shared libraries.

    An alternative approach, as hinted by Jenkins own documentation is to build the required functionality into it's own executable, and make sure that executable is available in the build process the Jenkins shared library is being called in.