如何从它的 IP 获取另一个 pod 名称?

How to get another pod name from it's IP?

我有一个公开端口(服务器)的 pod。其他 pods(客户端)可以与之通信。

服务器可以在套接字上找到远程 IP 和端口(当客户端连接到它时)。我正在寻找一种方法来获取客户端的 pod 名称(从其 IP 和端口)。

我看到了一堆 questions/answers 关于通过 kubectl 获取 pod 名称的文章。但是,我不确定我是否可以在集群内部执行 kubectl。

我正在尝试找出集群上 运行 的可用内容。如果它需要一些特殊权限也没关系。如果需要认证就更复杂了。

任何可以通过 kubectl 完成的事情也可以通过直接请求到 API 服务器来完成。您所需要的只是为您的 pod 设置适当的 ServiceAccount。一旦你拥有它——你可以使用大量专用于与 k8s API 服务器通信的库。

从这个 JSON object 中列出所有带有 List Pods API operation and parse the JSON response for the podIP field (e.g. with jq or some other JSON parsing tool) to find the JSON object of the Pod that has your desired IP address. Then, extract the metadata.name 字段的 Pods 以获取 Pod 的名称。

您可以通过直接使用您从中发出请求的 Pod 使用的 Kubernetes API (e.g. with curl) or with kubectl (e.g. kubectl get pods -o json | jq ...). In any case, you must include in this request the ServiceAccount token of the ServiceAccount 来执行此操作(如果您直接使用 Kubernetes API,作为 Authorization header,如果你使用带有 --token command-line 标志的 kubectl)。

关于 Pod 的 authorisation, you need a Role allowing the list verb on the pods resource and a RoleBinding that binds this Role to the ServiceAccount that your Pod is using (by default, Pods use a ServiceAccount named default in their namespace, but you can specify a custom ServiceAccount with the serviceAccountName 字段。