Kubernetes and Cloud Native Associate (KCNA)Kubernetes FundamentalsEasy
A developer needs to create a new Kubernetes object from a YAML file named `config.yaml`. They want to ensure that if the object already exists, it will be updated to reflect the changes in the file, and if it doesn't exist, it will be created. Which `kubectl` command should they use for this operation?
- A`kubectl apply -f config.yaml`
- B`kubectl patch -f config.yaml`
- C`kubectl create -f config.yaml`
- D`kubectl set -f config.yaml`
Show answer & explanationAnswer & explanation
Correct answer: A. `kubectl apply -f config.yaml`
`kubectl apply` is the recommended command for creating and updating Kubernetes resources declaratively from a file. It intelligently handles both creation and updates.
Why the other options are wrong
- B. `kubectl patch` is for modifying specific fields of an existing resource, not for creating or full declarative updates.
- C. `kubectl create` is for creating new resources; it will fail if the resource already exists.
- D. `kubectl set` is used for specific updates like image versions or resource limits, not for general creation/update from a file.
kubectl apply
The `kubectl apply` command is used for applying changes to Kubernetes resources defined in a file. It creates the resource if it doesn't exist or updates it if it does, based on the file's content.
- Idempotent: running it multiple times has the same effect.
- Uses server-side apply (or client-side apply) to merge changes.
- Preferred method for declarative configuration management.
Memory trick: Apply Always Adapts