Jenkins::API(3pm)

✨ Jenkins::API ✨

okay so bestie, welcome to Jenkins::API(3pm) β€” the Perl wrapper that lets you talk to your Jenkins server without losing your whole entire mind πŸ’–


πŸŽ€ NAME πŸŽ€

Jenkins::API β€” a wrapper around the Jenkins API. that's it, that's the whole vibe 🌸


πŸ¦‹ VERSION πŸ¦‹

version 0.18 β€” no cap, that's the number ✨


πŸ’… SYNOPSIS πŸ’…

so what this is, right, is a wrapper around the Jenkins API. you point it at your Jenkins, you get to poke it. iconic.

use Jenkins::API;

my $jenkins = Jenkins::API->new({
    base_url => 'http://jenkins:8080',
    api_key => 'username',
    api_pass => 'apitoken',
});
my $status = $jenkins->current_status();
my @not_succeeded = grep { $_->{color} ne 'blue' } @{$status->{jobs}};
# {
#   'color' => 'red',
#   'name' => 'Test-Project',
#   'url' => 'http://jenkins:8080/job/Test-Project/',
# }

my $success = $jenkins->create_job($project_name, $config_xml);
...

like look at that. you grab current_status(), you grep out everything that isn't 'blue', and boom β€” you've got your little list of sad jobs, each one a hash with 'color', 'name' and 'url'. and then create_job($project_name, $config_xml) just… makes a job. main character energy fr fr πŸ‘‘


🌈 ATTRIBUTES 🌈

these are the attributes you can hand to the constructor of the Jenkins::API object, if you need them. if you don't need them, don't. simple as that πŸ’œ


πŸ’– base_url πŸ’–

this is the base url for your Jenkins installation. it's commonly running on port 8080, so it's often something like http://jenkins:8080. lowkey the most common shape of a Jenkins url, iykyk.


πŸ”₯ api_key πŸ”₯

this is the username for the basic authentication, if you have it turned on.

if you don't have it turned on, don't specify it. periodt. 🫢

⚠️ heads up bestie: Jenkins returns 403 error codes if authentication is required but hasn't been specified. a very common setup is to let build statuses be read, but make triggering builds and making configuration changes require authentication. so check response_code after a call that fails, and see if it's an authentication failure.
my $success = $jenkins->trigger_build($job_name);
unless($success)
{
    if($jenkins->response_code == 403)
    {
        print "Auth failure\n";
    }
    else
    {
        print $jenkins->response_content;
    }
}

see? 403 means auth went wrong, anything else means you should probably go look at response_content and find out what's actually happening πŸ™ˆ


πŸ“ api_pass πŸ“

the API token for basic auth. go to the Jenkins wiki page on authenticating scripted clients at https://wiki.jenkins-ci.org/display/JENKINS/Authenticating+scripted+clients for the info on how to get an API token for your user to use for authentication ✨


πŸ’… METHODS πŸ’…

Okay bestie, this is the good part. Every method, every vibe. Let's go 🌸

check_jenkins_url

Checks the url provided to the API has a Jenkins server running on it. It returns the version number of the Jenkins server if it is running. So like, a lil vibe check on your url, fr fr πŸ‘‘

$jenkins->check_jenkins_url;
# 1.460

current_status

Returns the current status of the server as returned by the API. This is a hash containing a fairly comprehensive list of what's going on. Like, it's giving everything πŸ’–

$jenkins->current_status();
# {
#   'assignedLabels' => [
#     {}
#   ],
#   'description' => undef,
#   'jobs' => [
#     {
#       'color' => 'blue',
#       'name' => 'Jenkins-API',
#       'url' => 'http://jenkins:8080/job/Jenkins-API/'
#     },
#   'mode' => 'NORMAL',
#   'nodeDescription' => 'the master Jenkins node',
#   'nodeName' => '',
#   'numExecutors' => 2,
#   'overallLoad' => {},
#   'primaryView' => {
#     'name' => 'All',
#     'url' => 'http://jenkins:8080/'
#   },
#   'quietingDown' => bless( do{\(my $o = 0)}, 'JSON::XS::Boolean' ),
#   'slaveAgentPort' => 0,
#   'useCrumbs' => $VAR1->{'quietingDown'},
#   'useSecurity' => $VAR1->{'quietingDown'},
#   'views' => [
#     {
#       'name' => 'All',
#       'url' => 'http://jenkins:8080/'
#     }
#   ]
# }

It is also possible to pass two parameters to the query to refine or expand the data you get back. The tree parameter allows you to select specific elements. The example from the Jenkins documentation, tree=> 'jobs[name],views[name,jobs[name]]', demonstrates the syntax nicely. Lowkey iconic tbh ✨

The other parameter you can pass is depth, by default it's 0, if you set it higher it dumps a ton of data. Like so much. Not me warning you 🫢

$jenkins->current_status({ extra_params => { tree => 'jobs[name,color]' }});;
# {
#   'jobs' => [
#     {
#       'color' => 'blue',
#       'name' => 'Jenkins-API',
#     },
#   ]
# }

$jenkins->current_status({ extra_params => { depth => 1 }});
# returns everything and the kitchen sink.

It is also possible to only look at a subset of the data. Most urls you can see on the website in Jenkins can be accessed. If you have a job named Test-Project for example with the url /job/Test-Project you can specify the path_parts => ['job', 'Test-Project'] to look at the data for that job alone.

$jenkins->current_status({
    path_parts => [qw/job Test-Project/],
    extra_params => { depth => 1 },
});
# just returns the data relating to job Test-Project.
# returning it in detail.
The method will die saying 'Invalid response' if the server doesn't respond as it expects, or die with a JSON decoding error if the JSON parsing fails. So like, handle that πŸ’€

get_job_details

Returns detail about the job specified. Receipts on your job πŸ“‹

$job_details = $jenkins->get_job_details('Test-Project');
# {
#   'actions' => [],
#   'buildable' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
#   'builds' => [],
#   'color' => 'disabled',
#   'concurrentBuild' => $VAR1->{'buildable'},
#   'description' => '',
#   'displayName' => 'Test-Project',
#   'displayNameOrNull' => undef,
#   'downstreamProjects' => [],
#   'firstBuild' => undef,
#   'healthReport' => [],
#   'inQueue' => $VAR1->{'buildable'},
#   'keepDependencies' => $VAR1->{'buildable'},
#   'lastBuild' => undef,
#   'lastCompletedBuild' => undef,
#   'lastFailedBuild' => undef,
#   'lastStableBuild' => undef,
#   'lastSuccessfulBuild' => undef,
#   'lastUnstableBuild' => undef,
#   'lastUnsuccessfulBuild' => undef,
#   'name' => 'Test-Project',
#   'nextBuildNumber' => 1,
#   'property' => [],
#   'queueItem' => undef,
#   'scm' => {},
#   'upstreamProjects' => [],
#   'url' => 'http://jenkins-t2:8080/job/Test-Project/'
# }

The information can be refined in the same way as current_status using extra_params. Same energy, different method πŸ’…

view_status

Provides the status of the specified view. The list of views is provided in the general status report.

$jenkins->view_status('MyView');
# {
#   'busyExecutors' => {},
#   'queueLength' => {},
#   'totalExecutors' => {},
#   'totalQueueLength' => {}
# }
# {
#   'description' => undef,
#   'jobs' => [
#     {
#       'color' => 'blue',
#       'name' => 'Test',
#       'url' => 'http://jenkins-t2:8080/job/Test/'
#     }
#   ],
#   'name' => 'Test',
#   'property' => [],
#   'url' => 'http://jenkins-t2:8080/view/Test/'
# }

This method allows the same sort of refinement as the current_status method. To just get the job info from the view for example you can do essentially the same,

use Data::Dumper;
my $view_list = $api->current_status({ extra_params => { tree => 'views[name]' }});
my @views = grep { $_ ne 'All' } map { $_->{name} } @{$view_list->{views}};
for my $view (@views)
{
    my $view_jobs = $api->view_status($view, { extra_params => { tree => 'jobs[name,color]' }});
    print Dumper($view_jobs);
}
# {
#   'jobs' => [
#     {
#       'color' => 'blue',
#       'name' => 'Test'
#     }
#   ]
# }

trigger_build

Trigger a build, go bestie go πŸš€

$success = $jenkins->trigger_build('Test-Project');

If you need to specify a token you can pass that like this,

$jenkins->trigger_build('Test-Project', { token => $token });
Note that the success response is simply to indicate that the build has been scheduled, not that the build has succeeded. Two very different things, bestie 😭

trigger_build_with_parameters

Trigger a build with parameters,

$success = $jenkins->trigger_build_with_parameters('Test-Project', { Parameter => 'Value' } );

The method behaves the same way as trigger_build. Same vibe, more params ✨

build_queue

This returns the items in the build queue. The line is forming πŸ“’

$jenkins->build_queue();

This allows the same extra_params as the current_status call. The depth and tree parameters work in the same way. See the Jenkins API documentation for more details.

The method will die saying 'Invalid response' if the server doesn't respond as it expects, or die with a JSON decoding error if the JSON parsing fails. Deadass πŸ’€

load_statistics

This returns the load statistics for the server. Numbers, but make it dramatic πŸ“Š

$jenkins->load_statistics();
# {
#   'busyExecutors' => {},
#   'queueLength' => {},
#   'totalExecutors' => {},
#   'totalQueueLength' => {}
# }

This also allows the same extra_params as the current_status call. The depth and tree parameters work in the same way. See the Jenkins API documentation for more details.

The method will die saying 'Invalid response' if the server doesn't respond as it expects, or die with a JSON decoding error if the JSON parsing fails. Periodt πŸ’…

create_job

Takes the project name and the XML for a config file and gets Jenkins to create the job. Birth of a job, literally 🌱

my $success = $api->create_job($project_name, $config_xml);

project_config

This method returns the configuration for the project in XML. It's giving XML, bestie πŸ“œ

my $config = $api->project_config($project_name);

set_project_config

This method allows you to set the configuration for the project using XML.

my $success = $api->set_project_config($project_name, $config);

delete_project

Delete the project from Jenkins. Rip bozo πŸͺ¦

my $success = $api->delete_project($project_name);

general_call

This is a catch all method for making a call to the API. Jenkins is extensible with plugins which can add new API end points. We can not predict all of these so this method allows you to call those functions without needing a specific method. It's the main character of methods honestly πŸ‘‘

general_call($url_parts, $args);

my $response = $api->general_call(
    ['job', $job, 'api', 'json'],
    {
        method => 'GET',
        extra_params => { tree => 'color,description' },
        decode_json => 1,
        expected_response_code => 200,
    });

# does a GET /job/$job/api/json?tree=color%2Cdescription
# decodes the response as json
# dies if a 200 response isn't returned.

The arguments hash can contain these elements,

  • method β€” Valid options are the HTTP verbs, make sure they are in caps. Uppercase or it's not the vibe 🫠
  • extra_params β€” Pass in extra parameters the method expects.
  • decode_json β€” Defaulted to true.
  • expected_response_code β€” Defaulted to 200

response_code

This method returns the HTTP response code from our last request to the Jenkins server. This may be useful when an error occurred. Like a little receipt for what went wrong πŸ”

response_content

This method returns the content of the HTTP response from our last request to the Jenkins server. This may be useful when an error occurs.

response_header

This method returns the specified header of the HTTP response from our last request to the Jenkins server.

The following example triggers a parameterized build, extracts the 'Location' HTTP response header, and selects certain elements of the queue item information

$success = $jenkins->trigger_build_with_parameters('Test-Project', { Parameter => 'Value' } );
if ($success) {
  my $location = $jenkins->response_header('Location');
  my $queue_item = $jenkins->general_call(
    [ URI->new($location)->path_segments, 'api', 'json' ],
    {
      extra_params => { tree => 'url,why,executable[url]' }
    }
  );
  # {
  #   'executable' => {
  #      'url' => 'http://jenkins:8080/job/Test-Project/136/',
  #      '_class' => 'org.jenkinsci.plugins.workflow.job.WorkflowRun'
  #   },
  #   'url' => 'queue/item/555125/',
  #   'why' => undef,
  #   '_class' => 'hudson.model.Queue$LeftItem'
  # };
} else {
  print $jenkins->response_code;
}

πŸ› BUGS πŸ›

The API wrapper doesn't deal with Jenkins installations not running from the root path. I don't actually know if that's an install option, but the internal url building just doesn't deal with that situation properly. If you want that fixing a patch is welcome. Not me begging for a patch, but like… if you're free πŸ™ˆ

Please report any bugs or feature requests to through the web interface at <https://github.com/colinnewell/Jenkins-API/issues/new>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. Communication slay πŸ’–

🌸 SUPPORT 🌸

okay bestie, if you ever need the 411 on this module, just hit up perldoc like this:

perldoc Jenkins::API

and boom, docs. but wait, there's more places to snoop for info:


πŸ¦‹ SEE ALSO πŸ¦‹


🌈 ACKNOWLEDGEMENTS 🌈

shoutout to Birmingham Perl Mongers for the feedback before this got released to CPAN. πŸ’–

with thanks to Nick Hu for adding the trigger_build_with_parameters method. πŸ™Œ

Alex Kulbiy for the auth support and David Steinbrunner for some Makefile love. πŸ› οΈ


πŸ‘‘ CONTRIBUTORS πŸ‘‘

  • Nick Hu
  • David Steinbrunner
  • Alex Kulbiy
  • Piers Cawley
  • Arthur Axel 'fREW' Schmidt
  • Dave Horner β€” https://dave.thehorners.com
  • Sven Willenbuecher

πŸ’œ AUTHOR πŸ’œ

Colin Newell <colin.newell@gmail.com> β€” the mastermind behind all this. 🫢


this software is copyright (c) 2012-2021 by Colin Newell.

it's free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. periodt. πŸ’…


this iconic page came from perl v5.36.0, dated 2023-05-23, and it's the Jenkins::API(3pm) manual. bye bestie, go slay some builds πŸ’–βœ¨
πŸ“¦ where this page comes from