Maksim Sorokin
Maksim Sorokin

Reputation: 2404

Handling common updates to Jenkinsfile in multiple branches

We have a project with several long-living branches and multiple short-living branches. We use Jenkins with Pipeline plugin and have Multibranch Pipeline job defined to build our source code. We use Jenkinsfile to describe the build, test and deployment of our project.

Our Jenkinsfile does the job perfectly, however it became a bit complex. We have a certain logic depending on the current branch, etc. E.g. build and deploy docker images only from branches matching a certain pattern.

Thus we strive to keep Jenkinsfile the same in each branch. However, sometimes we need to make an update to the Jenkinsfile and it requires us to update the same file in all the branches.

How to handle such "common updates" to Jenkinsfile in all the branches and still have a possibility to use the "Multibranch Pipeline" job type? Is it possible to have a single Jenkinsfile for the project and still have a possibility to use the "Multibranch Pipeline" job type?

Upvotes: 3

Views: 1398

Answers (1)

Maksim Sorokin
Maksim Sorokin

Reputation: 2404

This can be implemented using Shared Libraries. It is possible to have a single place containing Jenkinsfile logic, and still have "Multibranch Pipeline" job type.

First, create a new repository for your common Jenkinsfile logic with a structure:

(root)
+- vars
|   +- myJobPipeline.groovy

The content of myJobPipeline.groovy is your Jenkinsfile content with some modifications. For example it could be:

#!/usr/bin/groovy

def call(body) {
    def config = [:]
    body.resolveStrategy = Closure.DELEGATE_FIRST
    body.delegate = config
    body()


    # And here goes your original Jenkinsfile content

    node {
        stage('get the code') {
            checkout scm
        }
        stage('npm install') {
            sh 'npm install'
        }
        ...
}

Then, in Jenkins configuration go to Configure System -> Global Pipeline Libraries and define you Shared Library repository.

Lastly, in update your project Jenkinsfile to be:

#!/usr/bin/env groovy

myJobPipeline {
}

The actual pipeline definition will be loaded through the Shared Library.

Upvotes: 2

Related Questions