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

做~自己de王妃 提交于 2020-12-13 07:12:34

问题


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

回答1:


I was able to get the cluster name for the configmap used for clusterConfiguration. This config map exists if the cluster is a kubeadm one.

https://github.com/dguyhasnoname/k8s-cluster-checker/blob/master/objects/cluster.py#L17

below snippet fetches configmap from python client using module get-cm.py(in modules folder of above repo). It checks if clusetConfiguration configmap kubeadm-config is present and if found, greps out the cluster name. You can put configMap of your cluster in below snippet and try running the script.

    def get_cluster_name():
        cm = K8sConfigMap.get_cm('kube-system')
        for item in cm.items:
            if 'kubeadm-config' in item.metadata.name:
                if 'clusterName' in item.data['ClusterConfiguration']:
                    cluster_name = re.search(r"clusterName: ([\s\S]+)controlPlaneEndpoint", \
                    item.data['ClusterConfiguration']).group(1)
                    print ( "\nCluster name: {}".format(cluster_name))

the grepping of cluster name is happening in below line:

re.search(r"clusterName: ([\s\S]+)controlPlaneEndpoint",

cluster name value is found between clusterName: and controlPlaneEndpoint strings. You can change these strings if needed, according to your env.




回答2:


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


来源:https://stackoverflow.com/questions/59483772/how-can-i-use-kubernetes-python-api-to-get-clusters-information

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!