jenkinsgroovycontinuous-integrationjenkins-pipelinejenkins-groovy

Is there a way to modularize Jenkinsfile while keeping the stage functionality?


I have a enormous Jenkinsfile that I need to modularize to improve maintainability, so what I want to do is seperate build, test and deploy into individual files but each has multiple stages and I don't want to lose the functionality to display each stage on Jenkins and check their errors easily.

Example:

 stages {
        stage('Clone') {}
        stage('Pre Build Clean') {}
        stage('Copy Requirements') {}
        stage('Build') {}
        }

I want to move all of this into build.groovy and call it by

stage('Build') {
    steps {
        script {
            build.buildApp()
        }
    }
}

at the same time maintaining the stage view on Jenkins. Is this possible or is there a better way to do this?


Solution

  • You can reach this by hosting the stages code in an external file.

    // build.groovy
    
    
    def buildStages() {
        return [
            stage('Build 1') {
                // Do not use steps directive here
                // This code will be imported in a steps block (inside Jenkinsfile)
                println 'Build 1'
            },
            stage('Build 2') {
                println 'Build 2'
            },
        ]
    }
    
    return this
    

    You can invoke then the added function in the Jenkinsfile

    pipeline {
        agent any
        stages {
            stage('Import lib'){
                steps {
                    script {
                        buildLib = load 'build.groovy'
                    }
                }
            }
            stage('Build') {
                steps {
                    script {
                        buildLib.buildStages()
                    }
                }
            }
        }
    }
    

    Note that a parent stage will be added. It might not suit your need of maintaining the stage view. The stages view will look like enter image description here