Can we use a single jenkins file for multibranch piepeline in jenkins using shared libraries?

432 Views Asked by At

I am trying to write a jenkinsfile which will take the data from shared libraries in jenkins for multibranch pipeline, something like below:-

@Library('Template')_

if (env.BRANCH_NAME == 'master') {
    jenkins1(PROJECTNAME: 'test', GITURL: 'http://test/test.git')
    } else {
        jenkins2(PROJECTNAME: 'test1', GITURL: 'http:////test/test.git')
    }

so the pipeline take the shared library depending upon the if condition, if the branch is master if statement data should work or else should be build.

1

There are 1 best solutions below

2
On

Yes that’s possible. Actually we’re using a multibranch project to test our changes to our shared library that way.

You have to use the library step to load the library instead of the @Library annotation, like:

if (condition) {
    library(‘someLib@${env.BRANCH_NAME}’)
} else {
    library(‘someOtherLib’)
}

See https://jenkins.io/doc/pipeline/steps/workflow-cps-global-lib/#library-load-a-shared-library-on-the-fly for all details.

By the way: In case you’re planning to do Pull Requests the following Post might be useful to you as well: https://stackoverflow.com/a/51915362/4279361