Search code examples
kubernetesdocker-volumepersistent-volumes

Kubernetes `local` PV and directory creation


When configuring a local PV I noticed there is no option to explicitly create the PV directory on the underlying node if it does not already exist, unlike an hostPath PV which provides the DirectoryOrCreate option (as shown in the doc here), a local PV requires you to first create the directory manually and give it the correct ownership and permissions.

I am trying to use a local PV with a directory as a mounted local storage device with this code:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: jenkins-pv-volume
  namespace: jenkins
spec:
  capacity:
    storage: 4Gi
  volumeMode: Filesystem
  accessModes:
    - ReadWriteOnce
  persistentVolumeReclaimPolicy: Delete
  storageClassName: local-storage
  local:
    path: "/var/jenkins_home"
  nodeAffinity:
    required:
      nodeSelectorTerms:
        - matchExpressions:
            - key: kubernetes.io/hostname
              operator: In
              values:
                - worker-1

However, in order for the PV to be configured correctly, I first need to ssh into the worker-1 node and run the following commands:

sudo mkdir -p /var/jenkins_home
sudo chown -R 1000:1000 /var/jenkins_home
sudo chmod -R 755 /var/jenkins_home

Would it be possible to create the directory and give it the correct ownership and permissions when the PV configuration is applied?


Solution

  • No, you cannot skip this step.

    However you can write script which will work in the background and execute commands which will create directory for local volume and assign rights to it. Remember to give execute permission to your script. For example, create script with proper commands then create ConfigMap which will run created script in also ConfigMap will configure PV.

    See example: configmap-volume, configmap-scripts.