Kubernetes and Cloud Native Associate (KCNA)Kubernetes FundamentalsMedium
A developer needs to create a new Kubernetes object using a YAML manifest file named `my-app.yaml`. The file is correctly formatted and contains the necessary API version, kind, metadata, and spec. Which `kubectl` command should be used to apply this manifest to the cluster?
- A`kubectl apply -f my-app.yaml`
- B`kubectl create -f my-app.yaml`
- C`kubectl patch -f my-app.yaml`
- D`kubectl run -f my-app.yaml`
Show answer & explanationAnswer & explanation
Correct answer: A. `kubectl apply -f my-app.yaml`
The `kubectl apply` command is the standard and recommended way to create or update Kubernetes resources from a YAML file. It performs a 'declarative' update, meaning it intelligently determines whether to create, update, or delete resources based on the manifest and the current state.
Why the other options are wrong
- B. `kubectl create` is generally used for creating new resources, but `apply` is preferred for idempotent operations and managing existing resources.
- C. `kubectl patch` is used for modifying existing resources with specific changes, not for applying a full manifest to create or update.
- D. `kubectl run` is primarily used for quickly creating Pods or Deployments from a command line, not for applying general YAML manifests.
`kubectl apply`
A `kubectl` command used to create or update Kubernetes resources from a file (e.g., YAML). It is idempotent and performs declarative updates, comparing the desired state in the file with the current state in the cluster.
- Recommended for declarative management.
- Creates resources if they don't exist, updates if they do.
- Idempotent, safe to run multiple times.
Memory trick: Apply for All changes, Create for New, Run for Quick Pods, Patch for Precise edits.