Skip to content
Latchkey

kubectl apply "field is immutable" on an existing resource in CI - Fix it

Some fields are fixed for a resource's lifetime: a Deployment's spec.selector, a Service's clusterIP, a Job's spec.template. Changing one and re-applying is rejected with "field is immutable". The resource must be recreated, not patched.

What this error means

A kubectl apply over an existing object fails with The Deployment "api" is invalid: spec.selector: Invalid value: ...: field is immutable after you edited a selector or another fixed field.

kubectl
The Deployment "api" is invalid: spec.selector: Invalid value:
v1.LabelSelector{...}: field is immutable

Common causes

An immutable field changed between deploys

A selector, clusterIP, or other fixed field differs from the live object, and Kubernetes does not allow updating it in place.

A label/selector refactor applied to a live object

Renaming match labels rewrites the selector, which a running Deployment treats as immutable.

How to fix it

Recreate the resource instead of patching it

  1. Confirm which field the message says is immutable.
  2. Delete the existing resource (accepting the brief gap) and apply the new spec.
  3. For zero-downtime, roll out under a new name and shift traffic.
Terminal
kubectl delete deployment api
kubectl apply -f deployment.yaml

Keep immutable fields stable across deploys

Treat the selector as a fixed contract; change pod template labels without altering the selector.

deployment.yaml
spec:
  selector:
    matchLabels:
      app: api   # do not change once deployed

How to prevent it

  • Never change a Deployment selector or Service clusterIP on a live object.
  • Recreate (or blue/green) when an immutable field must change.
  • Review manifest diffs for immutable-field edits before applying.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →