Search This Blog

Tuesday, December 11, 2018

Jenkins JSON API usage

<?php



class Jenkins
{

private $crumb_field;
private $crumb_value;

/**
* Undocumented check the jenkins url is active
*
* @return boolean
*/
function isActive()
{
$response = \Httpful\Request::get(JENKINS_URL . 'api/json/')
->expectsJson()
->authenticateWith(JENKINS_USER, JENKINS_PASS)
->send();

return isset($response->body->assignedLabels[0]->name);

}
function getVersion()
{

$response = \Httpful\Request::get(JENKINS_URL . 'api/json/')

->expectsJson()

->authenticateWith(JENKINS_USER, JENKINS_PASS)
->send();
}
/**
*
* getLastBuild information for the $jobName sent
* @param mixed $jobName - Valid job name
*/

function getLastBuildInfo($jobName)
{

$response = \Httpful\Request::get(JENKINS_URL . '/job/' . $jobName . '/lastBuild/api/json')
->expectsJson()
->authenticateWith(JENKINS_USER, JENKINS_PASS)
->send();
return $response->body;
}
/**
* get all available jobs from the Jenkins with basic information
*
* @return Object
*/
function getJobs()
{
$response = \Httpful\Request::get(JENKINS_URL . '/api/json?tree=jobs[name,color,url,description,buildable,inQueue,healthReport,lastStatbleBuild,lastUnstableBuild,lastSuccessfulBuild,lastFailedBuild]')
->expectsJson()
->authenticateWith(JENKINS_USER, JENKINS_PASS)
->send();
return $response->body;
}
/**
* get config.xml for the jobname passed from Jenkins URL
*
* @param [string] $jobName
* @return Object
*/
function getJobConfig($jobName)
{

$response = \Httpful\Request::get(JENKINS_URL . 'job/' . $jobName . '/config.xml')
->expectsXml()
->authenticateWith(JENKINS_USER, JENKINS_PASS)
->send();
return $response;
}
/**
* trigger a job
*
* @param [string] $jobName
* @return Object
*/
function buildJob($jobName)
{
if ($this->crumb_field == '' || $this->crumb_value == '') {
$this->getCrumb();
}
$response = \Httpful\Request::post(JENKINS_URL .'job/'.$jobName .'/build')
->addHeader($this->crumb_field, $this->crumb_value)
->authenticateWith(JENKINS_USER, JENKINS_PASS)
->send();
return $response;
}
/**
* Get crumb information
*
* @return void
*/
function getCrumb()
{
$response = \Httpful\Request::get(JENKINS_URL . 'crumbIssuer/api/json')
->authenticateWith(JENKINS_USER, JENKINS_PASS)
->expectsJson()
->send();
$this->crumb_field = $response->body->crumbRequestField;
$this->crumb_value = $response->body->crumb;
}
/**
* Copy job to a new name
*
* @param [type] $from - Jobname
* @param [type] $to - Jobname
* @return Object
*/
function createJob($from, $to)
{

if ($this->crumb_field == '' || $this->crumb_value == '') {
$this->getCrumb();
}
$response = \Httpful\Request::post(JENKINS_URL . 'createItem?name=' . $to . '&from=' . $from . '&mode=copy')
->addHeader($this->crumb_field, $this->crumb_value)

->authenticateWith(JENKINS_USER, JENKINS_PASS)
->send();
return $response;
}

}