Assigning a unique number in env inside each pod in a kubernetes cluster

Viewed 832

I have a kubernetes cluster inside which there will be some pods running. For each pod I want to assign a unique id as env variable. eg: pod 1 server_id= 1, pod 2 server_id=2 etc. Anyone have any idea how this can be done. I am building my docker image and deploying to cluster through gitlab ci.

1 Answers

Adding ENV variables into helm or YAML template

You can add a variable to the YAML file and apply it as per the requirement if your deployment are different.

Get the variables values into POD and use it

Or else you can get the POD name of deployment that will be different from each other and if you are fine to use that which will be unique

apiVersion: v1
kind: Pod
metadata:
  name: dapi-envars-fieldref
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "sh", "-c"]
      args:
      - while true; do
          echo -en '\n';
          printenv MY_NODE_NAME MY_POD_NAME MY_POD_NAMESPACE;
          printenv MY_POD_IP MY_POD_SERVICE_ACCOUNT;
          sleep 10;
        done;
      env:
        - name: MY_NODE_NAME
          valueFrom:
            fieldRef:
              fieldPath: spec.nodeName
        - name: MY_POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: MY_POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
        - name: MY_POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        - name: MY_POD_SERVICE_ACCOUNT
          valueFrom:
            fieldRef:
              fieldPath: spec.serviceAccountName
  restartPolicy: Never

If you want to set your own variable and values you have to use the different deployment.

if you want to manage the sequence you need to use the stateful sets.

Sequence something like

POD-1
POD-2
POD-3

as environment variables at the, you want just this you can use stateful sets POD name and get value from node and inject back to POD and application use it further.

Related