๐งท kubectl apply: Declarative Resource Management
The kubectl apply command is a core part of the declarative Kubernetes workflow. It creates or updates resources to match the desired state defined in a file.
โ
Why Use kubectl apply?
- Idempotent: running it multiple times has the same effect
- Only changes fields that differ
- Stores last applied configuration for intelligent merging
- Ideal for GitOps and CI/CD pipelines
๐ ๏ธ Common Usage
kubectl apply -f <file.yaml>
Apply a folder:
kubectl apply -f manifests/
Dry-run to preview changes:
kubectl apply -f deployment.yaml --dry-run=client
๐ Create vs Apply vs Replace
| Command | Purpose | Behavior |
|---|---|---|
kubectl create |
Create new object | Fails if it exists |
kubectl apply |
Create or update based on diff | Smart merge; stores last config |
kubectl replace |
Replace full object | Deletes and recreates (dangerous for live objects) |
๐ง Behind the Scenes: Last Applied Config
Kubernetes stores the last applied configuration as an annotation on the object:
metadata:
annotations:
kubectl.kubernetes.io/last-applied-configuration: '{...}'
This is used to calculate the diff intelligently when reapplying.
๐ซ Gotchas
applyonly updates fields it manages โ manual changes outside the YAML are retained unless overwritten- Some fields like
spec.selectorare immutable (change = recreate) - Best not to mix
kubectl editor imperative commands withapplyfor the same object
๐งช Use kubectl diff
Preview changes before applying:
kubectl diff -f my-deployment.yaml
โ๏ธ Apply from stdin
cat pod.yaml | kubectl apply -f -
โ Summary
- Use
applyfor stable, repeatable infrastructure - Organize YAML into folders for modular apply
- Avoid mixing declarative and imperative styles on the same object
- Combine with
kubectl diffand--dry-runfor safe updates