Skip to content

containers[0].image: Required value after kubectl patch --type=merge

Kubernetestested on kind, Kubernetes v1.37.0

You only want to set an environment variable and get an error about a missing image. The reason is the patch type: a JSON merge patch knows no keys in lists and replaces the whole container list.

Symptom

kubectl -n laden patch deploy web --type=merge -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","env":[{"name":"MODUS","value":"winter"}]}]}}}}'; echo "exit $?"
The Deployment "web" is invalid: spec.template.spec.containers[0].image: Required value
exit 1

Luckily the API server rejects the result – otherwise the container would run without an image.

Diagnosis

The same patch without --type (strategic merge) works, because containers are merged by their name.

kubectl -n laden patch deploy web -p '{"spec":{"template":{"spec":{"containers":[{"name":"nginx","env":[{"name":"MODUS","value":"herbst"}]}]}}}}'
kubectl -n laden get deploy web -o jsonpath='{.spec.template.spec.containers[0].image} {.spec.template.spec.containers[0].env}{"\n"}'
deployment.apps/web patched
nginx:1.30.7-alpine [{"name":"MODUS","value":"herbst"}]

Causes

--type=mergeJSON merge patch replaces lists

RFC 7386 knows no list keys. The containers list in the patch replaces the existing one completely – with a container that only has name and env.

strategic mergeThe default knows keys

Strategic merge patch is the default of kubectl patch and merges containers by their name field. CRDs do not support it, though.

Fix

For precise changes use a JSON patch with path and operation.
kubectl -n laden patch deploy web --type=json -p '[{"op":"replace","path":"/spec/template/spec/containers/0/env/0/value","value":"winter"}]'
kubectl -n laden get deploy web -o jsonpath='{.spec.template.spec.containers[0].env}{"\n"}'
deployment.apps/web patched
[{"name":"MODUS","value":"winter"}]

Don't: Reach for --type=merge on built-in Kubernetes objects with lists. Merge patch suits CRDs and simple maps; patch lists in built-in objects with strategic merge or a JSON patch.

▶
Break it yourself and find it – free
Kubernetes tools, Day 2: changing resources – three ways to patch and how they differ for lists.
Go to day 2 →

FAQ

When do I need a JSON patch?

When you want to change a specific list element by its index or delete a field (op remove).

Why does strategic merge not work on my CRD?

CRDs have no strategy information. There you have merge (lists are replaced) or a JSON patch.

Related error patterns

More