Dynamic Disk provisioning with Kubernetes

Posted on May 12, 2022
Note: This article was written a while ago and may contain outdated information. Please verify the details before relying on it. If I express opinions or recommendations, they might not reflect my current views. For this reason, I recommend checking for more recent articles on the same topic.

Kubernetes can automatically provision PersistentVolume for you and make them available for your PersistentVolumes. This can be helpful if you are for example in a cloud provider like Azure.

You need the interaction between the StorageClass, PersistentVolumeClaim and Pod resources to make it work.

Diagram of the interaction between StorageClass, PersistentVolumeClaim and Pod

The StorageClass resource

For this you need to create a StorageClass resource which describes the classes of storages you offer.

You can list your available StorageClass resources via the following command:

kubectl get sc

The StorageClass resource looks like the following:

apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: managed-premium-retain
provisioner: disk.csi.azure.com
parameters:
  skuName: Premium_LRS
reclaimPolicy: Retain
volumeBindingMode: WaitForFirstConsumer
allowVolumeExpansion: true

Significant fields are name and provisioner. The name field will be referenced later in your PersistentVolumeClaim and trigger the provisioning.

The provisioner field describes the provisioner which is responsible for the provisioning of the PersistentVolume.

Things to know about the StorageClasses:

The PersistentVolumeClaim resource

Within the PersistentVolumeClaim you reference the name of the StorageClass:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: azure-managed-disk
spec:
  accessModes:
  - ReadWriteOnce
  storageClassName: managed-premium-retain
  resources:
    requests:
      storage: 5Gi

With this a PersistentVolume is provisioned and bound to the PersistentVolumeClaim. They are mapped 1:1 to claims.

The Pod resource

In the Pod resource the persistentVolumeClaim is referenced throguh it’s name:

kind: Pod
apiVersion: v1
metadata:
  name: nginx
spec:
  containers:
    - name: myfrontend
      image: mcr.microsoft.com/oss/nginx/nginx:1.15.5-alpine
      volumeMounts:
      - mountPath: "/mnt/azure"
        name: volume
  volumes:
    - name: volume
      persistentVolumeClaim:
        claimName: azure-managed-disk

The claim can be referenced through the volumeMounts field in the Pod.

Further reading

Want to know more?

Keep on reading and choose one of the related articles. You can also check the home page for my latest thoughts, notes and articles.