5

I want to create a first shared library to factorize my code in jenkins pipelines. For example, I use two notify methods for all my pipelines and I would like to have them in one location. So I searched how to create a shared library, and I have done this :

project tree

In my Notify class, my methods :

#!/usr/bin/env groovy

package fr.enterprise

class Notify {
    static def notifySuccessful(String targetEnv) {
        emailext (
            subject: "SUCCESSFUL: New version deployed on $targetEnv",
            body: """<html>
                <body>
                Go try it now! It's better when it's hot.
                <br>
                <br>With love,
                <br>Your Dear Jenkins
                </body>
                </html>""",
            recipientProviders: [[$class: 'RequesterRecipientProvider']]
        )
    }

    static def notifyFailed(String targetEnv, String jobName, String buildUrl, String buildNumber) {
        emailext (
            subject: "FAILURE: Couldn't deploy new version on $targetEnv",
            body: """<html>
                <body>
                I'm really sorry, but something went wrong when deploying Fides.
                <br>
                Please have a look at the logs here:
                <br><a href="$buildUrl/console">$jobName [$buildNumber]</a>
                <br>
                <br>With love,
                <br>Your Dear Jenkins
                </body>
                </html>""",
            recipientProviders: [[$class: 'RequesterRecipientProvider']]
        )
    }
}

I import it in my pipeline code :

@Library('jenkins-shared-lib')
import fr.enterprise.Notify

And in jenkins : jenkins config

When my pipeline want use one of my method, I have this error :

groovy.lang.MissingMethodException: No signature of method: java.lang.Class.emailext() is applicable for argument types: (java.util.LinkedHashMap)

What have I forgot ?

Here my code to call my methods :

success {
  script {
    Notify.notifySuccessful(params.TARGET_ENV)
  }
}
failure {
  script {
    Notify.notifyFailed(params.TARGET_ENV, env.JOB_NAME, env.BUILD_URL, env.BUILD_NUMBER)
  }
}
Franck Cussac
  • 310
  • 1
  • 3
  • 14

1 Answers1

0

From Jenkins docs: Library classes cannot directly call steps such as sh or git (or the one you are using). In order to do it you should do something like this

Notify.groovy

#! /usr/bin groovy

def notifySuccessful(String targetEnv) {
        your code
}
return this

note the usage of return this.
and then from the pipeline the declaration you can use it

@Library('jenkins-shared-lib') _


def notify = new fr.enterprise.Notify()
notify.notifySuccessful("var")
AplusP
  • 21
  • 2