[英]Can a pod within my cluster get a list of pods in a service?
Suppose I have a Service
within my cluster called workers
.假设我的集群中有一个名为workers
的Service
。 From kubectl
, I can list the pods in that service using the selector the service uses:从kubectl
,我可以使用服务使用的选择器列出该服务中的 pod:
kubectl get pods --selector app=worker
Can a pod within the cluster get a list of that service's pods?集群中的 pod 能否获取该服务的 pod 列表?
You can achieve it quite easily with Kubernetes Python Client library .您可以使用Kubernetes Python Client library轻松实现它。 The following code can be run locally as it uses your .kube/config
file for authentication:以下代码可以在本地运行,因为它使用您的.kube/config
文件进行身份验证:
from kubernetes import client , config
config.load_kube_config()
v1 = client.CoreV1Api()
list_pods = v1.list_pod_for_all_namespaces(label_selector="app=worker")
for item in list_pods.items:
print(item.metadata.name)
Before that you will need to install the mentioned library, which can be done with pip
:在此之前,您需要安装上述库,可以使用pip
完成:
pip3 install kubernetes
For production use I would recommend integrating it with your python docker image and of course instead of using .kube/config
file, you will need to create a ServiceAccount
for your client Pod
so it can authenticate to kubernetes API . For production use I would recommend integrating it with your python docker image and of course instead of using .kube/config
file, you will need to create a ServiceAccount
for your client Pod
so it can authenticate to kubernetes API . This is nicely described in this answer , provided by krelst .这在krelst提供的这个答案中得到了很好的描述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.