如何通过Kubernetes Python Client获取自建Service的ClusterIP
用Kubernetes Python Client获取Service ClusterIP的方法
当然有完全对应的实现方式,ClusterIP存储在Service对象的spec.cluster_ip属性中,你可以根据需求选择精准查询单个服务,或者遍历所有服务获取ClusterIP。
方法1:精准查询指定服务的ClusterIP(推荐)
如果你明确知道目标Service的名称和所在命名空间,直接调用read_namespaced_service方法即可,不需要遍历所有服务,效率更高:
from kubernetes import client, config # 加载K8s配置,本地测试用kubeconfig,集群内运行可替换为load_incluster_config() config.load_kube_config() core_v1_api = client.CoreV1Api() # 填写你创建时对应的服务名和命名空间 service_name = "service-example" namespace = "default" # 获取服务对象并提取ClusterIP svc = core_v1_api.read_namespaced_service(name=service_name, namespace=namespace) cluster_ip = svc.spec.cluster_ip print(f"Service {service_name} 的ClusterIP为: {cluster_ip}")
方法2:遍历所有命名空间的所有Service获取ClusterIP(和官方Pod示例逻辑一致)
和你给出的列Pod IP的示例逻辑完全对应,换成Service相关的API即可:
from kubernetes import client, config config.load_kube_config() v1 = client.CoreV1Api() print("Listing services with their ClusterIPs:") ret = v1.list_service_for_all_namespaces(watch=False) for i in ret.items: print("%s\t%s\t%s" % (i.spec.cluster_ip, i.metadata.namespace, i.metadata.name))
注意事项
- 如果你创建的是Headless Service(创建时指定spec.cluster_ip为None),该字段返回值会为空
- 如果你在集群内部运行这段代码,把
config.load_kube_config()替换为config.load_incluster_config()即可正常完成鉴权
内容的提问来源于stack exchange,提问作者Renato S Dias
相关产品推荐
相关产品推荐

