MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

Kubectl: Persistent Volumes PV & PersistentVolumeClaim PVC

To turn an existing PersistentVolumeClaim (PVC) into a YAML manifest you can deploy again, run kubectl get pvc <name> -o yaml and remove the fields the cluster generates: status, uid, resourceVersion, creationTimestamp, binding annotations and, in some cases, spec.volumeName. The commands above are a starting point, but the grep version produces invalid YAML. This page explains why, gives corrected commands using yq, jq and kubectl-neat, and covers how PVs and PVCs bind so the restored claim actually reaches the Bound state.


PV and PVC in brief

A PersistentVolume (PV) is a piece of storage in the cluster. An administrator creates it by hand, or a StorageClass provisioner creates it on demand. A PersistentVolumeClaim (PVC) is a namespaced request for storage that a Pod mounts. The control plane binds each PVC to exactly one PV, and that binding is recorded on both objects. This matters when you export and re-create a PVC.

FieldObjectWhat it means for export
spec.volumeNamePVCName of the PV the claim is bound to. Keep it to rebind the same PV. Remove it to get a new volume.
spec.claimRefPVPoints to the PVC by name, namespace and uid. A re-created PVC has a new uid, so a stale claimRef blocks binding.
spec.storageClassNamePVC and PVMust exist in the target cluster, or dynamic provisioning fails.
persistentVolumeReclaimPolicyPVDelete removes the storage when the PVC is deleted. Retain keeps it.
statusBothRuntime state written by the cluster. Never include it in a manifest.

Why the grep one-liner produces broken YAML

grep -v deletes single lines. It does not understand YAML structure. It removes the status: line but leaves the indented lines under it. Here is typical raw output for a dynamically provisioned claim:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  annotations:
    pv.kubernetes.io/bind-completed: "yes"
    pv.kubernetes.io/bound-by-controller: "yes"
    volume.kubernetes.io/storage-provisioner: ebs.csi.aws.com
  creationTimestamp: "2023-05-10T08:12:44Z"
  finalizers:
  - kubernetes.io/pvc-protection
  name: grafana-pod
  namespace: management
  resourceVersion: "184233"
  uid: 7c1e2f4a-0d6b-4c55-9a51-3f0e1b2c9d10
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  storageClassName: gp3
  volumeMode: Filesystem
  volumeName: pvc-7c1e2f4a-0d6b-4c55-9a51-3f0e1b2c9d10
status:
  accessModes:
  - ReadWriteOnce
  capacity:
    storage: 10Gi
  phase: BoundCode language: JavaScript (javascript)

Once the status: line is gone, accessModes, capacity and phase move up into spec. That gives a duplicate accessModes key and unknown fields spec.capacity and spec.phase. Current kubectl validates strictly by default, so kubectl apply rejects the file with a duplicate-key or unknown-field error. Older clients might accept it and silently drop fields. The grep version also leaves the binding annotations and volumeName in place, so the claim can sit in Pending even when the file is accepted.

Note: selfLink is no longer populated by current Kubernetes versions, and kubectl hides managedFields by default. Deleting them is harmless, but they are not the real problem. The old kubectl get --export flag was removed in Kubernetes 1.18, which is why these cleanup pipelines exist.

Corrected export commands

Option 1: yq (mikefarah yq v4). It deletes whole YAML nodes, children included. In v4 the eval subcommand is the default, so yq '...' and yq eval '...' - do the same thing. The Python yq package uses jq syntax and will not run this expression.

kubectl get pvc grafana-pod -n management -o yaml | yq 'del(
    .status,
    .metadata.creationTimestamp,
    .metadata.resourceVersion,
    .metadata.uid,
    .metadata.selfLink,
    .metadata.managedFields,
    .metadata.annotations["pv.kubernetes.io/bind-completed"],
    .metadata.annotations["pv.kubernetes.io/bound-by-controller"],
    .metadata.annotations["volume.kubernetes.io/storage-provisioner"],
    .metadata.annotations["volume.beta.kubernetes.io/storage-provisioner"],
    .metadata.annotations["kubectl.kubernetes.io/last-applied-configuration"]
  )' > deployable-pvc.yamlCode language: JavaScript (javascript)

Option 2: jq. Use it when yq is not installed. kubectl apply accepts JSON files as well as YAML.

kubectl get pvc grafana-pod -n management -o json | jq 'del(
    .status,
    .metadata.creationTimestamp,
    .metadata.resourceVersion,
    .metadata.uid,
    .metadata.managedFields,
    .metadata.annotations["pv.kubernetes.io/bind-completed"],
    .metadata.annotations["pv.kubernetes.io/bound-by-controller"],
    .metadata.annotations["kubectl.kubernetes.io/last-applied-configuration"]
  )' > deployable-pvc.jsonCode language: JavaScript (javascript)

Option 3: the kubectl-neat plugin. It removes common cluster-generated fields for you. Install it with krew, then check the output by eye before you apply it.

kubectl krew install neat
kubectl get pvc grafana-pod -n management -o yaml | kubectl neat > deployable-pvc.yamlCode language: JavaScript (javascript)

To export every PVC in a namespace at once, run the same delete expression against the List object. Here is the yq version:

kubectl get pvc -n management -o yaml | yq 'del(
    .items[].status,
    .items[].metadata.creationTimestamp,
    .items[].metadata.resourceVersion,
    .items[].metadata.uid,
    .items[].metadata.annotations["pv.kubernetes.io/bind-completed"],
    .items[].metadata.annotations["pv.kubernetes.io/bound-by-controller"]
  )' > all-pvcs.yamlCode language: JavaScript (javascript)

Same cluster or a new cluster: decide on volumeName

A clean manifest still needs one decision: should the claim attach to the existing volume or get a new one?

  • New cluster or fresh, empty volume: delete spec.volumeName too, for example by adding .spec.volumeName to the del(...) list. The StorageClass then provisions a new PV. Make sure the storageClassName exists in the target cluster (kubectl get storageclass).
  • Same cluster, keep the data: keep spec.volumeName. The PV must use the Retain reclaim policy, and its stale claimRef must be cleared (see the next section). If the reclaim policy was Delete, the storage was removed when the old PVC was deleted.
  • Moving data between clusters: exporting the manifest does not copy any data. Use a backup tool or CSI volume snapshots, or point a static PV at the same cloud disk.

Here is a cleaned manifest for the same-cluster case:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: grafana-pod
  namespace: management
  finalizers:
  - kubernetes.io/pvc-protection
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
  storageClassName: gp3
  volumeMode: Filesystem
  volumeName: pvc-7c1e2f4a-0d6b-4c55-9a51-3f0e1b2c9d10

Note: Keeping the kubernetes.io/pvc-protection finalizer is fine, because the cluster adds it anyway. Do not strip finalizers from live objects to force a deletion. That can orphan storage that is still in use.

Rebinding a retained PV

After you delete a PVC, a PV with the Retain policy moves to Released. It stays reserved for the old claim's uid and will not bind to the re-created PVC. Protect the PV first, then clear the reference:

# Before deleting the PVC, make sure the PV will survive
kubectl patch pv pvc-7c1e2f4a-0d6b-4c55-9a51-3f0e1b2c9d10 \
  -p '{"spec":{"persistentVolumeReclaimPolicy":"Retain"}}'

# After the PVC is deleted, the PV shows STATUS Released
kubectl get pv pvc-7c1e2f4a-0d6b-4c55-9a51-3f0e1b2c9d10

# Remove the stale claimRef so the PV becomes Available
kubectl patch pv pvc-7c1e2f4a-0d6b-4c55-9a51-3f0e1b2c9d10 \
  --type json -p '[{"op":"remove","path":"/spec/claimRef"}]'

# Re-create the claim
kubectl apply -f deployable-pvc.yamlCode language: PHP (php)

If you also want a manifest for the PV itself, export it the same way and remove status, metadata.uid, metadata.resourceVersion, metadata.creationTimestamp and spec.claimRef. If you want to pre-bind it to the new claim, keep only name and namespace under claimRef.

Validate and apply

  1. Check the file locally: kubectl apply --dry-run=client -f deployable-pvc.yaml.
  2. Validate against the API server, including strict field checks: kubectl apply --dry-run=server -f deployable-pvc.yaml. Expected output: persistentvolumeclaim/grafana-pod created (server dry run).
  3. Apply it: kubectl apply -f deployable-pvc.yaml.
  4. Watch the binding: kubectl get pvc grafana-pod -n management -w. STATUS should change to Bound. With a WaitForFirstConsumer StorageClass, it stays Pending until a Pod uses the claim. That is expected.
  5. If the claim stays Pending, run kubectl describe pvc grafana-pod -n management and read the Events section.

Common errors and fixes

SymptomCauseFix
unknown field "spec.capacity" or a duplicate accessModes keyThe grep one-liner left status children in the fileUse yq, jq or kubectl-neat to delete the whole status node
the object has been modified or a resourceVersion conflictmetadata.resourceVersion was left in the fileDelete resourceVersion and uid
spec is immutable after creation except resources.requests...You applied changed spec fields to a PVC that already existsDelete and re-create the PVC. Only storage size can grow in place, and only if the StorageClass sets allowVolumeExpansion: true
PVC stuck in Pending with volumeName setThe PV is Released with a stale claimRef, or it does not exist in this clusterClear the PV's claimRef, or remove volumeName to provision a new volume
storageclass.storage.k8s.io "gp3" not foundThe target cluster uses different StorageClass namesChange storageClassName to one listed by kubectl get sc

Everyday PV and PVC commands

kubectl get pv                                   # cluster-wide volumes, status, claim, reclaim policy
kubectl get pvc -A                               # claims in all namespaces
kubectl describe pvc grafana-pod -n management   # events, bound volume, mounted-by pods
kubectl get storageclass                         # provisioners, default class, expansion support
kubectl get pvc grafana-pod -n management \
  -o jsonpath='{.spec.volumeName}{"\n"}'          # which PV backs this claim
kubectl patch pvc grafana-pod -n management \
  -p '{"spec":{"resources":{"requests":{"storage":"20Gi"}}}}'   # expand, if allowedCode language: PHP (php)

For workloads that use these claims, and for other kubectl walkthroughs, see the Kubernetes tutorials.

Frequently asked questions

How do I export a Kubernetes PVC to YAML?

Run kubectl get pvc <name> -n <namespace> -o yaml, then remove status, uid, resourceVersion, creationTimestamp and the binding annotations with yq, jq or the kubectl-neat plugin. Plain grep -v is unsafe because it leaves the nested lines of status behind.

Why does kubectl get –export not work anymore?

The --export flag was deprecated and then removed in Kubernetes 1.18. Use -o yaml together with a cleanup tool such as yq or kubectl-neat.

Why is my re-created PVC stuck in Pending?

The usual causes are a spec.volumeName pointing to a PV that is Released with a stale claimRef, a PV that does not exist in the cluster, a missing StorageClass, or a WaitForFirstConsumer StorageClass that is waiting for a Pod. kubectl describe pvc shows which one applies.

Does exporting a PVC manifest back up the data?

No. The manifest only describes the storage request. To protect the data, use a backup tool or CSI volume snapshots, and set the PV reclaim policy to Retain before you delete the claim.

Can I edit a PVC after it is created?

Most of the PVC spec cannot be changed after creation. The main exception is increasing resources.requests.storage when the StorageClass allows volume expansion. For any other change, re-create the claim.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Kubernetes storageclassย using OpenEBS Local PV HostPath โ€” Complete Step-by-Step Kubernetes Tutorial

Dynamic storage provisioner: openebs.io/localLab platform: Self-managed Kubernetes v1.35.10 on Ubuntu Linux (kubeadm or other manual installation)OpenEBS release referenced: OpenEBS 4.6.2 (HostPath engine v4.6.0), current as checked on November 12, 2026Lab…

Read More

Kubernetes PersistentVolume, PersistentVolumeClaim, volume using hostPath

pv.yaml $ kubectl create -f pv.yaml $ kubectl get pv pvc.yaml $ kubectl create -f pvc.yaml $ kubectl get pvc pod.yaml Rajesh Kumar I’m Rajesh Kumar, a…

Read More

Kubrnetes: Example of StorageClass

Choose a storage class and set it as your default by setting the storageclass.kubernetes.io/is-default-class=true annotation. Scheduling based on Node label selector The ‘Allowed Topologies’ feature allows you select the…

Read More

Kubernetes PersistentVolume and PersistentVolumeClaim using NFS volume types

Save the definition to a file, for example nfs-pv.yaml, and create the PV: $ kubectl create -f nfs-pv.yaml persistentvolume “pv0001” created $ get pv $ kubectl create…

Read More

Troubleshooting Knative Guide

This page collects kubectl commands for troubleshooting Knative Serving: finding an OOMKilled activator, checking the net-istio-controller, load testing a Knative Service (ksvc), inspecting the autoscaler and its…

Read More

How to install Knative Servingย 1.7.4ย Manually?

To install Knative Serving 1.7.4 manually, you apply the Serving CRDs, then the core components, then a networking layer such as Istio or Kourier. Each step is…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x