Answer a question

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

Answers

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.

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐