Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save marcosborges/4ad3896b42608eff13489e4695d3c961 to your computer and use it in GitHub Desktop.
Save marcosborges/4ad3896b42608eff13489e4695d3c961 to your computer and use it in GitHub Desktop.
import jenkins.model.Jenkins
import jenkins.plugins.git.GitSCMSource
import jenkins.plugins.git.traits.BranchDiscoveryTrait
import org.jenkinsci.plugins.workflow.libs.GlobalLibraries
import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration
import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever
def sharedLibraryName = "mySharedLibName"
def repository = "git@github.com:[OWNER]/[REPO].git"
if (! Jenkins.instance.getDescriptor(GlobalLibraries).getLibraries().findAll{ it.getName() == sharedLibraryName }) {
def libraries = Jenkins.instance.getDescriptor(GlobalLibraries).getLibraries()
def scm = new GitSCMSource(repository)
scm.traits = [new BranchDiscoveryTrait()]
def library = new LibraryConfiguration(sharedLibraryName, new SCMSourceRetriever(scm))
library.defaultVersion = "master"
library.implicit = true
library.allowVersionOverride = true
library.includeInChangesets = false
libraries << library
def gSettings = Jenkins.instance.getExtensionList(GlobalLibraries.class)[0]
gSettings.libraries = libraries
gSettings.save()
println 'Global Shared Libraries configured succefully'
}
@user-muthu
Copy link

How to use this and what is the purpose of this script?

@marcosborges
Copy link
Author

Hi again @mydearmuthu1978

This script is also to be run in the Jenkins script console.

From line 1 to 6 are imports of the classes that the script will use.

In line 8 there is the variable that contains the name you want to use to register your shared library.

In line 9 is the address of the GIT repository where your shared library is.

In line 11 there is a condition that the installation code will only be executed if the shared library is not installed.

In line 12 I get all shared libraries already registered with Jenkins.

In lines 13 and 14 I initialize a class that is responsible for git information.

In lines 15 to 19 I initialize the class responsible for configuring the shared library.

In line 20 added this new library to the list of existing libraries.

From line 21 to 13 I save this new shared library.

@user-muthu
Copy link

Thank you so much Marcos

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment