Wednesday, September 13, 2017

Create HTML dashboard of Jenkins jobs status

Perl script to fetch live jobs' status from Jenkins server and generate and display HTML dashboard from it.

use strict;
use warnings;
use autodie;
use REST::Client;
use MIME::Base64;
use JSON;

my $api_proto = 'http';               #HTTP/HTTPS
my $api_url = 'localhost';       #Server IP
my $api_port = '8080';                #Port number
my $api_user = 'admin';           #Jenkins account username
my $api_pass = 'password';          #Jenkins account password
my $client = REST::Client->new();    #Perl Rest Client Object

$client->addHeader('Authorization', 'Basic '.encode_base64($api_user . ':' . $api_pass));

my $html = "";
$html = $html."<!DOCTYPE html><html><head><title></title></head><body><table style='width:100%'>";
$html = $html."<tr><th>NAME</th><th>COLOR</th><th>URL</th></tr>";

if ($client->responseCode() == 200)
    my $data = decode_json($client->responseContent());
    my @jobs = @{$data->{'jobs'}};
    print("\nTotal ".scalar(@jobs)." jobs found..\n\n");
    foreach my $job (@jobs)
        $html = $html."<tr>";
        $html = $html."<td><font color='".$job->{'color'}."'>".$job->{'name'}."</font></td>";
        $html = $html."<td><font color='".$job->{'color'}."'>".$job->{'color'}."</font></td>";
        $html = $html."<td><a href=".$job->{'url'}."><font color='".$job->{'color'}."'>".$job->{'url'}."</font></a></td>";
        $html = $html."</tr>";

    print("\ncould not connect to jenkins server... :( :(\n");

$html = $html."</table></body></html>";

open (my $fh, ">Jenkins Dashboard.html") or die("Could not open file. $!");
print $fh $html;
close $fh;

system("Jenkins Dashboard.html");