Search code examples
kuberneteskubernetes-statefulset

How to read an arg from a volume in a kubernetes deployment?


I want to create a statefulset that runs an image that creates devices. I want each pod to create unique devices, so the first will do 1-20, and second 21-40 etc. The image takes in a flag that indicates what index to start at. I am struggling to implement this so that the flag is unique for each pod in the statefulset.

I tried to use an init container that creates a file on a volume, and puts the pod number on that file. this worked as expected. I can access this file from the main container as well. How do i pass the value in this file as an arg for my container? I have tried to directly access it in the args section as well as create an environment variable but neither work. Ideally something like this would work but does not:

env:
  - name: index 
    value: "cat ./pod/pod.toml"
args: ["--start-index","$(index)"]

Solution

  • You can expose the pod name as an environment variable via the downward api:

    env:
      - name: PODNAME
        valueFrom:
          fieldRef:
            fieldPath: metadata.name
    

    You can use this variable to calculate the index in a shell script, and then launch your service with the appropriate argument:

    command:
    - sh
    - -c
    - |
      podnumber=$(echo $PODNAME | cut -f2 -d-)
      startindex=$(( podnumber * 20 + 1 ))
      exec myserver --start-index $index
    

    Pod 0 will run with --start-index 1, pod 1 will run with --start-index 21, etc.

    Note that this does require overriding the ENTRYPOINT in your image (by setting command in the manifest) because you need to perform the calculations in a shell script. Whether this is easy or complex depends on the image that you're using and whether or not it has an extensive existing ENTRYPOINT script.