kubernetescube

How to dynamically set an environment variable in Kubernetes StatefulSet based on pod name and port?


I am working on deploying a StatefulSet in Kubernetes for Cube.js Cube Store workers.

I need to set the CUBESTORE_SERVER_NAME environment variable dynamically based on the pod name and a specific port number.

Below is my current StatefulSet configuration:

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: cubestore-worker
spec:
  serviceName: cubestore-worker
  replicas: 3
  selector:
    matchLabels:
      app: cubestore-worker
  template:
    metadata:
      labels:
        app: cubestore-worker
    spec:
      dnsPolicy: ClusterFirst
      containers:
      - name: cubestore
        image: cubejs/cubestore:latest
        ports:
        - containerPort: 9001
        env:
        - name: POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: CUBESTORE_SERVER_NAME
          value: ${POD_NAME}:9001
        envFrom:
        - configMapRef:
            name: cubestore-worker-configmap
        volumeMounts:
        - name: cubestore-storage
          mountPath: /cube/data
      volumes:
      - name: cubestore-storage
        persistentVolumeClaim:
          claimName: cubestore-pvc-shared

I am trying to set CUBESTORE_SERVER_NAME to be a combination of the pod name and port, like cubestore-worker-0:9001. However, my current approach does not seem to work, and the variable is not being set correctly.

How can I correctly set the CUBESTORE_SERVER_NAME environment variable to include both the pod name and the port dynamically within the StatefulSet?


Solution

  • It is called the "Dependent Environment Variable", and you need to use the previous environment variable with () instead of {}.

    you can see all the options available in the official docs: https://kubernetes.io/docs/tasks/inject-data-application/define-interdependent-environment-variables/