From cc50aca2b2620b6005e0f8770b5140cf55671015 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Steven!=20Ragnar=C3=B6k?= Date: Sat, 29 Apr 2017 17:22:25 -0400 Subject: [PATCH] Use current Jenkins plugin API to generate puppet class for plugins. This script can connect to a live jenkins instance and fetch plugin data, then output a puppet class with the plugin versions and dependencies specified. This does not handle the job of configuring any plugins, that still needs to be done manually. There's lots of cleanup to be done with this script but I'm satisfied enough for a Saturday afternoon. --- scripts/jenkins_plugins.py | 52 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100755 scripts/jenkins_plugins.py diff --git a/scripts/jenkins_plugins.py b/scripts/jenkins_plugins.py new file mode 100755 index 00000000..3a3deb63 --- /dev/null +++ b/scripts/jenkins_plugins.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""Fetch and format currently installed Jenkins plugins as puppet configuration. +""" + +import json +import sys + +from argparse import ArgumentParser +from base64 import b64encode +from datetime import datetime +from urllib.request import Request, urlopen + +resource_template = """ ::jenkins::plugin {{ '{name}': + version => '{version}', + require => {dependency_list} + }} +""" + +def main(): + parser = ArgumentParser(description="Generate a puppet class for currently installed Jenkins plugins.") + parser.add_argument("--username") + parser.add_argument("--password") + parser.add_argument("--jenkins") + args = parser.parse_args(sys.argv[1:]) + generate_class(args) + + +def generate_class(args): + print("# This module was automatically generated on {0:%Y-%m-%d %H:%M:%S}".format(datetime.now())) + print("# Instead of editing it, update plugins via the Jenkins web UI and rerun the generator.") + print("# Otherwise your changes will be overwritten the next time it is run.") + print("class profile::jenkins::rosplugins {") + ciurl = "http://{}/pluginManager/api/json?depth=5".format(args.jenkins) + plugin_request = Request(ciurl) + plugin_request.add_header("Authorization", authorization_header_for(args.username, args.password)) + response = urlopen(plugin_request) + parsed = json.loads(response.read().decode()) + for plugin in sorted(parsed['plugins'], key=lambda p: p['shortName']): + dependencies = ", ".join(["Jenkins::Plugin['{}']".format(dep['shortName']) + for dep in sorted(plugin['dependencies'], key=lambda d: d['shortName'])]) + print(resource_template.format(name=plugin['shortName'], version=plugin['version'], + dependency_list="[ " + dependencies + " ]")) + print("}") + + +def authorization_header_for(username, password): + encoded = b64encode((username + ":" + password).encode('ascii')) + return "Basic {}".format(encoded.decode('ascii')) + + +if __name__ == '__main__': + main()