How can I use Kubernetes Python API to get clusters information?

12/26/2019

I'm seeking the answer regarding how to use the Kubernetes Python API to get cluster information (kubectl get clusters).

~$ kubectl -n <namespace> get clusters
NAME         AGE
cluster-1   6d17h
cluster-2   6d17h
-- Sudhakar Donkena
api
kubernetes
python

1 Answer

12/31/2019

Below is the code to get the cluster info (CRD):

clusters_info = []
d1  = {}
config.load_kube_config()
#config.load_incluster_config()
configuration = client.Configuration()
api_instance = client.AppsV1beta2Api(client.ApiClient(configuration))
try:
   api_response = api_instance.list_namespaced_stateful_set(namespace)
   for cluster in api_response.items:
       d1['name']=cluster.metadata.labels['operator.io/cluster']
       clusters_info.append(d1.copy())
   return clusters_info
except ApiException as e:
   return "Exception when calling AppsV1beta2Api->patch_namespaced_stateful_set_status: %s\n" % e
-- Sudhakar Donkena
Source: StackOverflow