我想要实现的是从容器内部查看 3 个副本名称。 关注this guide我能够获取当前的 pod 名称,但我还需要副本中的 pod 名称。
理想情况下我想:
print(k8s.get_my_replicaset_names())
或
print(os.getenv("MY_REPLICASET"))
结果如下:
[frontend-b2zdv,frontend-vcmts,frontend-wtsmm]
这是所有容器副本(当然也是当前容器)的 pod 名称,并最终比较名称列表中的当前名称以获取列表中的索引。
有什么办法可以实现这一点吗?
最佳答案
正如您可以阅读的那样 here ,Downward API 用于向正在运行的容器公开 Pod
和 Container
字段:
There are two ways to expose Pod and Container fields to a running Container:
- Environment variables
- Volume Files
Together, these two ways of exposing Pod and Container fields are called the Downward API.
它并不意味着公开有关管理此类 Pod
的其他对象/资源(例如 ReplicaSet
或 Deployment
)的任何信息。
您可以通过执行以下命令来准确查看哪些字段包含描述正在运行的 Pod
的 yaml
list :
kubectl get pods <pod_name> -o yaml
其输出的示例片段可能如下所示:
apiVersion: v1
kind: Pod
metadata:
annotations:
<some annotations here>
...
creationTimestamp: "2020-10-08T22:18:03Z"
generateName: nginx-deployment-7bffc778db-
labels:
app: nginx
pod-template-hash: 7bffc778db
name: nginx-deployment-7bffc778db-8fzrz
namespace: default
ownerReferences: 👈
- apiVersion: apps/v1
blockOwnerDeletion: true
controller: true
kind: ReplicaSet 👈
name: nginx-deployment-7bffc778db 👈
...
如您所见,在 metadata
部分中,它包含 ownerReferences
,在上面的示例中,它包含对 ReplicaSet
对象的一个引用,通过该引用Pod
受到管理。因此,您可以轻松获取这个特定的 ReplicaSet
名称,因为它是 Pod
yaml list 的一部分。
但是,您无法通过这种方式获取有关此 ReplicaSet
管理的其他 Pod
的信息。
此类信息只能从 api 服务器获取,例如通过使用 kubectl 客户端或以编程方式直接调用 API。
关于kubernetes - 如何获取容器内的所有副本集名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64259866/