TEAM IM Insights

Kubernetes Developer Tools - Displaying Application Version

Written by Mat Thomas | Jul 3, 2024 1:00:00 PM

Use the Kubernetes API to pull back pod data.

Kubernets API - Pod Data

For cloud admins, it's fairly straightforward to run "kubectl describe pods" to pull back all pod data but for regular developers, needing to provide access and kubectl training is not necessarily desired.  Additionally this requires manually running a command and parsing through the data.  In my previous post, I outlined how to associate a pod with a service account to call the Kubernetes API.  We'll be updating that account to grant permissions to access pod data.  This assumes all steps in said post have been followed.

Configuring the service account to access pod data

Granting the service account permissions to pod data is fairly straightforward.  Simply update and rerun the Role yaml file as follows, note, the only change is adding "pods" in the rules.resources array:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: dev-tools-reader
rules:
- apiGroups: [""] # "" indicates the core API group
  resources: ["pods"]
  verbs: ["get", "watch", "list"]

Validating access to the API

Similar to validating basic connections, the following commands can be run from inside the pod to validate access to the pods resource:

SERVICEACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount
TOKEN=$(cat ${SERVICEACCOUNT}/token)
CACERT=${SERVICEACCOUNT}/ca.crt
curl --cacert ${CACERT} --header "Authorization: Bearer ${TOKEN}" -X GET https://kubernetes.default.svc/api/v1/namespaces/default/pods

This should return a large JSON response with information about each pod in the default namespace.

Parsing out the data

At this point we could simply return the massive JSON response to developers and have them sort though it but that defeats the purpose of quickly displaying application version as outlined in my original post.  Kubernetes has a fairly extensive list of client libraries, we'll be using java for this example.  Our code snippet for parsing out version from tags looks something like:
        try {
            ApiClient client = Config.defaultClient();
            Configuration.setDefaultApiClient(client);

            CoreV1Api api = new CoreV1Api();
            V1PodList list = api.listNamespacedPod("default", null, null, null, null, null, null, null, null, null, null);
            for (V1Pod item : list.getItems()) {            
              console.log("name", item.getMetadata().getName());
                console.log(item.getMetadata().getLabels().get("version"));
            }
        } catch (IOException | ApiException e) {
            // TODO Auto-generated catch block
            System.out.println(e.getMessage());
            e.printStackTrace();
        }

Displaying the data is left as an exercise for the reader.