Kubernetes how create folders for Physical Volumes (PVs) automatically

Adding commands before an entrypoint.

Kubernetes how create folders for Physical Volumes (PVs) automatically
Page content

Introduction

This will be a quick short blog entry. Today I needed to have a container that could self-initialize it’s own Physical Volumes. This is quite easy to do with an init container. I’m going to provide a simple example to show how this works with busybox.

Deployment YAML

  initContainers:
  - name: init-pv
    image: {{ .Values.initpv.image }}
    volumeMounts:
      - name: init
        mountPath: {{ .Values.persistentVolume.path }}
  {{- with .Values.initpv.command }}
    command:
     {{- toYaml . | nindent 8 }}
  {{- end }}
  volumes:
    - name: init
      persistentVolumeClaim:
        claimName: {{ .Values.serviceName }}-init

This is what the yaml looks like in the deployment. Essentially you are declaring a physical volume at the root of all your other physical volumes. Then while the init container is running, the init container can create the necessary folders and set any necessary permissions before the main container starts.

Bash for init container ( values.yaml )

initpv:
  image: docker.io/busybox:latest
  command:
   - sh
   - "-c"
   - |
     check_pv () {
             path=$1
             uid=$2
             gid=$3
             subpath=$4

             # Check if Directory Exists
             if [ -d "${path}" ]
             then
                 echo "Directory ${path} exists"
             else
                 echo "Creating Directory ${path}"
                 mkdir -p ${path}/${subpath}
             fi

             echo Permissions detected: `stat -c '%u:%g' ${path}`
             echo Permissions wanted: ${uid}:${gid}

             # Check if Ownership is correct
             if [ "${uid}:${gid}" = "`stat -c '%u:%g' ${path}`" ]; then
                 echo "Permissions are correct"
             else
                 echo "Changing Permissions"
                 chown -R "${uid}:${gid}" ${path}
                fi

      }
      check_pv "/opt/app/namespace/container" "1000" "1000" "subpath"     

In this example I pass the directory i need created, the permissions, and if I need a subpath folder created. Obviously this can be done with anything available on the image you are using as the init container. Bash is simple and everyone understands it so its great pseudo code if you want to write something sophicated.