Jenkins Typical pipeline leverage Groovy closure - unix1998/technical_notes GitHub Wiki

In Jenkins, we can use Groovy closures to create reusable and modular code that can be stored in a shared library. This approach allows you to define the main framework or architecture of your CI/CD pipeline in a reusable way, and then call it from your Jenkinsfile with specific parameters. Here’s how it works in more detail:

  1. Create a Shared Library: Define your reusable pipeline steps or stages as Groovy scripts (usually stored in a Git repository). These scripts can include the main framework or architecture of your pipeline.

  2. Define the Groovy Closure: Write a Groovy script that encapsulates the common logic of your pipeline in a closure. This closure can accept parameters such as the source code URL, build tool, artifact repository, etc.

  3. Load the Shared Library in Jenkins: Configure Jenkins to use the shared library. This can be done in the Jenkins global configuration under "Global Pipeline Libraries" or by specifying the library in your Jenkinsfile using the @Library annotation.

  4. Use the Closure in Your Jenkinsfile: In your Jenkinsfile, call the closure defined in the shared library, passing the necessary parameters. This allows you to execute the pipeline with different configurations without duplicating code.

Here’s a simplified example to illustrate this process:

1. Define the Shared Library (e.g., vars/pipelineFramework.groovy):

def call(Map params) {
    pipeline {
        agent any

        stages {
            stage('Checkout') {
                steps {
                    git url: params.sourceCodeUrl
            stage('Build') {
                steps {
                    sh "${params.buildTool} clean install"
            stage('Publish') {
                steps {
                    // Assuming you are using Maven for artifact publishing
                    sh "mvn deploy -Drepository.url=${params.artifactRepo}"

2. Load the Library in Jenkins:

Configure the library in Jenkins global settings or use the @Library annotation in your Jenkinsfile.

3. Use the Closure in Your Jenkinsfile:

@Library('your-shared-library') _

    sourceCodeUrl: '',
    buildTool: 'mvn',
    artifactRepo: 'http://your-artifact-repo/repository'

In this example:

  • pipelineFramework is the name of the closure defined in the shared library.
  • Parameters like sourceCodeUrl, buildTool, and artifactRepo are passed to the closure, allowing for a flexible and reusable pipeline configuration.

This approach allows you to maintain a clean and modular pipeline structure, making it easier to manage and scale your CI/CD processes.