In this post, we look into loading and reusing independent Groovy scripts for more modular and testable Jenkins pipeline.
An example with Scripted Pipeline is provided although it is also applicable to newer Declarative Pipeline with minor modifications.
Keep in mind that Jenkins Shared Libraries is the more scalable alternative to run and reuse custom Groovy scripts in Jenkins pipeline.
Basic example of Loading Groovy scripts
script example.groovy
123456789
def example1() {
println 'Hello from example1'
}
def example2() {
println 'Hello from example2'
}
return this
The example.groovy script defines example1 and example2 functions before ending with return this.
Note that return this is definitely required and one common mistake is to forget ending the Groovy script with it.
In Jenkinsfile, simply use load step to load the Groovy script.
After the Groovy script is loaded, the functions insides can be used where it can be referenced, as shown above.
Demo: Processing Github JSON from Groovy
In this demo, we first show how to process JSON response from Github API in Groovy.
Processing JSON from Github
1234567891011121314151617
Stringusername=System.getenv('GITHUB_USERNAME')Stringpassword=System.getenv('GITHUB_PASSWORD')StringGITHUB_API='https://api.github.com/repos'Stringrepo='groovy'StringPR_ID='2'// Pull request IDStringurl="${GITHUB_API}/${username}/${repo}/pulls/${PR_ID}"println"Querying ${url}"deftext=url.toURL().getText(requestProperties:['Authorization':"token ${password}"])defjson=newJsonSlurper().parseText(text)defbodyText=json.body// Check if Pull Request body has certain textif(bodyText.find('Safari')){println'Found Safari user'}
The equivalent bash command for retrieving JSON response from Github API is as follows:
Continuing the demo from the last section, we now put the Groovy code into a callable function in a script called “github.groovy”.
Then, in our Jenkinsfile, we proceed to load the script and use the function to process JSON response from Github API.
When loading and running Groovy scripts, you might find yourself running to RejectedAccessException errors.
In those cases, usually it can be resolved by manually approving some method signatures in Jenkins > Manage Jenkins > In-process Script Approval page.
Adminstrators privilege is required for doing so.
More troubleshooting information is listed in this blog post.