Can I import a groovy script from a relative directory into a Jenkins file?

I have a project structured as follows:

/ / Jenkinsfile / build_tools / / pipeline.groovy # Functions which define the pipeline / reporting.groovy # Other misc build reporting stuff / dostuff.sh # A shell script used by the pipeline / domorestuff.sh # Another pipeline supporting shell-script 

Is it possible to import groovy files into / build _tools so that I can use the functions inside these two files in my Jenkins file?

Ideally, I would like to have a Jenkins file that looks something like this (pseudocode):

 from build_tools.pipeline import build_pipeline build_pipeline(project_name="my project", reporting_id=12345) 

The bit I'm stuck on is how you write the working equivalent of this pretentious import statement in line # 1 of my pseudocode.

PS. Why I do this: the build_tools folder is actually a git submodule shared by many projects. I am trying to give each project access to a common set of building tools to stop every project developer from reusing this wheel.

+4
source share
1 answer

The best way to download common groovy code is with shared libraries .

If you have a shared library:

 simplest-jenkins-shared-library master % cat src/org/foo/Bar.groovy package org.foo; def awesomePrintingFunction() { println "hello world" } 

Drag it to the original control, configure it in your jenkins work, or even globally (this is one of the only things you do through the Jenkins user interface when using the pipeline), as in this screenshot:

tell jenkins about a shared library

and then use it, for example, as follows:

 pipeline { agent { label 'docker' } stages { stage('build') { steps { script { @Library('simplest-jenkins-shared-library') def bar = new org.foo.Bar() bar.awesomePrintingFunction() } } } } } 

The output from the console log for this assembly, of course, will include:

 hello world 

There are many other ways to write shared libraries (e.g. using classes) and using them (e.g. defining vars so you can use them in Jenkinsfiles in super-slick ways). You can even upload non-groovy files as resources. Check out the shared library docs for these extended use cases.

+7
source

All Articles