Update deployment labels using “kubectl patch” does not work in v1.18

6/26/2020

I am trying to update a label using kubectl v1.18.

I tried kubectl patch deployment my-deployment --patch "$(cat patch1.yaml)"; it returns an error

The Deployment "my-deployment" is invalid: spec.selector: Invalid value: v1.LabelSelector{MatchLabels:mapstringstring{"app":"nginx"}, MatchExpressions:[]v1.LabelSelectorRequirement(nil)}: field is immutable

apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    client: user
  name:  my-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: revproxy
  strategy:
     type: RollingUpdate
     rollingUpdate:
       maxUnavailable: 1
       maxSurge: 2
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: revproxy
    spec:
      containers:
      - image: nginx:1.7.9
        name: nginx
        resources: {}
      dnsPolicy: ClusterFirst
      restartPolicy: Always

The patch yaml is

spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
-- Vijay S
kubectl
kubernetes

1 Answer

6/26/2020

From the docs here

Note: In API version apps/v1, a Deployment's label selector is immutable after it gets created.

Motivations for making label selector immutable are

  1. Changing selectors leads to undefined behaviors - users are not expected to change the selectors
  2. Having selectors immutable ensures they always match created children, preventing events such as accidental bulk orphaning

If you want to make modification to label selector you will have to delete the exiting deployment and recreate it.

Modification to only metadata.labels should work though.

-- Arghya Sadhu
Source: StackOverflow