To change a Kubernetes object that is already deployed, kubectl offers three
commands: edit opens the object in an editor, patch changes one precise
field, replace sends the whole object back from a file. This lesson, meant
for administrators who run a cluster, teaches you to choose between the three,
to predict the effect of a patch on a list, and to keep the cluster from
drifting away from the Git repository. It is the first practice lesson of the
"Maintain and upgrade" module: a maintenance often starts with a change of this
kind, before the maintenance preparation and the node drain taught in the next
lessons.
What you will learn
- Choose between
kubectl edit,kubectl patchandkubectl replaceaccording to the urgency and the scope of the change - Write a patch of the three types (strategic, merge, json) and predict its
effect on a list such as
containers - Spot the drift between the cluster and the versioned manifest, then resolve it
- Predict what
replacedoes without--force(version conflict, immutable fields) and with--force(delete then recreate)
Prerequisites
This lesson assumes two tasks taught earlier in the course: deploying a
manifest with kubectl apply
(create and apply),
and following or undoing a Deployment rollout
(rolling updates and rollbacks).
Comparing a file with the cluster using kubectl diff is explained in this
lesson, where it is needed; the lesson
diff and wait
goes deeper.
You also need a test cluster, for example the kind cluster of the course, and
write rights on a namespace.
The outputs in this lesson come from a Kubernetes 1.37 cluster with kubectl
1.37. The examples change a web Deployment in the boutique namespace, which has two
containers: the web server and a log agent, log-agent. This second
container is not decorative, it makes the list trap described below
visible.
# web.yaml: the version stored in GitapiVersion: apps/v1kind: Deploymentmetadata: name: web namespace: boutiquespec: replicas: 2 selector: matchLabels: app: web template: metadata: labels: app: web spec: containers: - name: web image: nginx:1.27@sha256:6784fb0834aa7dbbe12e3d7471e69c290df3e6ba810dc38b34ae33d3c1c05f7d ports: - containerPort: 80 - name: log-agent image: busybox:1.37@sha256:a7dbc319b1438115a207e11930dc4bb3e643dcb3ec0bdd694bb36cd8fad289ec command: ["sh", "-c", "sleep 3600"]To reproduce, create the namespace with kubectl create namespace boutique,
then deploy the manifest with kubectl apply -f web.yaml. The command
kubectl -n boutique get deploy web must show 2/2 in the READY column:
both replicas are running.
Which command should you choose to change a live object?
The rule fits in one sentence: apply from Git day to day, patch for a
targeted and scriptable change, edit for an emergency fix, replace when a
complete file must be the authority. The three commands of this lesson write
directly to the cluster, without going through the Git repository: they are
fast, and each one leaves a drift to resolve afterwards, unless the file
you send itself comes from Git.
| Need | Command | What it sends to the server |
|---|---|---|
| Fix something during an incident | kubectl edit | only what you changed in the editor, as a patch |
| Change one field, in a script | kubectl patch | only the fields of the patch |
| Impose a complete file | kubectl replace -f | the whole object, as written in the file |
| Manage the object day to day | kubectl apply -f | the difference computed against the last applied version |
Read this table through its last column. A patch only touches what it
names. kubectl edit builds one itself: it compares the original object with
the one you saved, and sends only the difference. replace, on the other hand,
sends back the whole object, so any field missing from the file goes with
it. That is what makes replace more dangerous than it looks, and patch
safer in a script.
kubectl edit: fix things live during an incident
kubectl edit opens the object in a text editor and sends your changes to the
server as soon as you save and quit. kubectl computes the difference between
the original object and your version, then sends it as a patch: strategic merge
for native types, JSON merge for custom resources (these patch types are
described below). It is the tool of the incident: no file to write, no pull
request to wait for. The price is traceability: the change exists only in
the cluster.
kubectl -n boutique edit deploy webThe editor used is the one in the KUBE_EDITOR variable, otherwise the one
in EDITOR, otherwise vi on Linux. For a graphical editor, the command must
wait for the file to be closed, otherwise kubectl thinks you quit without
changing anything: export KUBE_EDITOR="code --wait". Always specify the
namespace with -n: without it, kubectl opens the object of the
current namespace, which is not necessarily the one of the incident.
Three outcomes are possible, and kubectl tells them apart by its message:
deployment.apps/web edited # change sent and acceptedEdit cancelled, no changes made. # file saved without any changeerror: deployments.apps "web" is invalid # change refused by the APIA copy of your changes has been stored to "/tmp/kubectl-edit-4114702328.yaml"error: Edit cancelled, no valid changes were saved.Quitting the editor without saving therefore cancels everything, at no
risk. An invalid change, such as an empty image, is refused by the API
server: nothing is applied, and what you typed is kept in a temporary file in
/tmp so that you do not lose it.
How do you avoid drift between the cluster and Git?
Drift is the gap between what runs in the cluster and what the manifest in the
Git repository describes. An edit or a patch creates it for sure. It is
not serious as long as it is known: it becomes so at the next kubectl apply of
the manifest, or at the next synchronization of a GitOps tool, which
overwrites your fix without warning.
The scenario takes two commands to reproduce. An operator scales the Deployment up to four replicas during a load peak, then the comparison with the Git file reveals the gap:
kubectl -n boutique patch deploy web -p '{"spec":{"replicas":4}}'kubectl diff -f web.yaml- replicas: 4+ replicas: 2The output of kubectl diff, shortened here to the useful lines, shows the
live value with - and the one the file would impose with +. The exit code
is 1 when a difference exists and 0 when the cluster matches the manifest, which lets you
detect drift in a script or a CI. If nobody carries the change over, the next
kubectl apply -f web.yaml brings the Deployment back to two replicas, right
in the middle of the peak.
The complete procedure, when an emergency forces you to change things outside Git:
-
Check the context and save the current state
Terminal window kubectl config current-contextkubectl -n boutique get deploy web -o yaml > web.avant.yaml -
Change the object with
kubectl editorkubectl patch, then check the result withkubectl -n boutique rollout status deploy/web. -
Compare the cluster with the versioned manifest
Terminal window kubectl diff -f web.yaml -
Carry the change over into
web.yaml, have it reviewed and merged like any pull request.kubectl diff -f web.yamlmust then show nothing and return code 0: the drift is resolved for every field that the manifest declares.
kubectl diff compares the cluster with what applying the manifest would
produce. A field changed live that the manifest does not declare therefore does
not show up: an empty diff does not prove that the cluster is back to its
original state. For those fields, compare with the backup of step 1 or reread
the object with kubectl get -o yaml.
The backup of step 1 is not a clean manifest: it contains fields written by
the server (status, uid, resourceVersion). It is used to compare and,
as a last resort, to restore, never to replace the file in the repository.
kubectl patch: change one precise field
kubectl patch sends the server a fragment of an object and changes only the
fields it names. The rest of the object is not sent back, so it is not exposed
to a copy error. It is the command of scripts and operating procedures: the same line
produces the same effect on every run.
kubectl -n boutique patch deploy web -p '{"metadata":{"annotations":{"incident-ref":"INC-2026-0142"}}}'deployment.apps/web patchedThe patch is written in JSON between single quotes, so that the shell
leaves the double quotes it contains alone. Run again identically, the command
answers deployment.apps/web patched (no change): this message is not an error,
it confirms that the object was already in the requested state. Malformed
JSON, for its part, is refused (invalid JSON patch) before any change.
Which patch type should you choose?
kubectl patch accepts three formats, chosen with --type: strategic (the
default), merge and json. They differ mostly in how they treat lists,
and that is where accidents happen.
| Type | Option | Effect on a list | Use case |
|---|---|---|---|
| Strategic merge | --type=strategic (default) | merges the elements by their key, for example name for containers | native resources |
| JSON merge (RFC 7386) | --type=merge | replaces the whole list with the one in the patch | custom resources, simple fields |
| JSON patch (RFC 6902) | --type=json | works on a precise index: add, replace, remove | append to a list, targeted removal |
Strategic merge is specific to Kubernetes: each native type declares how to
merge its lists, containers by container name, ports by port number.
JSON merge ignores these rules and treats every list as a single value.
JSON patch merges nothing: it describes operations on paths.
The list trap: strategic keeps, merge replaces
The same patch, which names only the web container, keeps log-agent in
strategic and deletes it in merge. This is the difference to remember from
this lesson, and you can check it with two commands. First in strategic,
the default type, to move web to nginx 1.30:
kubectl -n boutique patch deploy web -p '{"spec":{"template":{"spec":{"containers":[{"name":"web","image":"nginx:1.30@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb"}]}}}}'kubectl -n boutique get deploy web -o jsonpath='{range .spec.template.spec.containers[*]}{.name}{"\n"}{end}'weblog-agentStrategic merge found the web container by its name, changed its
image, and left log-agent intact. The same fragment sent with
--type=merge gives a very different result:
kubectl -n boutique patch deploy web --type=merge -p '{"spec":{"template":{"spec":{"containers":[{"name":"web","image":"nginx:1.27@sha256:6784fb0834aa7dbbe12e3d7471e69c290df3e6ba810dc38b34ae33d3c1c05f7d"}]}}}}'kubectl -n boutique get deploy web -o jsonpath='{range .spec.template.spec.containers[*]}{.name}{"\n"}{end}'webJSON merge replaced the entire list with the one in the patch: log-agent
is gone, and the Deployment started a rollout to recreate all the Pods without
it. The server refused nothing, since the resulting object remains valid.
Remember the rule: on a list of a native resource, stay in strategic or switch
to json, never merge.
For the image alone, kubectl set image deploy/web web=<image> has the same
effect as the strategic patch, and is more readable. The patch keeps its
advantage for any other field, and for a script that changes several fields
at once.
JSON patch: target a list index
JSON patch designates a field by a path, such as
/spec/template/spec/containers/0/env, and applies an operation to it. The
segments are separated by /, list indexes start at 0, and the special
segment - designates the end of an existing list. Adding an environment
variable to the first container is done in two steps, depending on whether the
list already exists:
# The env list does not exist yet: we create itkubectl -n boutique patch deploy web --type=json \ -p '[{"op":"add","path":"/spec/template/spec/containers/0/env","value":[{"name":"LOG_LEVEL","value":"debug"}]}]'
# It exists: we add an element at the endkubectl -n boutique patch deploy web --type=json \ -p '[{"op":"add","path":"/spec/template/spec/containers/0/env/-","value":{"name":"FEATURE_X","value":"on"}}]'
kubectl -n boutique get deploy web -o jsonpath='{.spec.template.spec.containers[0].env}'[{"name":"LOG_LEVEL","value":"debug"},{"name":"FEATURE_X","value":"on"}]The remove operation removes an element by its index
(/spec/template/spec/containers/0/env/1), and replace changes an
existing value. A replace operation on an absent path fails: the server
only answers The request is invalid: the server rejected our request due to an error in our request,
without naming the faulty path. Before writing a path, read the real structure
with kubectl get deploy web -o json: an index shifts as soon as an element is
added or removed.
How do you patch a custom resource?
Strategic merge exists only for native types: on a custom resource (CRD), use
--type=merge or --type=json. A custom resource does not carry the list
merge rules that make up strategic merge, and the server refuses this format
with an explicit message:
error: application/strategic-merge-patch+json is not supported by demo.k-operer.io/v1, Kind=Koperer: the body of the request was in an unknown format - accepted media types include: application/json-patch+json, application/merge-patch+json, application/apply-patch+yamlThe same fragment passed with --type=merge is accepted. Keep this in mind
with the objects of an operator (certificates, databases, policies): they
are almost all custom resources, and the default type of kubectl patch
fails on them.
kubectl replace: replace the whole object
kubectl replace -f replaces the existing object with the content of the file:
it is an update, the object keeps its identity and its Pods are not deleted.
Everything the file does not mention goes back to its default value, or
disappears if it has none, like an annotation. The object must exist: on a
missing object, the command fails with NotFound instead of creating it.
What does replace do without --force?
Without --force, replace deletes nothing: the object keeps the same uid,
and the Pods in place keep running. Here is the test on the web Deployment, moving
replicas from 2 to 3 in a fresh export:
kubectl -n boutique get deploy web -o yaml > web.export.yaml# change replicas: 2 to replicas: 3 in the filekubectl replace -f web.export.yamlkubectl -n boutique get pods -l app=webdeployment.apps/web replacedNAME READY STATUS RESTARTS AGEweb-66597f58f5-d88sg 2/2 Running 0 6sweb-66597f58f5-lnhst 2/2 Running 0 6sweb-66597f58f5-m9b9v 0/2 ContainerCreating 0 0sThe two existing Pods stayed, the third is added. If the file changes the Pod
template, an image for example, the Deployment applies its usual strategy:
a rolling update, Pod by Pod, with a new revision in
kubectl rollout history. replace therefore does not interrupt the service
any more than an apply carrying the same change.
The danger lies elsewhere: a field missing from the file is reset to its
default value. Sent with a manifest that does not declare replicas,
replace brought the Deployment from three replicas down to one, the
default value, without any warning. That is the meaning of the command help:
"the complete resource spec must be provided".
Why does replace refuse a file exported too early?
A file exported by kubectl get -o yaml carries the resourceVersion of the
object at that moment, and the server refuses to replace an object that has
changed since. This mechanism, optimistic concurrency, prevents you from
overwriting without knowing it the change made by a colleague or by a
controller. Replaying the same export a second time is enough to trigger it:
Error from server (Conflict): error when replacing "web.export.yaml": Operation cannot be fulfilled on deployments.apps "web": the object has been modified; please apply your changes to the latest version and try againOn a Deployment, the object changes without anyone touching it: the
controller updates its status, which changes the resourceVersion. During
a rollout, an export a few seconds old is already stale. The remedy is to
export again, reapply the change and rerun. A file without
resourceVersion, such as a manifest from Git, is not checked: it replaces the
object whatever its state, which also overwrites the concurrent change that the
conflict would have reported.
What should you do about an immutable field?
Some fields cannot change after creation, such as the selector of a
Deployment, and replace refuses them like patch or apply do. The server
names the field at fault:
The Deployment "web" is invalid: spec.selector: Invalid value: {"matchLabels":{"app":"web2"}}: field is immutableNo update gets around this rule: you must delete then recreate the
object. That is exactly what replace --force does, with its consequences.
replace --force: delete then recreate
kubectl replace --force deletes the object then recreates it from the file:
it is no longer an update, and all the Pods of a Deployment are stopped at
once. The output announces it in two lines:
kubectl replace --force -f web.yamlkubectl -n boutique get pods -l app=webdeployment.apps "web" deleted from boutique namespacedeployment.apps/web replacedNAME READY STATUS RESTARTS AGEweb-66597f58f5-b8pnx 0/2 Pending 0 0sweb-66597f58f5-d88sg 2/2 Terminating 0 15sweb-66597f58f5-lnhst 2/2 Terminating 0 15sweb-66597f58f5-tzfsh 0/2 ContainerCreating 0 0sThe old Pods all go to Terminating while the new ones are barely starting:
none is ready, and a Service that targets these Pods has no target left. The
recreated object carries a new uid and restarts at revision 1: its rollout
history is lost. Reserve --force for the only case that requires it, an
immutable field to change, in a window where the interruption is accepted.
Should you use replace or apply?
apply computes a difference and touches only the fields it manages;
replace sends the whole object and resets everything the file omits. That is
why apply remains the default choice as soon as another actor, an
autoscaler or an operator, writes to the same object.
| Criterion | kubectl replace | kubectl apply |
|---|---|---|
| Missing object | NotFound failure | creation |
| Field missing from the file | reset to its default value | left as is if it was never applied |
| Stale exported file | resourceVersion conflict | not applicable, apply does not read it |
| Usage | impose a complete file, occasionally | declarative management day to day |
A replace from a file that does not carry the
kubectl.kubernetes.io/last-applied-configuration annotation removes it
from the object: the next kubectl apply then shows a warning and sets it
again. This message is harmless, it signals that an imperative command went
through.
How do you roll back after a failed change?
For a Deployment, kubectl rollout undo goes back to the previous revision of
the Pod template; for any other object, reapply the version from Git. The
native rollback is taught in the lesson
rolling updates and rollbacks:
it covers only the template, not replicas or the annotations, and does not
work after a replace --force, which erased the history.
For an object without history, such as a ConfigMap or a Service, the reliable
source remains the versioned manifest: kubectl apply -f. Failing that, the
backup taken before the intervention can be replayed with
kubectl replace -f, after removing its resourceVersion line, otherwise the
server answers with the conflict seen above.
Troubleshooting
The messages of these three commands come either from the API server, which refuses an invalid object or a concurrent write, or from kubectl itself. The table lists the exact messages of Kubernetes 1.37, so that you recognize them at a glance.
| Symptom | Cause | Solution |
|---|---|---|
Edit cancelled, no changes made. | file saved without any change | nothing to do, no change was sent |
Edit cancelled, no valid changes were saved. | change refused by the API | rerun kubectl edit and fix it, the refused input stays readable in /tmp |
the object has been modified; please apply your changes to the latest version | stale resourceVersion | export again, redo the change, rerun |
field is immutable | field that cannot be changed, such as spec.selector | replace --force in an accepted interruption window |
NotFound on a replace | the object does not exist | kubectl apply -f or kubectl create -f |
The request is invalid on a json patch | missing path or wrong index | read the structure with kubectl get -o json |
strategic-merge-patch+json is not supported | custom resource | --type=merge or --type=json |
| a container disappeared after a patch | --type=merge on a list | patch again in strategic, or kubectl rollout undo |
| the fix is cancelled the next day | drift overwritten by an apply or by GitOps | carry the change over into the manifest |
Put it into practice
This lab replays an incident on the web Deployment of the magasin namespace, which has two containers. You move web to nginx 1.30 without losing the log-agent container and without recreating the object, you note the incident on the Deployment, then you set log-agent to debug. Finally you carry over into the manifest ~/magasin/web.yaml every change made in the cluster, including the four replicas set during the load peak, until kubectl diff sees no difference at all.
The validation checks four requirements. web runs nginx 1.30 while log-agent is still there, and the Deployment is the same object (same uid). The incident-ref annotation of web names the incident. log-agent, the second container of the list, carries LOG_LEVEL=debug. Finally kubectl diff sees no difference between the cluster and the manifest, and the four replicas of the peak are kept. A patch that replaces the whole list of containers, or an object deleted then recreated, fails the first requirement.
The module challenge, done alone and without hints, has its own page: Bring live changes back to the Git repository.
Key takeaways
kubectl editis the tool of the incident: save the object before, carry the change over into Git after.kubectl patchonly touches the fields it names; the default type is strategic merge.- On a list, strategic merges by key (the container name), merge replaces the whole list, json works on an index.
- A custom resource refuses strategic merge:
--type=mergeor--type=json. kubectl diff -freveals the drift of the fields that the manifest declares: code 1 as long as the cluster differs from the versioned manifest. A field changed live and absent from the manifest does not show up.kubectl replacewithout--forceupdates the object in place, but resets to their default value the fields missing from the file and refuses a staleresourceVersion.replace --forcedeletes then recreates: all the Pods go down at once, the rollout history is lost.
Knowledge check
This quiz checks that you can choose the command, predict the effect of a
patch type on a list, and anticipate what replace does with and
without --force.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Bring live changes back to the Git repository
A new full quiz with random questions
Work again only on the questions you missed