jenkinsgroovyjenkins-pipeline

How to implement and invoke utility methods in Jenkins pipelines?


I want to implement reusable functions/methods to use in my Jenkins pipeline:

 listAllUnitTests([
      $class: 'MyUtilities',
      arg1: 'foo',
      arg2: 'bar'
      ])

What's not clear is how to actually do it; is this a plugin, extension, something else?

I started with something familiar, such as Git checkout:

node {
    checkout([
         $class: 'GitSCM',
         branches: scm.branches,
         extensions: scm.extensions,
         userRemoteConfigs: scm.userRemoteConfigs
    ])
 }

Looking at the source for GitSCM, a Jenkins plugin, the checkout method appears to be fairly standard; no special annotations or anything else, although I'm not sure how the pipeline arguments align with the method signature because there's clearly a mismatch. I suspect I'm on the wrong track.

@Override
public void checkout(
   Run<?, ?> build,
   Launcher launcher,
   FilePath workspace,
   TaskListener listener,
   File changelogFile,
   SCMRevisionState baseline)
        throws IOException, InterruptedException {

How do I implement parameterized functionality to invoke from Jenkins pipelines to achieve something like this?

node {
  stage('test'){

     myUtilMethod([
          $class: 'MyUtilities',
          arg1: 'foo',
          arg2: 'bar'
          ])
  }
}

Solution

  • You can implement one or more libraries using https://github.com/jenkinsci/workflow-cps-global-lib-plugin/

    I recommend explicitly specifying that you need the library (with the @Library annotation as mentioned in the page above), and not make it implicitly available. This way you can use a specific branch of it on test jobs while developing and testing your library.

    Check out fabric8 for a pretty comprehensive set of examples: https://github.com/fabric8io/fabric8-pipeline-library