[Part I] Rancher 2 — Java API Client — Hello World

Gonçalo Lourenço
2 min readNov 27, 2018

--

Photo by frank mckenna on Unsplash

Kubernetes came to save the day when you have lots of micro services to deploy and maintain. It is a bit complex to manage at the beginning but when you get all the concepts, nothing will stop you. If you are still deciding which solution to use, keep in mind that Rancher discarded their own solution in order to adopt Kubernetes.

I’ve recently had the need to have a Kubernetes workload controlled by an internal system, Java based. Since I’m using Rancher 2, I’ve decided to use Rancher’s API v3 instead of using Kubernetes API directly. Although I might explore this last API in the future, but for now I didn’t want to worry about reinventing the wheel and Rancher did a great job with their API.

This part will show how to get your script ready to invoke the API. Starting by creating a token from Rancher in order to be authorized, and perform a simple API call.

I haven’t found any useful Rancher API Documentation, the one they provide didn’t seem very helpful to me, so I had to dig and explore a bit by myself.

If you already have Rancher 2, you can access to the Rancher’s API like this:

https://<yourhost>/v3

Before we start coding the first thing to do, in order to make my script authorized to call this API, is to generate a token directly from Rancher.

Step 1 at Rancher

Step 1: Click on the Avatar > API & Keys

Step 2: Click on the “Add Key”

Step 3: Choose a name, and create.

Step 4: Copy the Bearer Token, that’s what we’re going to use for the HTTP Authentication.

Jumping into Java, we need a way to perform HTTPS requests and retrieved the JSON response. In the image bellow the readJsonFromUrl function makes HTTPS requests and returns a JSONObject. It also adds the Authorization header with the value “Bearer <the token you copied from Rancher>“.

We are now ready to start calling Rancher’s API, with the code bellow, and check the response by printing it:

In the second part, I’ll show how to get the Projects and its Workloads from the Rancher API v3: [Part II] Rancher 2 — Java API Client — Get Kubernetes Workloads

--

--