如何获取容器内的所有副本集名称

how to get all replicaset names inside a container

考虑以下 example provided in this doc

我想要实现的是从容器内部查看 3 个副本的名称。 在 this guide 之后,我能够获得当前的 pod 名称,但我还需要我的副本中的 pod 名称。

理想情况下我想:

print(k8s.get_my_replicaset_names())

print(os.getenv("MY_REPLICASET"))

结果如下:

[frontend-b2zdv,frontend-vcmts,frontend-wtsmm]

这是所有容器的副本(当然也是当前容器)的 pod 名称,最终比较名称列表中的当前名称以获取列表中的索引。

有什么办法可以实现吗?

如您所见here向下 API 用于将 PodContainer 字段公开给运行 容器:

There are two ways to expose Pod and Container fields to a running Container:

Together, these two ways of exposing Pod and Container fields are called the Downward API.

这并不意味着公开有关管理此类 Pod 的其他 objects/resources(例如 ReplicaSetDeployment)的任何信息。

您可以通过执行以下命令准确查看哪些字段包含描述 运行 Podyaml 清单:

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 清单的一部分。

但是,您无法通过这种方式获取有关此 ReplicaSet 管理的其他 Pods 的信息。

此类信息只能从 api 服务器 获取,例如通过使用 kubectl 客户端或以编程方式直接调用API.