我在这里假设您已经将一个 Pod 部署到集群中,现在您正在尝试查询它正在运行的节点。
这实际上是两个不同的问题:
也就是说,Pod 如何识别它正在运行的具体 Kubernetes 节点
有两种方法可以做到这一点,但都涉及到向下的API https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/。您可以将 pod 名称下推或将节点名称下推(或两者)。您需要首先执行此操作才能启用所需的查找。因此,运行 kubernetes python 客户端的 pod 需要像这样部署:
apiVersion: v1
kind: Pod
metadata:
name: example-app
spec:
containers:
- name: python-kubernetes-client
image: my-image
command: [ "start_my_app" ]
env:
- name: MY_NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: MY_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
restartPolicy: Never
好的,现在您已经有了正在运行的 pod 可用的 pod 信息和节点信息。
然后仅查询该节点上 pod 的完整列表
现在您知道了 pod 正在运行的节点名称,使用 python API 查询在其上运行的 pod 相对简单:
#!/usr/bin/env python
from kubernetes import client, config
import os
def main():
# it works only if this script is run by K8s as a POD
config.load_incluster_config()
# use this outside pods
# config.load_kube_config()
# grab the node name from the pod environment vars
node_name = os.environ.get('MY_NODE_NAME', None)
v1 = client.CoreV1Api()
print("Listing pods with their IPs on node: ", node_name)
# field selectors are a string, you need to parse the fields from the pods here
field_selector = 'spec.nodeName='+node_name
ret = v1.list_pod_for_all_namespaces(watch=False, field_selector=field_selector)
for i in ret.items:
print("%s\t%s\t%s" %
(i.status.pod_ip, i.metadata.namespace, i.metadata.name))
if __name__ == '__main__':
main()