Skip to content

๐Ÿงท 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

  • apply only updates fields it manages โ€” manual changes outside the YAML are retained unless overwritten
  • Some fields like spec.selector are immutable (change = recreate)
  • Best not to mix kubectl edit or imperative commands with apply for 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 apply for stable, repeatable infrastructure
  • Organize YAML into folders for modular apply
  • Avoid mixing declarative and imperative styles on the same object
  • Combine with kubectl diff and --dry-run for safe updates