Using kubectl patch to modify existing Kubernetes objects

2 min read

To be able to modify a Kubernetes object we can use kubectl edit to do it interactively. It can come handy if we need to test values but it makes it harder to automate it. If we need a way to change a Kubernetes object using a non-interactive command, kubectl patch is the best option for us.

To be able to modify a Kubernetes object in batch mode we need to tell kubectl which fields we want to set. For example, if we want to add a top-level entry such as allowVolumeExpansion to be able to resize EBS-backed PVCs:

$ kubectl get sc gp2 -o yaml
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  (...)
  name: gp2
parameters:
  fsType: ext4
  type: gp2
provisioner: kubernetes.io/aws-ebs
reclaimPolicy: Delete
volumeBindingMode: WaitForFirstConsumer

It's the most trivial case, we just need to define the object that will be merged into the existing one using the -p option:

$ kubectl patch sc gp2 -p '{"allowVolumeExpansion": true}'
storageclass.storage.k8s.io/gp2 patched

If we need to modify a value that has more levels, we will have to include all of them to the patch. For example, for the following definition to se a different spec.resources.requests.storage value:

$ kubectl get pvc demopvc -o yaml
(...)
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
(...)

We will have to define the entire path to reach the value we want to change:

$ kubectl patch pvc demopvc -p '{"spec": {"resources": {"requests": {"storage": "20Gi"}}}}'
persistentvolumeclaim/demopvc patched

Checking again the object with kubectl get pvc we will be able to see how it has been successfully patched:

$ kubectl get pvc demopvc -o yaml
(...)
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 20Gi
(...)

Posted on 18/08/2021

Categories