Jenkins REST API call triggers job and passes parameters

Posted on October 3rd, 2015 at 11:00 AM


The job being triggered will require 'This build is parameterised' to be set and in this case a String Parameter declared as STRPARAM. The job also needs 'Trigger builds remotely' set in 'Build Triggers' and an Authentication Token string declared, in this case 'build'. This provides very basic security.
 

 
The job uses STRPARAM at the Build stage just like any other environment variable. Create a html file, say trigger-job.html, to make a XMLHTTPRequest (XHR) and place in the /var/lib/jenkins/userContent folder on your Jenkins server. Start the trigger process by calling URL http://%JENKINS-SERVER%:8080/userContent/trigger-job.html where %JENKINS-SERVER% is your server location. Once triggered however the Jenkins job sends little in the way of response except for a Location response header and of course the job starts to execute.
 

 
Add the javscript below to your html page. Call the XHR request function from say window.onload or another event.

function request() 
{
  xmlhttp = false;   
  xmlhttp = new XMLHttpRequest();   // ok for latest IE, Chrome, Firefox and Safari

  xmlhttp.onreadystatechange = handleStateChange;
  var server = "http://%JENKINS-SERVER%:8080"; // substitute %JENKINS-SERVER%
  var path = "/view/%VIEW%/job/";              // substitute %VIEW% and append any sub-views
  var job = "testjob";                         // name of job to be triggered
  var query = "/buildWithParameters?token=" ;
  var buildtoken = "build";                    // authentication token set in triggered job
  var parametername = "STRPARAM";
  var parameterstr = "%YOURSTRING%";           // substitute your string value
  var url = server + path + job + query + buildtoken + '&' + parametername + '=' + parameterstr;
  xmlhttp.open("GET",url,true); // async xhr call
  xmlhttp.send(null);
}

var handleResponse = function (status, response, header) 
{ 
  // handle XHR response
  // jenkins build trigger call only returns responseheader
}

var handleStateChange = function () 
{
  switch (xmlhttp.readyState) 
  {
    case 0 : // UNINITIALIZED
    case 1 : // LOADING
    case 2 : // LOADED
    case 3 : // INTERACTIVE
      break;
    case 4 : // COMPLETED
      handleResponse(xmlhttp.status, xmlhttp.responseXML, xmlhttp.getResponseHeader ("Location")); 
      break;
    default: alert("error");
  }
}