Back to Terraform

Persistent Storage: PVCs, StorageClasses and Stateful Recovery

November 6, 2026 Wasil Zafar 20 min read

Distinguish Kubernetes objects, provisioned cloud volumes and recoverable application data

Table of Contents

  1. Trace PVC Binding to the Actual Volume
  2. Choose Access, Capacity and Reclaim Behavior Deliberately
  3. A StatefulSet Is Not a Backup Strategy
  4. Plan Replacement and Namespace Deletion Around Retained Data
  5. Restore a Tiny Dataset and Inspect Remaining Volumes

Trace PVC Binding to the Actual Volume

A claim is a request; a volume is a record of something that exists. The StorageClass is a cluster-scoped template that names a CSI provisioner and its parameters. The PersistentVolumeClaim is a namespaced request for size, access mode and class. The PersistentVolume is the cluster-scoped object that represents the actual disk. A pod never mounts a disk directly; it mounts a claim by name.

Ownership splits across three layers. Terraform writes the class and the claim through kubernetes_storage_class_v1 and kubernetes_persistent_volume_claim_v1. The CSI provisioner, running in the cluster, calls the cloud API and creates the PV. The kubelet attaches and mounts the result on whichever node runs the pod.

A dynamically provisioned PV never enters Terraform state. A clean plan therefore proves the claim object exists, not that a disk was provisioned or that its bytes are reachable. Inventory has to come from the cluster and from the cloud account, because neither view is complete alone.

Class selection happens at admission, not at mount time. When the claim omits the field, the default class annotation supplies one, and with no default the claim waits with no class at all. An empty string is an explicit opt-out that forces static binding to a PV you created yourself. A named class that does not exist leaves the claim Pending indefinitely.

Dynamic provisioning starts when binding is allowed. Immediate provisions as soon as the claim exists, which can place a zonal disk in a zone the pod never reaches. WaitForFirstConsumer waits for the scheduler to choose a node, so the disk lands in that node's zone. A Pending claim with no consumer is the expected state in that mode.

Terraform waits for Bound by default. wait_until_bound is true on the claim resource, so a first-consumer class with no pod turns a correct configuration into a create timeout. Disable the wait when the claim deliberately precedes its consumer, then verify binding as a separate step.

Topology is a hard constraint on zonal storage. A disk created in one zone cannot be attached by a pod in another, and the pod stays Pending with a volume node affinity conflict. Cluster autoscaling can look broken when the real problem is that no node in the disk's zone has capacity.

The provisioner is a cloud identity, not a Kubernetes permission. It needs rights to create, attach and delete disks in the account, usually through workload identity or an instance role. A claim that never binds reports the reason in a provisioner event about permissions, quota or an unsupported parameter, so read that event before editing the PVC.

Two failures look identical in Terraform. A rejected parameter is a provisioning error in the cluster, while a missing default class is an admission problem. Neither changes the next plan, because both live in status that the provider does not own.

Figure 1 follows the chain and marks the four points where it stops.

Trace PVC Binding to the Actual Volume
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    P["Pod mounts a claim by name"] --> PVC["PersistentVolumeClaim
size, mode, class"] PVC --> AD{"storageClassName set?"} AD -->|"omitted"| DEF["Default class annotation
fills the field"] AD -->|"empty string"| STATIC["Static binding only
match an existing PV"] AD -->|"named"| SC["StorageClass
provisioner and parameters"] DEF --> SC STATIC --> BIND SC --> MODE{"volumeBindingMode"} MODE -->|"Immediate"| PROV["CSI provisioner
creates the cloud disk"] MODE -->|"WaitForFirstConsumer"| SCHED["Scheduler picks a node
then provision in its zone"] SCHED --> PROV PROV --> PV["PersistentVolume
cluster-scoped record"] PV --> BIND["Claim phase Bound"] BIND --> MOUNT["Kubelet attaches and mounts
on one node"] PROV -.->|"no permission or quota"| E1["Claim Pending
provisioner event"] SCHED -.->|"zone not allowed"| E2["Claim Pending
no topology match"] MOUNT -.->|"disk in another zone"| E3["Pod Pending
node affinity conflict"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class P,PVC,AD primary; class DEF,STATIC,SC,MODE,PROV,SCHED,PV secondary; class BIND,MOUNT ok; class E1,E3 danger; class E2 warn;

The chain has three owners and no single witness. Terraform owns the request, the provisioner owns the disk, and the kubelet owns the mount. Figure 2 maps those owners as zones, and each of them can report success while the next link is still broken.

A claim crosses three owners before a pod sees a filesystem Terraform creates a StorageClass and a PersistentVolumeClaim. Admission fills in the default class, and the binding mode decides whether a consumer must exist before provisioning. The CSI provisioner creates a cloud disk in one zone and a cluster-scoped PersistentVolume. The kubelet attaches and mounts that disk on one node. A pod in another zone cannot attach it, and a dynamically provisioned PersistentVolume never appears in Terraform state. Request, provision, attach: three owners in one chain Terraform writes StorageClass provisioner and parameters PersistentVolumeClaim size, mode, class name Default class filled at admission No PV appears here. A clean plan is not a disk. Control plane and provisioner Binding mode Immediate or first consumer CSI provisioner creates the cloud volume PersistentVolume cluster-scoped record Pending means no PV yet. Read provisioner events. Cloud and node Disk in one zone size and class parameters Attach to one node RWO stops at the node Mount at pod start filesystem inside container Another zone cannot attach. Read the pod event next. WaitForFirstConsumer: the claim stays Pending until a pod is scheduled. That wait is the mechanism that puts the disk in the right zone. A pod scheduled in another zone cannot attach this disk. The PV and the cloud volume survive; the pod does not start.

Choose Access, Capacity and Reclaim Behavior Deliberately

Access mode describes a capability, not a lock manager. ReadWriteOnce means one node may mount the volume read-write, so two pods on that node can share it. ReadWriteMany needs a shared filesystem driver behind the claim, and asking a block driver for it leaves the claim Pending. ReadWriteOncePod narrows the guarantee to a single pod and depends on CSI support.

Size is a floor, not a promise of usable bytes. The provisioner may round the request up to its minimum volume size, and filesystem overhead consumes part of the result. Set the number from measured growth plus a margin, and write down why that number was chosen.

Expansion needs both a class permission and a driver capability. Setting allow_volume_expansion to true lets a claim grow, but the driver must also support growing that volume. Kubernetes does not support shrinking, so every increase is a one-way ratchet that a later plan cannot undo.

A resize happens in two stages. The cloud volume grows first, then the filesystem is expanded. Some drivers finish online, while others report a pending filesystem resize and need the pod restarted before the container sees the extra space. A claim larger than the filesystem inside the pod is a normal intermediate state.

Reclaim policy belongs to the PV, copied from the class at creation. Editing the StorageClass later does not rewrite PVs that already exist, which is why changing class behavior is a migration rather than a settings edit. Treat the class as immutable in practice and introduce a new one with a new name.

Delete is the default that surprises people. With Delete, removing the claim removes the PV and the cloud disk. With Retain, the PV moves to Released: the disk and its bytes survive, but the PV is no longer Available and will not bind to a new claim on its own.

Released is not the same as recovered. A replacement claim stays Pending because the old PV still references the previous claim's UID. Recovery means clearing that reference or creating a new PV that points at the same cloud volume, then verifying the data before an application mounts it.

Capacity and retention are one decision. A database on Delete without a snapshot has a recovery time equal to its restore pipeline, while a Retain volume without an inventory becomes a monthly bill with no owner.

Figure 3 follows the choices and the failure branch each one creates.

Choose Access, Capacity and Reclaim Behavior Deliberately
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
    A["Claim spec"] --> B{"Which access mode?"}
    B -->|"ReadWriteOnce"| C["One node at a time
block driver fits"] B -->|"ReadWriteMany"| D{"Shared filesystem driver?"} D -->|"no"| X1["Claim stays Pending
mode unsupported"] D -->|"yes"| E["NFS, Azure Files or EFS"] C --> F{"Need more capacity?"} E --> F F -->|"yes"| G{"allowVolumeExpansion true?"} G -->|"no"| X2["Update rejected
replace the claim"] G -->|"yes"| H["Request grows
filesystem resize may need restart"] F -->|"no"| I{"Reclaim policy on the PV"} H --> I I -->|"Delete"| J["Claim delete removes
PV and cloud disk"] I -->|"Retain"| K["PV becomes Released
disk and bytes remain"] K --> L{"claimRef cleared?"} L -->|"no"| X3["New claim Pending
old volume unreachable"] L -->|"yes"| M["Bound again
after checksum verification"] classDef primary fill:#132440,color:#ffffff,stroke:#0b172b; classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a; classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f; classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420; classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f; class A,B,D,F,G,I,L primary; class C,E,H,K secondary; class M ok; class J,X1,X3 danger; class X2 warn;

Pick the mode from the workload, then confirm the driver. Three replicas that each need their own disk are three ReadWriteOnce claims, not one shared claim. A shared upload directory is the case that actually justifies ReadWriteMany, and it also justifies the operational cost of a network filesystem.

A StatefulSet Is Not a Backup Strategy

A StatefulSet gives each member a name, a DNS record and a claim. Terraform's kubernetes_stateful_set_v1 declares a volume_claim_template that works as a PVC factory: each ordinal gets a separate claim, created before its pod starts. Rescheduling that pod reattaches the same claim, which is the identity guarantee.

Identity is continuity, not durability. Each claim's name is the template name, the set name and the ordinal joined by hyphens, so the pod and its storage are addressed together. The same bytes come back after a restart, including a corrupted file, a dropped table or an encrypted volume. A backup answers a different question: what would you restore if this claim disappeared?

The retention policy decides what scaling leaves behind. By default, both when_scaled and when_deleted retain claims, so scaling up again reattaches the old data. That is usually right for a quorum member and wrong for a worker that must start empty. Set both fields deliberately instead of inheriting them.

A successful snapshot is not automatically application-consistent. A CSI snapshot captures a crash-consistent disk image. A database needs its writes flushed and its logs quiesced first, or the restore has to replay and repair before it is trusted.

Snapshot objects are operational, not declarative infrastructure. The snapshot class is a cluster template Terraform can own. Individual snapshots belong to a schedule with a retention window and an owner, and keeping every one of them in state turns Terraform into a backup catalog.

Data movement is a job, not a resource attribute. Seeding or migrating a dataset belongs to a one-shot Job or the database's own tooling, run with its own evidence and idempotency key. A Terraform resource that uploads rows makes every plan depend on content, and every apply a potential duplicate writer.

Restore is a separate, rehearsed path. Create a new claim from the snapshot, fix ownership through the pod's security context, start the application against it, and verify a known query. Restoring over the live claim is not a drill, and it destroys the evidence you would need if the restore fails.

Ownership has to be a name, not a team. The data owner sets recovery point, recovery time and what counts as a valid restore. The platform team owns the class, the CSI driver and the snapshot controller. A runbook with no name beside each step is a hope rather than a control.

Plan Replacement and Namespace Deletion Around Retained Data

Terraform destroys in dependency order, not in business order. The workload goes first, then the claim if Terraform manages it, then the namespace. That order is technically correct and still wrong for the data if nobody decided what happens to the disk.

Claims from a volume claim template are not in state. Destroying the StatefulSet removes the pods and, with the default policy, leaves the claims behind. Destroying the namespace then removes those claims as part of namespace cleanup. The same command therefore has two very different data outcomes depending on which object it targets.

Namespace deletion is a cascading delete. Every namespaced object goes, including PVCs, Secrets and Services. The PVs survive because they are cluster-scoped, and their reclaim policy decides whether the cloud disk follows.

Replacement is the quiet data-loss path. Changing a claim's class, access modes or volume name forces a new claim. Renaming a StatefulSet or a claim template creates claims with new names. The old PV becomes Released and the new pod mounts an empty disk unless someone restores first.

Protect the objects you cannot recreate. A prevent_destroy lifecycle on the claim or PV turns an accidental destroy into a plan error. It does not protect against namespace deletion, because the namespace owns the claim, so the namespace needs the same treatment.

A managed PV adds a delete path to understand. Adopting an existing disk as a PV resource is useful for recovery, and risky because a destroy removes the PV object while the disk's fate still follows the reclaim policy.

Teardown has a sequence and an owner for each step. Stop writers, take and verify a final backup, scale the workload to zero, delete the claim deliberately, confirm the PV state, then remove the namespace. Every step should name the expected observation, not just the command.

Replacement is not a rollback. A new pod with an old image still mounts whatever the claim contains now. Rolling back the workload does not roll back the data, which is why the restore decision belongs before the release rather than after it.

Figure 4 contrasts the two teardown outcomes with the replacement path.

Namespace deletion and claim replacement lead to different data outcomes The left panel shows a namespace destroy deleting pods, services and claims, after which the PV reclaim policy either deletes the cloud disk or leaves the PV Released with the disk orphaned. The right panel shows a changed class or template name creating a new claim with a new UID, which mounts an empty disk while the old PV sits Released. A restore into the new claim is the only step that carries the old bytes forward. Two commands, two very different fates for the bytes Namespace teardown Terraform destroys the namespace every namespaced object goes Pods deleted traffic stops PVC deleted PV leaves Bound PV reclaim policy decides the disk Delete PV and cloud disk are removed Retain PV Released and disk bills quietly The PV is cluster-scoped, so it outlives the namespace. Claim replacement Class or template name changes the old claim cannot follow New claim, new UID bound to newly provisioned storage Empty disk mounts the workload starts without its history Old PV stays Released with Retain, only in inventory The object name survives. The data does not. A restore into the new claim is the only step that carries the old bytes forward. Snapshot, restore, verify, then let the application start.

An inventory after teardown is the only proof. List PVs and cloud disks from outside the cluster; every survivor needs an owner, a reason and a deletion date. A disk nobody can name is a disk nobody will delete.

Restore a Tiny Dataset and Inspect Remaining Volumes

A binding test needs one claim, one consumer and a recorded observation. Read the claim phase, the PV name and the node's zone. A Bound claim proves the chain worked once; it does not prove the mount is writable.

Expansion is proven by the filesystem, not by the request. The claim capacity is the API's view, while the container sees the mounted filesystem. Comparing the two is what separates a completed resize from a pending one.

Recovery is proven by a checksum after a Released volume is reclaimed. That is the step most teams skip, and it is the only one that shows the bytes, not just the object, came back.

Lab

Restore a Tiny Dataset and Inspect Remaining Volumes

Execution status: design-only. These steps were not run against a live cluster. Use a disposable namespace, a disposable storage class and a dataset you can afford to lose.

Prerequisites. Terraform 1.17.1 with hashicorp/kubernetes 3.5.0, a cluster whose CSI driver supports snapshots, and permission to create classes, claims, pods and snapshots. Confirm the snapshot CRDs are installed before step 2, because a missing controller turns that step into a different exercise.

  1. Apply a StorageClass with Retain, expansion enabled and Immediate binding, then a claim of 1Gi and a pod that mounts it. Record the claim phase, the PV name and the node's zone.
  2. Write a small file and a checksum inside the mount, read both back through a second exec, then create a VolumeSnapshot and wait until it reports ready to use. This is the baseline the later steps compare against.
  3. Raise the claim request by 1Gi in configuration and apply. Read the claim conditions until the resize finishes, and restart the pod only if the driver reports a pending filesystem resize.
  4. Read the filesystem size and the checksum again. A larger request with an unchanged filesystem means the second resize stage has not completed.
  5. Scale the workload to zero, delete the claim, then read the PV phase. Expect Released, and confirm from the cloud console that the disk still exists.
  6. Recreate a claim with the same name and size. Expect Pending, because the PV still references the previous claim's UID. Clear that reference, confirm Bound, then verify the checksum before starting the workload.
  7. Restore the snapshot into a new claim with a different name in the same namespace, correct ownership through the pod's security context, and compare the checksum with step 2.
  8. Destroy the namespace with Terraform and list PVs and cloud disks from outside the cluster. Expect the claims to be gone and the retained disks to remain until you delete them.
ObservationSourceWhat it provesWhat it cannot prove
Claim BoundPVC statusa PV exists and matched the requestthat the mount is writable
Filesystem sizeinside the podthe resize reached the containerthat the application can use the space
PV Released with disk presentcluster and cloud inventoryRetain kept the bytes after claim deletionthat a new claim can bind them
Matching checksum after restoreapplication readthe dataset survived the round tripthat the backup is application-consistent

Expected observation. The claim binds under the lab's Immediate class, expansion ends with a larger filesystem inside the pod, and the retained volume is Released and unreachable until its claim reference is cleared. The restored dataset matches the baseline checksum, and the namespace destroy leaves the disks visible in cluster and cloud inventory but not in the namespace.

Failure checks. Pending with no provisioner event usually means a missing class or a first-consumer class with no pod. Bound but unmountable points at a zone mismatch, an attach limit or filesystem permissions. A Released PV that will not rebind has a claim reference that still names the old UID.

Cost and cleanup. Disks bill hourly while they exist, snapshots bill by stored size, and retained volumes survive the cluster. Delete the restored claim, remove the retained disks in the cloud, then destroy the namespace and confirm both inventories are empty.

References (checked 6 November 2026): persistent volumes, StatefulSets, volume snapshots, and the provider's claim and storage class references.

Next in the Series

In Kubernetes Manifest Resources: CRDs, Server-Side Apply and Field Ownership, we'll explore Use generic manifests while respecting schema discovery and competing field managers.