Implemented Jenkins global libs configuration by salt.
Change-Id: Iff800389488171789205605526d0baec38ba947a
diff --git a/README.rst b/README.rst
index e86ae05..fe3421d 100755
--- a/README.rst
+++ b/README.rst
@@ -573,9 +573,22 @@
team_domain: example.com
token: slack-token
room: slack-room
- token_credential_id: cred_id
+ token_credential_id: cred_id
send_as: Some slack user
+Pipeline global libraries setup
+
+.. code-block:: yaml
+
+ jenkins:
+ client:
+ lib:
+ my-pipeline-library:
+ enabled: true
+ url: https://path-to-my-library
+ credential_id: github
+ branch: master # optional, default master
+ implicit: true # optional default true
Usage
=====
diff --git a/_states/jenkins_lib.py b/_states/jenkins_lib.py
new file mode 100644
index 0000000..6f00f6e
--- /dev/null
+++ b/_states/jenkins_lib.py
@@ -0,0 +1,128 @@
+import logging
+logger = logging.getLogger(__name__)
+
+config_global_libs_groovy = """\
+import org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever;
+import org.jenkinsci.plugins.workflow.libs.LibraryConfiguration;
+import jenkins.plugins.git.GitSCMSource;
+
+def globalLibsDesc = Jenkins.getInstance().getDescriptor("org.jenkinsci.plugins.workflow.libs.GlobalLibraries")
+def existingLib = globalLibsDesc.get().getLibraries().find{{
+ (!it.retriever.class.name.equals("org.jenkinsci.plugins.workflow.libs.SCMSourceRetriever") ||
+ it.retriever.scm.remote.equals("{url}") &&
+ it.retriever.scm.credentialsId.equals("{credential_id}")) &&
+ it.name.equals("{lib_name}") &&
+ it.defaultVersion.equals("{branch}") &&
+ it.implicit == true
+}}
+if(existingLib){{
+ print("EXISTS")
+}}else{{
+ SCMSourceRetriever retriever = new SCMSourceRetriever(new GitSCMSource(
+ "{lib_name}",
+ "{url}",
+ "{credential_id}",
+ "*",
+ "",
+ false))
+ LibraryConfiguration library = new LibraryConfiguration("{lib_name}", retriever)
+ library.setDefaultVersion("{branch}")
+ library.setImplicit({implicit})
+ globalLibsDesc.get().getLibraries().add(library)
+ print("SUCCESS")
+}}
+""" # noqa
+
+remove_global_libs_groovy = """\
+def globalLibsDesc = Jenkins.getInstance().getDescriptor("org.jenkinsci.plugins.workflow.libs.GlobalLibraries")
+def existingLib = globalLibsDesc.get().getLibraries().removeIf{{it.name.equals("{lib_name}")}}
+if(existingLib){{
+ print("DELETED")
+}}else{{
+ print("NOT PRESENT")
+}}
+"""
+
+def present(name, url, branch="master", credential_id="", implicit=True, **kwargs):
+ """
+ Jenkins Global pipeline library present state method
+
+ :param name: pipeline library name
+ :param url: url to remote repo
+ :param branch: remote branch
+ :param credential_id: credential id for repo
+ :param implicit: implicit load boolean switch
+ :returns: salt-specified state dict
+ """
+ test = __opts__['test'] # noqa
+ ret = {
+ 'name': name,
+ 'changes': {},
+ 'result': False,
+ 'comment': '',
+ }
+ result = False
+ if test:
+ status = "SUCCESS"
+ ret['changes'][name] = status
+ ret['comment'] = 'Jenkins pipeline lib config %s %s' % (name, status.lower())
+ else:
+ call_result = __salt__['jenkins_common.call_groovy_script'](
+ config_global_libs_groovy, {"lib_name":name,
+ "url": url,
+ "branch": branch,
+ "credential_id": credential_id if credential_id else "",
+ "implicit": "true" if implicit else "false"
+ })
+ if call_result["code"] == 200 and call_result["msg"] in ["SUCCESS", "EXISTS"]:
+ status = call_result["msg"]
+ if status == "SUCCESS":
+ ret['changes'][name] = status
+ ret['comment'] = 'Jenkins pipeline lib config %s %s' % (name, status.lower())
+ result = True
+ else:
+ status = 'FAILED'
+ logger.error(
+ "Jenkins pipeline lib API call failure: %s", call_result["msg"])
+ ret['comment'] = 'Jenkins pipeline lib API call failure: %s' % (call_result[
+ "msg"])
+ ret['result'] = None if test else result
+ return ret
+
+
+def absent(name, **kwargs):
+ """
+ Jenkins Global pipeline library absent state method
+
+ :param name: pipeline library name
+ :returns: salt-specified state dict
+ """
+ test = __opts__['test'] # noqa
+ ret = {
+ 'name': name,
+ 'changes': {},
+ 'result': False,
+ 'comment': '',
+ }
+ result = False
+ if test:
+ status = "SUCCESS"
+ ret['changes'][name] = status
+ ret['comment'] = 'Jenkins pipeline lib config %s %s' % (name, status.lower())
+ else:
+ call_result = __salt__['jenkins_common.call_groovy_script'](
+ remove_global_libs_groovy, {"lib_name":name})
+ if call_result["code"] == 200 and call_result["msg"] in ["DELETED", "NOT PRESENT"]:
+ status = call_result["msg"]
+ if status == "DELETED":
+ ret['changes'][name] = status
+ ret['comment'] = 'Jenkins pipeline lib config %s %s' % (name, status.lower())
+ result = True
+ else:
+ status = 'FAILED'
+ logger.error(
+ "Jenkins pipeline lib API call failure: %s", call_result["msg"])
+ ret['comment'] = 'Jenkins pipeline lib API call failure: %s' % (call_result[
+ "msg"])
+ ret['result'] = None if test else result
+ return ret
diff --git a/jenkins/client/init.sls b/jenkins/client/init.sls
index e5e1552..b1f0b80 100644
--- a/jenkins/client/init.sls
+++ b/jenkins/client/init.sls
@@ -35,6 +35,10 @@
{%- if client.slack is defined %}
- jenkins.client.slack
{%- endif %}
+{%- if client.lib is defined %}
+ - jenkins.client.lib
+{%- endif %}
+
jenkins_client_install:
pkg.installed:
diff --git a/jenkins/client/lib.sls b/jenkins/client/lib.sls
new file mode 100644
index 0000000..341022f
--- /dev/null
+++ b/jenkins/client/lib.sls
@@ -0,0 +1,15 @@
+{% from "jenkins/map.jinja" import client with context %}
+{% for name, lib in client.get("lib",{}).iteritems() %}
+{%- if lib.enabled|default(True) %}
+ global_library_{{ name }}:
+ jenkins_lib.present:
+ - name: {{ lib.get('name', name) }}
+ - url: {{ lib.url }}
+ - credential_id: {{ lib.credential_id }},
+ - branch: {{ lib.get("branch", "master") }}
+{%- else %}
+ global_library_{{ name }}_absent:
+ jenkins_lib.absent:
+ - name: {{ lib.get('name', name) }}
+{%- endif %}
+{% endfor %}
\ No newline at end of file