While working with Jenkins over time, I realized there were few steps which were common between many jobs, and I was replicating over and over the same lines of code all over the place.
So to centralize the commonly shared code and trigger it from the downstream jobs is I aim to highlight in this blog.
Scenario:
In the above the orange block is a shared code amongst all the 3 downstream Jenkins job. so now the challenge is how to centralize this shared code block into a job of its own so that we don’t have replicate the same definition in each job.
Solution:
The following Groovy code came to the rescue which can be placed as follows:
import jenkins.* import jenkins.model.* import hudson.* import hudson.model.* FreeStyleBuild build = Jenkins.instance.getItemByFullName("Refresh the TFS Repo").scheduleBuild2(0).get(); Result result = build.getResult(); if(result == Result.FAILURE){ throw new Exception("Refresh from TFS Repo AzureDevOps Failed.") }
In the above code just insert the name of the job you would like to call in your downstream project and Voila, the shared job structure is now in place where unnecessary replication of same code block is avoided.
The above code block ensures that the downstream job step only progresses upon the condition the shared code block has executed successfully.
I hope the above helps.