Using another class from Jenkins Shared Pipeline - jenkins

I am currently using a Jenkins library without issues from my jobs.
Right now I am trying to do some refactor, there is a chunk of code to determine with AWS account to use in almost every tool we currently have in the library.
I created the following file "get account.groovy"
class GetAccount {
def getAccount(accountName) {
def awsAccount = "abcd"
return awsAccount;
}
}
Then I am trying to do this from within one of the other groovy scripts:
def getaccount = load 'getaccount.groovy'
def awsAccount = getaccount.getAccount(account)
But that does not work since it is looking for that file in the current work directory not in the library directory
I am unable to figure out what the best way to call another class from within a library that is already being used.

Jenkins load DSL is meant to load an externalize groovy file that is available in the job workspace and it will not work if you try to load a groovy script available in Jenkins shared library, because the shared library never checkout in the job Workspace.
If you follow the standard shared library structure like below, it could be done like :
shared-library
├── src
│   └── org
│   └── any
│   └── GetAccount.groovy
└── vars
└── aws.groovy
GetAccount.groovy
package org.any
class GetAccount {
def getAccount(accountName) {
def awsAccount = "abcd"
return awsAccount;
}
}
aws.groovy
import org.any;
def call() {
def x = new GetAccount()
// make use of val and proceed with your further logic
def val = x.getAccount('xyz')
}
In your Jenkinsfile (declarative or scripted ) you can use both the shared library groovy class like :
make use of aws.groovy
scripted pipeline
node {
stage('deploy') {
aws()
}
}
declarative pipeline
pipeline {
agent any;
stages {
stage('deploy') {
steps {
aws()
}
}
}
}
make use of GetAccount.groovy
scripted pipeline
import org.any
node {
stage('deploy') {
def x = new GetAccount()
// make use of val and proceed with your further logic
def val = x.getAccount('xyz')
}
}
declarative pipeline
import org.any
pipeline {
agent any;
stages {
stage('deploy') {
steps {
script {
def x = new GetAccount()
// make use of val and proceed with your further logic
def val = x.getAccount('xyz')
}
}
}
}
}

Related

Reuse a shared declarative Jenkins pipeline and overwrite/extend stages

I have a couple of projects and i am sharing a "default" Jenkins pipeline via "shared library". The default pipeline looks something like this:
def call(body) {
def pipelineParams = [:]
body.resolveStrategy = Closure.DELEGATE_FIRST
body.delegate = pipelineParams
body()
pipeline {
tools {
maven pipelineParams.mavenId
jdk pipelineParams.jdkId
}
options {
timestamps()
}
stages {
stage('A') {
steps {
// do stuff
}
}
stage('B') {
steps {
// do stuff
}
}
}
}
}
In most cases/projects this works just fine, but in some, i would like to change the behaviour/steps of some of these predefined stages.
Currently i have to copy the default pipeline, add it to the "special" project and alter the steps that i need to change. A problem arises the moment i need to add a step or configuration to all of my projects, regardless if the project is using the default or a special pipeline.
Another way i thought of is to implement something like extension points, pass closures into the default pipeline and call them in predefined places.
I would like to know, if there is any other way to deal with this kind of problem?

Executing shell commands from inside Pipeline Shared Library

I'm writing a shared library that will get used in Pipelines.
class Deployer implements Serializable {
def steps
Deployer(steps) {
this.steps = steps
}
def deploy(env) {
// convert environment from steps to list
def process = "ls -l".execute(envlist, null)
process.consumeProcessOutput(output, error)
process.waitFor()
println output
println error
}
}
In the Jenkinsfile, I import the library, call the class and execute the deploy function inside a script section:
stage('mystep') {
steps {
script {
def deployer = com.mypackage.HelmDeployer("test")
deployer.deploy()
}
}
}
However, no output or errors are printed on the Console log.
Is it possible to execute stuff inside a shared library class? If so, how, and what am I doing wrong?
Yes, it is possible but not really an obvious solution. Every call that is usually done in the Jenkinsfile but was moved to the shared-library needs to reference the steps object you passed.
You can also reference the Jenkins environment by calling steps.env.
I will give you a short example:
class Deployer implements Serializable {
def steps
Deployer(steps) {
this.steps = steps
}
def callMe() {
// Always call the steps object
steps.echo("Test")
steps.echo("${steps.env.BRANCH_NAME}")
steps.sh("ls -al")
// Your command could look something like this:
// def process = steps.sh(script: "ls -l", returnStdout: true).execute(steps.env, null)
...
}
}
You also have to import the object of the shared library and create an instance of it. Define the following outside of your Pipeline.
import com.mypackage.Deployer // path is relative to your src/ folder of the shared library
def deployer = new Deployer(this) // 'this' references to the step object of the Jenkins
Then you can call it in your pipeline as the following:
... script { deployer.test() } ...

Use multi-method global variables in Jenkins Shared Libraries

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.
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.

How "vars" in Jenkins Shared Libraries work?

I'm experiencing some behaviors in Jenkins Shared Libraries, and it'll be great if someone can explain this to me:
First issue
Let's say i have a file in the vars directory:
// MultiMethod.groovy
def Foo() { ... }
def Bar() { ... }
Now if i want to use those functions from the pipeline, what i did was:
// Jenkinsfile
#Library('LibName') _
pipeline {
...
steps {
script {
// Method (1): this will work
def var = new MultiMethod()
var.Foo()
var.Bar()
// Method (2) this will not work
MultiMethod.Foo()
}
}
}
(The (1) and (2) methods are methods of calling the methods in the groovy script. Don't be confused by these 2 uses of the word "Method" please.)
So it works only if I instantiate this MultiMethod with the new operator.
But, if I name the file multiMethod (camelCased) instead of MultiMethod, i can use method (2) to call the methods in the script. Can someone explain this behavior?
That seems to be working fine.
Second issue
Based on the example above. If I have the groovy file named MultiMethod, (We saw earlier that i can use its methods if I instantiate with with new), I can't seem to instantiate an object of MultiMethod when loading the library dynamically, like this:
// Jenkinsfile
pipeline {
...
steps {
script {
// Method (1): this will not work
library 'LibName'
def var = new MultiMethod()
var.Foo()
var.Bar()
}
}
}
If i try to do so, i get this:
Running in Durability level: MAX_SURVIVABILITY
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 11: unable to resolve class multiMethod
# line 11, column 32.
def mult = new multiMethod()
^
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:958)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUni
...
EDIT
I notice that if I do this:
// Jenkinsfile
pipeline {
...
steps {
script {
library 'LibName'
MultiMethod.Foo()
MultiMethod.Bar()
}
}
}
It does work !!
Last Question
Another question if you may. I noticed that people use to write
return this
In the end of their scripts in the vars directory. Can someone explain what is it good for? I'd be happy if someone could explain this in the context of how does the mechanism of this works, like why are those scripts turns into Global Variables?
Thanks
First Question Answer
It's because Jenkins has defined that standard for the shared library. To clear your doubt, there is really a good explanation in Jenkins official documentation and it will work if you do it by following the standards. like below example:
make sure you are following this folder structure
shared-library
├── src
│   └── org
│   └── any
│   └── MultiMethod.groovy
└── vars
└── multiMethod.groovy
multiMethod.groovy
def foo() {
echo "Hello foo from vars/multiMethod.groovy"
}
def bar() {
echo "Hello bar from vars/multiMethod.groovy"
}
Once you have this and you are configuring your shared library like this way, then you can make use of multiMethod.groovy on your Jenkins file like below:
Jenkinsfile
#Library('jenkins-shared-library') _
pipeline {
agent any;
stages {
stage('log') {
steps {
script {
multiMethod.foo()
multiMethod.bar()
}
}
}
}
}
why does it work this way? - it explains here
But to make use of src/org/any/MultiMethod.groovy available in the src folder, you have to instantiate the class and call the method. Below is my example
MultiMethod.groovy
package org.any
class MultiMethod {
def steps;
MultiMethod(steps) {
this.steps = steps
}
def foo() {
steps.echo "Hello foo from src/org/any/MultiMethod.groovy"
}
def bar() {
steps.echo "Hello bar from src/org/any/MultiMethod.groovy"
}
}
Jenkinsfile
#Library('jenkins-shared-library') _
import org.any.MultiMethod
pipeline {
agent any;
stages {
stage('log') {
steps {
script {
def x= new MultiMethod(this);
x.foo()
x.bar()
}
}
}
}
}
Second Question Answer
Your second question is duplicate to this post. I have tried to explain and given an example. Please take a look.
Last Question Answer
It's not necessary to return this from the Jenkins global variable defined in vars if you do
vars/returnThisTest.groovy
def helloWorld() {
echo "Hello EveryOne"
}
or
def helloWorld() {
echo "Hello EveryOne"
}
return this;
both are the same and from Jenkinsfile you can just call like returnThisTest.helloWorld(), but return this can be more useful when a scenario will be like this - a good example from Jenkins documentation

jenkinsfile use traits and other groovy synax

I would like to use a slightly more complex pipeline build via jenkinsfiles, with some reusable steps as I have a lot or similar projects. I'm using jenkins 2.0 with the pipeline plugins. I know that you can load groovy scripts which contain can contain some generic pieces of code but I was wondering if these scripts can use some of the Object oriented features of groovy like traits. For example say I had a trait called Step:
package com.foo.something.ci
trait Step {
void execute(){ echo 'Null execution'}
}
And a class that then implemented the trait in another file:
class Lint implements Step {
def execute() {
stage('lint')
node {
echo 'Do Stuff'
}
}
}
And then another class that contained the 'main' function:
class foo {
def f = new Lint()
f.execute()
}
How would I load and use all these classes in a Jenkinsfile, especially since I may have multiple classes each defining a step? Is this even possible?
Have a look at Shared Libaries. These enable the use of native groovy code in Jenkins.
Your Jenkinsfile would include your shared libary, and the use the classes you defined. Be aware, that you have to pass the steps variable of Jenkins, if you want to use stage or the other variables defined in the Jenkins Pipeline plugin.
Excerpt from the documentation:
This is the class, which would define your stages
package org.foo
class Utilities implements Serializable {
def steps
Utilities(steps) {this.steps = steps}
def mvn(args) {
steps.sh "${steps.tool 'Maven'}/bin/mvn -o ${args}"
}
}
You would use it like this:
#Library('utils') import org.foo.Utilities
def utils = new Utilities(steps)
node {
utils.mvn 'clean package'
}

Resources