如何使用 Kubernetes Python API 获取集群信息? [英] How can I use Kubernetes Python API to get clusters information?

查看:59
本文介绍了如何使用 Kubernetes Python API 获取集群信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关如何使用 Kubernetes Python API 获取集群信息的答案(kubectl get clusters).

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

推荐答案

我能够获得用于 clusterConfiguration 的配置映射的集群名称.如果集群是 kubeadm 集群,则此配置映射存在.

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

下面的代码段使用模块 get-cm.py(在上面 repo 的模块文件夹中)从 python 客户端获取配置映射.它检查 clusetConfiguration configmap kubeadm-config 是否存在,如果找到,则 grep 出集群名称.您可以将集群的 configMap 放在下面的代码段中并尝试运行脚本.

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))

集群名称的 grepping 发生在下面一行:

the grepping of cluster name is happening in below line:

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

集群名称值位于 clusterName:controlPlaneEndpoint 字符串之间.如果需要,您可以根据您的环境更改这些字符串.

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

这篇关于如何使用 Kubernetes Python API 获取集群信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆