Use Pod name or uid in Volume mountPath

8/3/2020

I have an NFS physical volume that my pods can all access via a PVC, files are kept after pods are destroyed.

I want each pod to be able to put its files under a unique subdirectory.

Is there anyway that I can dynamically utilize say metadata.uid or metadata.name in the mountPath for the container? i.e. conceptually this:

volumeMounts:

  - name: persistent-nfs-storage
    mountPath: /metadata.name/files

I think I can see how to handle first making the directory, by using an init container and putting the value into the environment using the downward API. But I don't see any way to utilize it in a PVC mountPath.

Thanks for any help.

-- thisisnotatest
kubernetes

1 Answer

8/3/2020

I don't know if it is possible to use Pod Name in Volume mountPath. But, if the intention is writing files in a separate folder(using pod name) of the same PVC, there are workarounds.

One way to achieve it is by getting the file path and pod name from env and then append them. After that write the log on that directory.

In details,

volumeMounts:
- name: persistent-nfs-storage
  mountPath: /nfs/directory

ENVs:

env:
- name: WRITE_PATH
  value: "$(NFS_DIR)/$(POD_NAME)"
- name: NFS_DIR
  value: /nfs/directory
- name: POD_NAME
  valueFrom:
    fieldRef:
      fieldPath: metadata.name

In Application, use $WRITE_PATH directory to write your necessary files. Also, if necessary create this directory from init container.

-- Abdullah Al Maruf - Tuhin
Source: StackOverflow