Skip to content

CSI volume snapshots in Kubernetes — VolumeSnapshotClass, policy, and restore to a fresh PVC

Configure VolumeSnapshotClass on a CSI driver, automate a daily snapshot policy, and restore an application to a fresh PVC without losing the original.

The data team asks you for a copy of the production Postgres PVC for an analytics rebuild. You take a pg_dump on the live primary, the dump takes ninety minutes during business hours, the dump finishes in a state that’s hours behind reality, and the analytics team is now consuming both the wall-clock time and the IOPS budget. CSI volume snapshots are the right answer to that request — copy-on-write, near-instant, restorable to a fresh PVC that can be mounted by a different pod for analysis, restored to a different namespace, or kept as a recovery point. If you don’t have them configured the answer is always “we’ll dump it again,” and the cost of that gap compounds.

What’s happening

A CSI volume snapshot is a point-in-time copy of a PVC managed by the CSI driver. The Kubernetes objects involved: VolumeSnapshotClass (cluster-scoped, declares which CSI driver and parameters to use), VolumeSnapshot (namespaced, the user’s request to snapshot a PVC), VolumeSnapshotContent (cluster-scoped, the actual snapshot resource the driver created). The plumbing requires the snapshot-controller deployment and the external-snapshotter CRDs — these are installed once per cluster, separately from any CSI driver.

The reclaim policy on a VolumeSnapshotClass mirrors PVCs: Delete removes the underlying snapshot when the VolumeSnapshot is deleted, Retain keeps the snapshot on the storage backend forever. For automated daily snapshots you want Delete; for manual “I want a checkpoint before this risky migration” snapshots you want Retain.

Restoring is the inverse of provisioning: a new PVC declares spec.dataSource pointing at the VolumeSnapshot, and the CSI driver clones the snapshot into a fresh volume. The original PVC is untouched. The new PVC must be the same size or larger, and must use a StorageClass on the same CSI driver as the original — you cannot snapshot from Longhorn and restore into EBS.

How to verify

Check that the snapshot-controller and CRDs are installed:

kubectl get crd | grep snapshot.storage.k8s.io
# volumesnapshotclasses.snapshot.storage.k8s.io
# volumesnapshotcontents.snapshot.storage.k8s.io
# volumesnapshots.snapshot.storage.k8s.io

kubectl get deploy -n kube-system snapshot-controller 2>/dev/null \
  || kubectl get deploy -A | grep snapshot-controller

If the CRDs are missing, no snapshots will work — install the external-snapshotter v8 manifests first:

SNAP_VER="v8.2.0"
kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/${SNAP_VER}/client/config/crd/snapshot.storage.k8s.io_volumesnapshotclasses.yaml
kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/${SNAP_VER}/client/config/crd/snapshot.storage.k8s.io_volumesnapshotcontents.yaml
kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/${SNAP_VER}/client/config/crd/snapshot.storage.k8s.io_volumesnapshots.yaml
kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/${SNAP_VER}/deploy/kubernetes/snapshot-controller/rbac-snapshot-controller.yaml
kubectl apply -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/${SNAP_VER}/deploy/kubernetes/snapshot-controller/setup-snapshot-controller.yaml

List VolumeSnapshotClasses already on the cluster:

kubectl get volumesnapshotclass

If empty, the CSI driver is installed but no snapshot class has been declared. Create one for your driver (Longhorn shown):

cat <<'EOF' | kubectl apply -f -
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshotClass
metadata:
  name: longhorn-snapshot
  annotations:
    snapshot.storage.kubernetes.io/is-default-class: "true"
driver: driver.longhorn.io
deletionPolicy: Delete
parameters:
  type: snap
EOF

Take an ad-hoc snapshot of an existing PVC and watch it complete:

PVC=postgres-data-postgres-0
NS=production
cat <<EOF | kubectl apply -f -
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
  name: ${PVC}-manual-$(date +%Y%m%d-%H%M)
  namespace: ${NS}
spec:
  volumeSnapshotClassName: longhorn-snapshot
  source:
    persistentVolumeClaimName: ${PVC}
EOF

kubectl get volumesnapshot -n ${NS} -w
# NAME                              READYTOUSE   SOURCEPVC               RESTORESIZE
# postgres-data-postgres-0-manual   false        postgres-data-postgres-0
# ...
# postgres-data-postgres-0-manual   true         postgres-data-postgres-0   200Gi

READYTOUSE: true means the snapshot is available for restore.

The fix

A snapshot policy is three components: the VolumeSnapshotClass (one per CSI driver), a CronJob that creates daily snapshots and prunes old ones, and a documented restore procedure that operators have practiced. The manifests below cover all three.

1. VolumeSnapshotClasses

---
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshotClass
metadata:
  name: longhorn-snapshot-delete
  annotations:
    snapshot.storage.kubernetes.io/is-default-class: "true"
    stackharbor.com/policy: "automated-daily"
driver: driver.longhorn.io
deletionPolicy: Delete
parameters:
  type: snap
---
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshotClass
metadata:
  name: longhorn-snapshot-retain
  annotations:
    stackharbor.com/policy: "manual-checkpoint"
driver: driver.longhorn.io
deletionPolicy: Retain
parameters:
  type: snap

2. Automated snapshot CronJob

Save as snapshot-cronjob.yaml. The CronJob runs once a day, takes a snapshot of every PVC matching a label selector, and prunes snapshots older than the retention window.

---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: snapshotter
  namespace: production
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: snapshotter
  namespace: production
rules:
  - apiGroups: [""]
    resources: ["persistentvolumeclaims"]
    verbs: ["get", "list"]
  - apiGroups: ["snapshot.storage.k8s.io"]
    resources: ["volumesnapshots"]
    verbs: ["get", "list", "create", "delete"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: snapshotter
  namespace: production
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: snapshotter
subjects:
  - kind: ServiceAccount
    name: snapshotter
    namespace: production
---
apiVersion: batch/v1
kind: CronJob
metadata:
  name: pvc-snapshot-daily
  namespace: production
spec:
  schedule: "15 2 * * *"            # 02:15 UTC every day
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 7
  failedJobsHistoryLimit: 14
  jobTemplate:
    spec:
      backoffLimit: 2
      template:
        spec:
          serviceAccountName: snapshotter
          restartPolicy: OnFailure
          containers:
            - name: snapshotter
              image: bitnami/kubectl:1.30
              env:
                - name: RETENTION_DAYS
                  value: "14"
                - name: LABEL_SELECTOR
                  value: "snapshot=daily"
                - name: SNAP_CLASS
                  value: "longhorn-snapshot-delete"
              command:
                - /bin/bash
                - -c
                - |
                  set -euo pipefail
                  TS=$(date -u +%Y%m%d-%H%M)
                  NS=production
                  echo "Snapshotting PVCs with ${LABEL_SELECTOR} at ${TS}"
                  for pvc in $(kubectl get pvc -n "${NS}" -l "${LABEL_SELECTOR}" \
                               -o jsonpath='{.items[*].metadata.name}'); do
                    cat <<EOF | kubectl apply -f -
                  apiVersion: snapshot.storage.k8s.io/v1
                  kind: VolumeSnapshot
                  metadata:
                    name: ${pvc}-auto-${TS}
                    namespace: ${NS}
                    labels:
                      pvc: ${pvc}
                      policy: daily
                  spec:
                    volumeSnapshotClassName: ${SNAP_CLASS}
                    source:
                      persistentVolumeClaimName: ${pvc}
                  EOF
                  done

                  echo "Pruning daily snapshots older than ${RETENTION_DAYS} days"
                  CUTOFF=$(date -u -d "${RETENTION_DAYS} days ago" +%s)
                  for snap in $(kubectl get volumesnapshot -n "${NS}" -l policy=daily \
                                -o jsonpath='{.items[*].metadata.name}'); do
                    CREATED=$(kubectl get volumesnapshot -n "${NS}" "${snap}" \
                              -o jsonpath='{.metadata.creationTimestamp}')
                    CREATED_TS=$(date -u -d "${CREATED}" +%s)
                    if [ "${CREATED_TS}" -lt "${CUTOFF}" ]; then
                      echo "Deleting ${snap}"
                      kubectl delete volumesnapshot -n "${NS}" "${snap}"
                    fi
                  done

Label the PVCs you want included in the daily policy:

kubectl label pvc -n production postgres-data-postgres-0 snapshot=daily
kubectl label pvc -n production redis-data-redis-0 snapshot=daily

3. Restore to a fresh PVC

The runbook: identify the snapshot, create a new PVC referencing it as dataSource, mount the new PVC into a pod, verify data, then promote (or discard).

# 1. Find the snapshot you want
kubectl get volumesnapshot -n production | grep postgres-data-postgres-0
# postgres-data-postgres-0-auto-20260513-0215   true   200Gi
SNAP=postgres-data-postgres-0-auto-20260513-0215

# 2. Create the restored PVC (must be >= original size, same StorageClass)
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: postgres-restored
  namespace: production
spec:
  storageClassName: gold-nvme-replicated
  dataSource:
    name: ${SNAP}
    kind: VolumeSnapshot
    apiGroup: snapshot.storage.k8s.io
  accessModes: [ReadWriteOnce]
  resources:
    requests:
      storage: 200Gi
EOF

# 3. Wait for the new PVC to bind
kubectl get pvc -n production postgres-restored -w

# 4. Mount it into a verification pod
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: restore-verify
  namespace: production
spec:
  restartPolicy: Never
  containers:
    - name: psql
      image: postgres:16
      command: ["sleep", "3600"]
      env:
        - name: PGDATA
          value: /var/lib/postgresql/data
      volumeMounts:
        - mountPath: /var/lib/postgresql/data
          name: data
  volumes:
    - name: data
      persistentVolumeClaim:
        claimName: postgres-restored
EOF

# 5. Verify the snapshot timestamp matches expectations
kubectl exec -n production restore-verify -- \
  bash -c 'ls -la /var/lib/postgresql/data/global/pg_control && \
           stat /var/lib/postgresql/data/global/pg_control'

If the verify pod can read the data and the timestamps match the snapshot, the restore is valid. Promote by pointing the application’s StatefulSet at the new PVC (or swap names via a brief downtime window). Discard by deleting restore-verify and postgres-restored — the snapshot is preserved.

Operational rules: (1) every stateful workload has at least one VolumeSnapshot per day and at least one Retain checkpoint per month; (2) the snapshot CronJob alerts on failure — silent skipping of a day is the failure mode that bites; (3) once a quarter, restore from a snapshot into a verification namespace and prove the application starts. A snapshot you have never restored is not a backup, it is a hypothesis with extra steps.

Stack Harbor configures, monitors, and drills CSI snapshot policy under Managed Cloud Ops, including off-cluster backup of snapshots to object storage as a second layer. If your cluster has CSI snapshots disabled or untested, request a snapshot policy review.