Thursday 27 October 2016

Jenkins REST API / Remote API


Jenkins is a open source continuous integration tool written in Java.
It is a server-based system running in a servlet container such as Apache Tomcat. It supports SCM tools including AccuRev, CVS, Subversion, Git, Mercurial, Perforce, Clearcase and RTC, and can execute Apache Ant and Apache Maven based projects as well as arbitrary shell scripts and Windows batch commands.

Jenkins has provided the flexibility of accessing it through code by exposing REST based API.



Steps to access Jenkins from REST / Remote API:

Step 1: 

Get to know how to consume or test any REST web services.

Step 2: 

Get the Jenkins URL, locally deployed or on any server.
 Ex: "http://localhost:8080". By default, Jenkins will be setup on port 8080.

Step 3: 

Set up the API Token & Build Token for the build which you need to access from code.

   Setting up Jenkins API Token:
   By Default API token is set for every user. Check if it is set or not.
   User Menu(at the top) --> Configure --> 'Show API Token [Under API Token Section]

   Setting up Jenkins Build Token:
   Goto to Job --> Configure --> Build Triggers --> Check 'Build Triggers Remotely' --> Provide any      string as JobToken.

Step 4: 

Follow the below code snippet


public String url = "";
public String reqMethod = "GET";
public String reqbody = "";
public HashMap  headers;
String JenkUser = "abcd";
String JenkPwd = "xyz";

public static void main(String[] args) {

String jobcase = "BuildDetails";

//Get Auth string to be used in headers by passing credentials
String userAuth = JenkUser  + ":" + JenkPwd;
String authEncoding = new Base64().encodeAsString(userAuth.getBytes());

//Set the Request details like Url, Request Type,Headers,Body
fillRequestDetails(jobcase);
        
//Execute Request & get the Response to parse.
String resp = execute(url, reqMethod, headers,reqbody);

}


public void fillRequestDetails(String jobcase){

switch(jobcase){
case "BuildJob":
url = "http://localhost:8080/job/TestJob/build?token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/xml");
headerParams.put("authorization", authEncoding);
break;

case "BuildDetails":
url = "http://localhost:8080/job/TestJob/10/api/xml?tree=result,timestamp,builtOn&token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/xml");
headerParams.put("authorization", authEncoding);
break;

case "BuildStatus":
url = "http://localhost:8080/job/TestJob/10/api/json?tree=result&token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/json");
headerParams.put("authorization", authEncoding);
break;

case "BuildConsoleLog":
url = "http://localhost:8080/job/TestJob/10/logText/progressiveText?start=0&token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/json");
headerParams.put("authorization", authEncoding);
break;

case "NextBuild":
url = "http://localhost:8080/job/TestJob/nextBuildNumber?token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/xml");
headerParams.put("authorization", authEncoding);
break;

case "JobDescription":
url = "http://localhost:8080/job/TestJob/description?token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/xml");
headerParams.put("authorization", authEncoding);
break;

case "LastBuild":
url = "http://localhost:8080/job/TestJob/lastBuild?token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/xml");
headerParams.put("authorization", authEncoding);
break;

case "lastCompletedBuild":
url = "http://localhost:8080/job/TestJob/lastCompletedBuild?token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/xml");
headerParams.put("authorization", accessString);
break;

case "LastSuccessfulBuild":
url = "http://localhost:8080/job/TestJob/lastSuccessfulBuild?token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/xml");
headerParams.put("authorization", authEncoding);
break;

case "LastFailedBuild":
url = "http://localhost:8080/job/TestJob/lastFailedBuild?token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/xml");
headerParams.put("authorization", authEncoding);
break;

case "StopBuild":
url = "http://localhost:8080/job/TestJob/<buildNo>/stop?token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/xml");
headerParams.put("authorization", authEncoding);
break;

case "DisableJob":
url = "http://localhost:8080/job/TestJob/disable?token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/xml");
headerParams.put("authorization", authEncoding);
break;

case "EnableJob":
url = "http://localhost:8080/job/TestJob/enable?token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/xml");
headerParams.put("authorization", authEncoding);
break;

case "DeleteJob":
url = "http://localhost:8080/job/TestJob/doDelete?token=BuildToken_XYZXYZ";
headerParams = new HashMap<>();
headerParams.put("Content-Type", "application/xml");
headerParams.put("authorization", authEncoding);
break;

default:
break;

 }
}



public String execute(String url,String reqType, HashMap headers, String reqBody) {
String respStr = null;

switch(reqType){
case "GET":
respStr = RestAssured.given().log().all().headers(headerParams).get(url).prettyPrint();
break;

case "POST":
respStr = RestAssured.given().log().all().headers(headerParams).body(reqBody).post(url).prettyPrint();
break;

default:
break;
}

return respStr;
}








References:
https://confluence.csiro.au/display/SC/Using+Jenkins'+Remote+Access+API
http://codegists.com/code/jenkins-get-current-build-status


2 comments:

  1. Dont you think using Soap would be be more secure when you deal with kernel level code base rather than using RestAPI

    ReplyDelete
    Replies
    1. When you say Kernel Level, I hope you are referring to machine level.
      AFAIK, When it comes to Machine to Machine communications including higher security still SOAP is preferable.
      But, When it comes to Web / Client-Service communications REST takes the preference.

      Delete