Previous: kubectl for CKAD - exercise 3 - set env and replace 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 resourcepod is running in the cluster. We want to set resource requests and limits for this pod.

Run the pod:

kubectl run resourcepod --image nginx:alpine

Output:

pod/resourcepod created

Attempting to directly set resource requests and limits like this throws an error:

kubectl set resources resourcepod --requests='memory=15Mi,cpu=100m' --limits='memory=20Mi,cpu=100m'

Error:

error: failed to patch resources update to pod template Pod "resourcepod" is invalid: spec: Forbidden: pod updates may not change fields other than ...

But, there is a way around it!

Use kubectl set resources with --dry-run=client to generate the YAML manifest

kubectl set resources resourcepod --requests='memory=15Mi,cpu=100m' --limits='memory=20Mi,cpu=100m' --dry-run=client -o yaml | vim -

Vim opens the YAML file generated by the command above. Notice that the resources are set to the values we’ve provided.

Save the document as a new file (for example, resourcepodnew.yaml)

:w resourcepodnew.yaml

Replace the running pod with the new 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

  1. write (save) the document:
    ESC        // 'ESC'ape from INSERT mode
    :w         // 'w'rite (save) the document
    
  2. 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, pod will be deleted, and a new pod will be created.

Check the resource limits and requests for the pod

Use this command to verify:

kubectl get po resourcepod -o yaml | grep resources -A6

Alternatively:

kubectl describe pod resourcepod | grep -E "Requests|Limits" -A2

Close the document / quit Vim

:q

Vim quits, closing the edited YAML file.

Congratulations!

Practice these steps to master setting resource requests and limits and replacing pods directly from Vim with kubectl.

Next: kubectl for CKAD - exercise 5 - run a multi-container pod