Read Kubectl last applied config with Python

Johan Louwers
2 min readNov 17, 2021

When working with Kubernetes you most likely will work with kubectl, either in a direct or an indirect fashion. kubectl, allows you to run commands against Kubernetes clusters. You can use kubectl to deploy applications, inspect and manage cluster resources, and view logs.

Last applied config

An interesting datapoint in many cases is, what is the last configuration that has been pushed to the cluster, using kubectl. As you might have many people / scripts interacting with your kubernetes cluster it is highly valuable to be able to find out what the last config was that was pushed into the cluster.

When in need for this information you can leverage the Kubernetes APIs to get the information. The below is a “cleaned” version of an API request to show information on a service. The shown part is a sub part of the full response and falls under “metadata”.”annotations”.”kubectl.kubernetes.io/last-applied-configuration” .

{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"annotations": {},
"labels": {
"k8s-app": "kubernetes-dashboard"
},
"name": "kubernetes-dashboard",
"namespace": "kubernetes-dashboard"
},
"spec": {
"ports": [{
"port": 443,
"targetPort": 8443
}],
"selector": {
"k8s-app": "kubernetes-dashboard"
}
}
}

Based upon the above you can see information of what has been applied to your kubernetes cluster by leveraging the Kubernetes APIs.

Using the Kubernetes Python Client

Even though the above is working and you can pull information by calling the Kubernetes APIs people most likely have a need to do this in a more specific and a more programmatic manner. When coding against the Kubernetes APIs you can leverage the Kubernetes Python client to do this relatively easy.

As an example, the below code will loop through all the namespaces and look for services which have kubectl.kubernetes.io/last-applied-configuration . For those it will print the namespace, service name, port and target port.

--

--

Johan Louwers

Johan Louwers is a technology enthousiasts with a long background in supporting enterprises and startups alike as CTO, Chief Enterprise Architect and developer.