I need to get resource usage of Pods in a Kubernetes Cluster with kubernetes python client

8/7/2020

i have linux command to get the resource usage of the pods in particular namespace what is the equivalent python command for it

$ kubectl top pod
NAME                                CPU(cores)   MEMORY(bytes)   
nginx-deployment-7fd6966748-57mt5   0m           2Mi             
nginx-deployment-7fd6966748-jpbjl   0m           2Mi             
nginx-deployment-7fd6966748-snrx4   0m           2Mi
-- Pradeep Padmanaban C
kubernetes
kubernetes-python-client
python
python-3.x

3 Answers

8/7/2020

There is no single command.

Kubernetes metrics are exposed on metrics.k8s.io. You will have to write program to query the API and get results.

For example for nodes.

This API is made available under the /apis/metrics.k8s.io/ endpoint

kubectl get --raw "/apis/metrics.k8s.io/v1beta1/nodes" | jq for node metrics

-- Rohit
Source: StackOverflow

9/18/2020

Thanks for the input the following command worked fine

>>> from kubernetes import client, config
>>> 
>>> config.load_kube_config()
>>> api = client.CustomObjectsApi()
>>> resource = api.list_namespaced_custom_object(group="metrics.k8s.io",version="v1beta1", namespace="default", plural="pods")
>>> for pod in resource["items"]:
...    print(pod['containers'], "\n")
...
-- Pradeep Padmanaban C
Source: StackOverflow

2/18/2021

You can run kubectl commands with python as well.

from subprocess import call
call('kubectl describe pod pod_name_here -n default', shell=True)

So you can filter anything with the Python Kubernetes library and also use kubectl commands to ease your work.

-- Lucas Pires
Source: StackOverflow