Remove label from node using patch

6/2/2020

I'd like to remove a label from node using strategic merge patch. Here is what I used to remove label:

kubectl patch node xxx --type='strategic' -p '{"metadata":{"labels":{"$patch": "delete", "node-role.kubernetes.io/master":""}}}'
xxx patched

It succeeded but there are two issues here:

  1. It removed all labels but not only the label I specified.
  2. When I tried to patch it again on same node, it reported error:
kubectl patch node xxx --type='strategic' -p '{"metadata":{"labels":{"$patch": "delete", "node-role.kubernetes.io/master":""}}}'
The Node "xxx" is invalid: metadata.labels: Invalid value: "$patch": name part must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyName',  or 'my.name',  or '123-abc', regex used for validation is '([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9]')

How should I only remove one label I specified? The patch with delete operation is not idempotent? I don't quite understand the error it reported when I tried to delete the label again.

-- JoyceLee
kubernetes

1 Answer

6/2/2020

Check the REST API that kubectl internally calls to remove a label from a node

kubectl label nodes kind-control-plane abc- -v=10

I0602 09:21:04.717687   37243 request.go:1068] Request Body: {"metadata":{"labels":{"abc":null}}}
I0602 09:21:04.717784   37243 round_trippers.go:423] curl -k -v -XPATCH  -H "User-Agent: kubectl/v1.18.0 (darwin/amd64) kubernetes/9e99141" -H "Accept: application/json" -H "Content-Type: application/merge-patch+json" 'https://127.0.0.1:32768/api/v1/nodes/kind-control-plane'

Then call the same API from client library

-- Arghya Sadhu
Source: StackOverflow