kubectl for CKAD - exercise 3 - set env and replace pod
Previous: kubectl for CKAD - exercise 2 - edit and replace a pod
Getting Started with kubectl for CKAD exam
First things first
Put your mouse away, forget you have a touchpad and keep your hands on the keyboard.
Start your terminal, the adventure continues…
The situation with the CKAD and other CK* exams is that we need to be fast. To be fast when editing YAML files and applying them with kubectl apply means - don’t leave Vim. Yes, we can run kubectl replace
right from inside Vim!
Scenario
A pod named colorpod
is running in the cluster. It has an environment variable APP_COLOR=red
. We want to change the value of APP_COLOR
to green
.
Run a pod with this command:
kubectl run colorpod --image nginx:alpine --env APP_COLOR=red
Output:
pod/colorpod created
To check the environment variables:
kubectl set env pods colorpod --list
Output:
# Pod colorpod, container colorpod
APP_COLOR=red
Attempting to directly set the environment variable like this throws an error:
kubectl set env pods colorpod APP_COLOR=green
But, there is a way around it!
Use kubectl set env
with --dry-run=client
to get the colorpod’s YAML manifest and replace the pod
kubectl set env pods colorpod APP_COLOR=green --dry-run=client -o yaml | vim -
Vim opens the YAML file generated by the command above. Notice that the value of the APP_COLOR
env variable is green
.
Save the document as a new file (for example, new-colorpod.yaml
)
:w new-colorpod.yaml
Replace the running pod with the updated definition directly from Vim
:!kubectl replace -f % --force --grace-period 0
If there is an error and the pod has not been replaced, read the error, correct the YAML, and repeat the steps
- write (save) the document:
ESC // 'ESC'ape from INSERT mode :w // 'w'rite (save) the document
- Use the previous
kubectl replace
command::up arrow // repeat to find the command :!kubectl replace -f % --force --grace-period 0 Enter
If everything is fine with the updated pod definition, it will be deleted, and a new pod will be created.
Close the document / quit Vim
:q
Vim quits, closing the edited YAML file.
Check, if the environment variable is set correctly on the newly created pod:
kubectl set env pods colorpod --list
Congratulations!
Practice these steps to master setting pod environment variables and replacing pods directly from Vim with kubectl.
Next: kubectl for CKAD - exercise 4 - set resources and replace pod