简体   繁体   中英

Pass number of deployed pods from deployment/replicaset/stateful to those pods in kubernetes

I need in the pods to know the total number of running pods for a deployment. I know that there is a downwards api for passing information about pods to the pods themselves in kubernetes.

Is it possible to even do this?

As you mentioned, the Downward API provides you with ways to pass pod/container fields to running containers. The number of running containers in a deployment is not a concern of nor a pod/container field, so this method won't work for you.

You can pass the number of running pods in a deployment to another pod by using an arbitrary environment variable via configmaps or mounted volumes.

Without knowing what exactly you're trying to achieve, here's a working example (I'm taking advantage of bash variable expansion, which allows me to assign value on the fly without having to actually create configmaps nor volumes). I'm assuming the pod counter is NOT part of the deployment you want to observe:

cat > podcounter.yaml <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: podcounter
  labels:
    app: podcounter
spec:
  replicas: 1
  selector:
    matchLabels:
      app: podcounter
  template:
    metadata:
      labels:
        app: podcounter
    spec:
      containers:
      - name: podcounter
        image: busybox:1.28
        command: ["sh", "-c", "env"]
        env:
        - name: NUM_PODS
          value: $(kubectl get deploy -o wide | grep YOUR_DEPLOYMENT | awk '{print $3}')
EOF

*$3 returns the count of available pods in that deployment.

** This method populates the environment variable at container-creation time and won't be updated further down the container's lifecycle. You'd need a cronjob for that.

You can get this information via Kubernetes REST API.

GET /apis/apps/v1/namespaces/{namespace}/deployments/{name}

https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.18/#deployment-v1-apps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM