Skip to main content

How to remove labels from Kubernetes Resource

This guide is about how to remove labels from Kubernetes Resource. In some cases, when you're rearchitecting the label naming convention in your Kubernetes, you may come up with this issue where you want to clear up the old labels in bulk, but very few docs have examples of how to do it with CLI or API.

In this guide, I'm using kubectl CLI and python Kubernetes SDK to remove labels from Kubernetes Resource, but you can choose any supported SDK or even directly use API.

For example, you have deployments with the following labels:

"app": "nginx",
"env": "production"

and you want to update all the deployments to have the following new labels:

"": "nginx",
"": "production"

Add New Labels to Kubernetes Resource

For this you can easily use the kubectl patch api add new labels to the resource

kubectl patch deployment -n default -l app=nginx -p '{"metadata":{"labels":{"":"nginx","":"production"}}}'

But this only adds new labels or updates existing ones with the same key in the deployment, not removing the old ones.

Remove Old Labels from Kubernetes Resource

To remove the old labels, you can use the kubectl patch api:

kubectl patch deployment -n default -l -p '{"metadata":{"labels":{"app": None,"env": None}}}'

Using Python Script