我正在寻找关于如何使用Kubernetes Python API来获取集群信息(kubectl get clusters)的答案。
~$ kubectl -n <namespace> get clusters
NAME AGE
cluster-1 6d17h
cluster-2 6d17h发布于 2020-07-30 17:20:16
我能够获得用于clusterConfiguration的配置映射的集群名称。如果集群是kubeadm集群,则存在此配置映射。
https://github.com/dguyhasnoname/k8s-cluster-checker/blob/master/objects/cluster.py#L17
下面的代码片段使用模块get-cm.py(在上面repo的modules文件夹中)从python客户端获取configmap。它检查是否存在clusetConfiguration配置映射kubeadm-config,如果找到,则显示群集名称。您可以将集群的configMap放在下面的代码片段中,然后尝试运行脚本。
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))群集名称的line发生在以下行中:
re.search(r"clusterName: ([\s\S]+)controlPlaneEndpoint",集群名称值位于clusterName:和controlPlaneEndpoint字符串之间。如果需要,您可以根据您的环境更改这些字符串。
发布于 2021-07-14 19:48:54
这个也许能帮到你,at
from pick import pick # install pick using `pip install pick`
from kubernetes import client, config
from kubernetes.client import configuration
def main():
contexts, active_context = config.list_kube_config_contexts()
if not contexts:
print("Cannot find any context in kube-config file.")
return
contexts = [context['name'] for context in contexts]
active_index = contexts.index(active_context['name'])
cluster1, first_index = pick(contexts, title="Pick the first context",
default_index=active_index)
cluster2, _ = pick(contexts, title="Pick the second context",
default_index=first_index)
client1 = client.CoreV1Api(
api_client=config.new_client_from_config(context=cluster1))
client2 = client.CoreV1Api(
api_client=config.new_client_from_config(context=cluster2))
print("\nList of pods on %s:" % cluster1)
for i in client1.list_pod_for_all_namespaces().items:
print("%s\t%s\t%s" %
(i.status.pod_ip, i.metadata.namespace, i.metadata.name))
print("\n\nList of pods on %s:" % cluster2)
for i in client2.list_pod_for_all_namespaces().items:
print("%s\t%s\t%s" %
(i.status.pod_ip, i.metadata.namespace, i.metadata.name))发布于 2019-12-31 14:05:16
下面是获取集群信息(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" % ehttps://stackoverflow.com/questions/59483772
复制相似问题