on 08-Jul-2019 01:31
In this article, we continue our exploration of Kubernetes API but this time we're going to use Python along with Wireshark.
I strongly advise you to go through Exploring Kubernetes API using Wireshark part 1: Creating, Listing and Deleting Pods and Exploring Kubernetes API using Wireshark part 2: Namespaces first.
We're not creating any app here. I'll just show you how you can explore Kubernetes API using Python's client API and Wireshark output retrieved from kubectl get pods command:
In case you want to follow along, I've set up gcloud tool as I'm using Google Cloud and GOOGLE_APPLICATION_CREDENTIALS environment variable on my Mac so I had no problem authenticating to Kubernetes API.
I hope you understand that when I say Kubernetes API, I'm talking about the API on Kubernetes Master node on my Google Cloud's Kubernetes cluster.
In this article, we're going to do the following (using Python):
Here we're loading auth and cluster info from kube-config file and storing into into our client API config:
We now store into v1 variable the API object. For the sake of simplicity, think of it as we were pointing to /api/v1/ folder and we haven't decided where to go yet:
We now move to /api/v1/namespaces/default/pods which where we find information about pods that belong to default namespace (watch=False just means we will not be monitoring for changes, we're just retrieving it as one-off thing):
Now, what we've stored in the above variable (ret) is the equivalent of moving to the root directory in our JSON tree (Object) in the output below:
The output above was from kubectl get pods command which lists all pods from default namespace and that's equivalent to what we're doing here using Python's Kubernetes Client API.
Python shows us similar options about where to go when I type ret. and hit tab:
We've got kind, apiVersion, metadata and items as options to move to but items is what we're looking for because it's supposed to store pod's information.
So let's move to items and store it in another variable called pods to make it easier to remember that it actually holds all pods' information from default namespace:
We're now in a comfortable place and ready to play!
Let's keep pods variable as our placeholder!
On Wireshark, pod's name is located in metadata.name:
\
So let's create another variable called pods_names to store all pods' names:
What we're looking for is in status.phase:
Let's store it in status variable in Python:
We can now display the output using built-in zip() method:
If you want something pretty you can use prettytable: