Update deployment labels using "kubectl patch" does not work

8/26/2019

I am trying to update a label using kubectl.

When I use apply it works but it doesn't when doing a patch.

I tried kubectl patch deployment nginx-deployment --patch "$(cat nginx.yaml)"; it returns back no change where I would expect to get back a label change.

These are the only changes on my yaml.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: testLab
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.8
        ports:
        - containerPort: 80
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: helloWorld
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.8
        ports:
        - containerPort: 80

Is there a restriction on what patch updates or it am I doing something wrong?

I also tried specifying --type strategic and other types but none seem to work.

-- e.f.a.
kubectl
kubernetes
minikube

2 Answers

8/26/2019

You should be having something like this in your metadata:

metadata:
  name: nginx-deployment
  labels:
    label: testLabel2
-- Bimal
Source: StackOverflow

8/27/2019

After executing command kubectl patch on your second file (where you changed label) you should see following error:

Error from server: cannot restore map from string

After executing command kubectl apply on this file you should get following error :

error: error validating "nginx.yaml": error validating data: ValidationError(Deployment.metadata): unknown field "label" in io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta; if you choose to ignore these errors, turn validation off with --validate=false

Your deployment file should looks like this:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: helloWorld
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.8
        ports:
        - containerPort: 8

You missed to add space after app label.

Add space and then execute command kubectl patch deployment nginx-deployment --patch "$(cat nginx.yaml)" once again.

Here are useful documentations: labels-selectors, kubernetes-deployments, kubernetes-patch.

-- MaggieO
Source: StackOverflow