How to remove a node label with kubernetes API

4/29/2019

I'm handling kubernetes node labels in go with kubernetes API. For label add, it works. But for label delete, do not know what is the right way.

This is the demo code that add label works:

key := "testkey"

value := "testvalue"

patch := `{"metadata":{"labels":{"` + key + `":"` + value + `"}}}`

_, err := clientset.CoreV1().Nodes().Patch("10.x.x.x", types.StrategicMergePatchType, []byte(patch))

So what about the delete case? I have tried some answers in Stack Overflow, like:

patch := `{"metadata":{"labels":{"$patch":"delete","testkey":"testvalue"}}}

It will remove all the labels on this node, but not the only "testkey" label.

-- yangyang
kubernetes

1 Answer

6/17/2019

In order to achive your goal you might need to use strategic merge patch.

Try to run something like this:

curl -k -v -XPATCH -H "Accept: application/json, /" -H "Content-Type: application/strategic-merge-patch+json" 10.x.x.x:x/api/v1/namespaces/default/pds/testvalue-xxxxx --data '{"metadata":{"labels":{"$patch": "delete", "testkey":"testvalue"}}}'

To get the exact pod name run:

kubectl get pod --show-labels | grep testvalue

I have used the necessary details you listed in the description but please check them again yourself as I did not reproduce this issue. However it worked fine in the past so I think we are good here.

For more details regarding the strategic merge patch see this documentation

Please, let me know if that helped.

-- OhHiMark
Source: StackOverflow