Syntax - Why do kubernetes labels get removed with a "-"?

3/16/2021

I am wondering if anybody knows the logical reasoning behind the syntax to remove a label in Kubernetes?

If I have a Pod named nginx labeled env=testing, I know that I can remove the label like so:

kubectl label pod nginx env-

But why do we need to use a -, not have some other command or a --remove flag to do so?

-- Sam Griffith
kubernetes
label

1 Answer

3/16/2021

I think it is a design decision.

You can check the implementation here:

https://github.com/kubernetes/kubectl/blob/master/pkg/cmd/label/label.go#L418

    func parseLabels(spec []string) (map[string]string, []string, error) {
    	labels := map[string]string{}
    	var remove []string
    	for _, labelSpec := range spec {
    		if strings.Contains(labelSpec, "=") {
    			parts := strings.Split(labelSpec, "=")
    			if len(parts) != 2 {
    				return nil, nil, fmt.Errorf("invalid label spec: %v", labelSpec)
    			}
    			if errs := validation.IsValidLabelValue(parts[1]); len(errs) != 0 {
    				return nil, nil, fmt.Errorf("invalid label value: %q: %s", labelSpec, strings.Join(errs, ";"))
    			}
    			labels[parts[0]] = parts[1]
    		} else if strings.HasSuffix(labelSpec, "-") {
    			remove = append(remove, labelSpec[:len(labelSpec)-1])
    		} else {
    			return nil, nil, fmt.Errorf("unknown label spec: %v", labelSpec)
    		}
    	}
    	for _, removeLabel := range remove {
    		if _, found := labels[removeLabel]; found {
    			return nil, nil, fmt.Errorf("can not both modify and remove a label in the same command")
    		}
    	}
    	return labels, remove, nil
    }
-- Ghokun
Source: StackOverflow