Adding a Shared Script for Jenkins

Alex Aitken
codeburst
Published in
2 min readOct 1, 2018

--

Recently, we discovered that we had a lot of duplication in our build scripts. Pretty much the same copy+paste code everywhere (we have a mono-repository). So, it came to me to try and resolve this duplication of logic across our builds (multiple services).

For context, we use the declarative pipeline, which for some projects involves utilising a docker image to set up dependencies. This makes it harder to include a shared script as things like “load filename.groovy” won’t work. But, there is a way around this.

There is a function, and you use a trusted library that’s in your source code. There are other ways to do this such as specifying a repository where some “shared code” lives and using that. But for us, we wanted a more straightforward way.

evaluate readTrusted(‘./path/to/your/file.groovy’)

Now, you can only do this when you have the source code checked out. We also evaluate our script inside of the pipeline as an extra step — in which we also set some variables that we can use.

So, what’s happening in the file.groovy? Well, it’s pretty simple actually. It’s the same sort of library file you would expect when you use load.

And that’s it. Now your declarative pipeline can have shared code within one repository without having to use the shared library functionality from Jenkins (which looks like a lot of work to me). It also means that you can test this per branch. So, you can make changes on a branch to the common code and test it out before merging to master.

I hope you found this useful. It took me a lot of searching to find this functionality.

Originally published at www.alexaitken.nz on October 1, 2018.

✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.

--

--