R Kaja Mohideen
R Kaja Mohideen

Reputation: 917

How to use Jenkins Pipeline Folder-Level Shared Library?

We have few components which is stored in their own git repositories. Specific combination of those components are built and delivered as solutions for different type of deployments/customers. So, we have a pipeline git repository which has multiple Jenkinsfile (with different names - and so the build names).

Obviously, there are many things common between these pipelines. I'm aware of Jenkins shared library and it works when they're given their own git repository. But, since my pipelines are already in dedicated git repository, I'm curious to know how to use "Folder-level Shared Libraries" explained here --> https://jenkins.io/doc/book/pipeline/shared-libraries/#folder-level-shared-libraries

But, I'm not able to figure out how to use this Folder-level shared libraries. I couldn't find any examples/documentation for this style of libraries.

Any pointers to documentation/example - or guidelines on how to go with this will be greatly appreciated.

Thanks.

Upvotes: 11

Views: 8653

Answers (2)

dahaze
dahaze

Reputation: 23

First: To use the Folder-level shared library, you have to create the standard library structure and commit it to a SCM repository.

Second: You have to configure jenkins to use the library in the options dialog of the folder where your pipeline is located.

Simple example with scripted pipeline and no extra repository for the library:

"<URL>/my-test-repo.git"
    |
    |- <JenkinsPipelineScript>
    |
    |- "jenkins_lib"
        |
        |- resources
        |- src
        |- vars
            |- "HelloWorld.groovy"

So in your JenkinsPipelineScript just import the library by

@Library('jenkins_lib') _

and call the "HelloWord.groovy" by

HelloWorld()

The HelloWorld.groovy can look like this:

def call() {
sh "echo Hello world from library-script!" 
}

Upvotes: 0

Pawel Wiejacha
Pawel Wiejacha

Reputation: 722

I guess that proper way to do that is to implement a custom SCMRetriever and use library step.

However, you can use the following hack:

Assuming jenkins/vars/log.groovy in your local repo contains:

def info(message) {
    echo "INFO: ${message}"
}

Your Jenkinsfile can load that shared library from the jenkins/ directory using library step:

node('node1') { // load library
    checkout scm
    // create new git repo inside jenkins subdirectory
    sh('cd jenkins && git init && git add --all . && git commit -m init &> /dev/null') 
    def repoPath = sh(returnStdout: true, script: 'pwd').trim() + "/jenkins"
    library identifier: 'local-lib@master', retriever: modernSCM([$class: 'GitSCMSource', remote: repoPath])
}

node('node2') {
    stage('Build') {
        log.info("called shared lib") // use the loaded library
    }
}

Upvotes: 5

Related Questions