12

Adding a Shared Script for Jenkins

 3 years ago
source link: https://www.alexaitken.nz/blog/adding-a-shared-script-for-jenkins/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Adding a Shared Script for Jenkins

October 1, 2018 By Alex Leave a Comment

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.

String getSomeCommonVariableFromFunction() { return "You probably won't need to do this often" }

return this

def common def myCommonVariable

pipeline { agent { docker { label 'Linux' } } stages { stage('Set up ENV variables that need common Library') { steps { script { common = evaluate readTrusted('./file.groovy') myCommonVariable = common.getSomeCommonVariableFromFunction() } } } } }

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. 

Reposted on Medium.

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK