如何使用官方 Python Kubernetes 客户端获取与我自己的(特权)pod 在同一 Kubernetes 节点上运行的 pod 列表?也就是说,Pod 如何识别它正在运行的具体 Kubernetes 节点,然后仅查询该节点上的完整 Pod 列表?
我在这里假设您已将 pod 部署到集群,现在您正在尝试查询它正在运行的节点。
这实际上是两个截然不同的问题:
也就是说,Pod 如何识别它正在运行的具体 Kubernetes 节点
有两种方法可以做到这一点,但它们都涉及向下的 API。您可以向下推送 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
Run Code Online (Sandbox Code Playgroud)
好的,现在您拥有可用于运行的 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()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3299 次 |
最近记录: |