I was using some global methods in the /var directory of the shared library, and everything worked fine. Now I need to keep the state of the process, so I'm writting a groovy class. Basically I have a class called 'ClassTest.groovy' in '/src' which is something like this;
class ClassTest {
String testString
def method1() { ... }
def method2() { ... }
}
and at the begining of the pipeline
library 'testlibrary@'
import ClassTest
with result:
WorkflowScript: 2: unable to resolve class ClassTest @line 2, column 1.
import ClassTest
before, I was just goind
library 'testlibrary@' _
and using the methods as
script {
libraryTest.method1()
...
libraryTest.method2()
}
where the methods were in a file '/var/libraryTest.groovy' and everything worked. So I know that the shared library is there, but I'm confused with the way groovy / Jenkins handle classes / shared libraries.
What's the correct way to import a class? I cannot find a simple example (with groovy file, file structure and pipeline) in the documentation.
EDIT: I moved the file to 'src/com/company/ClassTest.groovy' and modified the pipeline as
@Library('testlibrary@') import com.company.ClassTest
def notification = new ClassTest()
but now the error is
unexpected token: package @ line 2
the first two lines of the groovy file are:
// src/com/company/ClassTest.groovy
package com.company;
What is a Shared Library in Jenkins? A shared library is a collection of independent Groovy scripts which you pull into your Jenkinsfile at runtime. The best part is, the Library can be stored, like everything else, in a Git repository. This means you can version, tag, and do all the cool stuff you're used to with Git.
Global Shared Libraries These libraries are considered "trusted:" they can run any methods in Java, Groovy, Jenkins internal APIs, Jenkins plugins, or third-party libraries. This allows you to define libraries which encapsulate individually unsafe APIs in a higher-level wrapper safe for use from any Pipeline.
So far this is what I've found.
To load the library in the pipeline I used:
@Library('testlibrary@') import com.company.ClassTest
def notification = new ClassTest()
In the class file, no package instruction. I guess that I don't need one because I don't have any other files or classes, so I don't really need a package. Also, I got an error when using the same name for the class and for the file where the class is. The error specifically complained and asked for one of them to be changed. I guess this two things are related to Jenkins.
That works, and the library is loaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With