Kubectl tips and tricks

When you need a pod starter yaml, create an alias like below.

After 1.18:
alias pod=‘kubectl run $name --image=$image --dry-run=client -o yaml > $name_$image_pod.yaml && vi $name_$image_pod.yaml’

Before 1.18:
alias pod=‘kubectl run $name --image=$image --generator=run-pod/v1 --dry-run -o yaml > $name_$image_pod.yaml && vi $name_$image_pod.yaml’

Then just set image and name then type “pod”

Save your time :slight_smile:

1 Like

Hi. I would also add line numbering. So, that would be:
set nu ts=2 sw=2 expandtab ruler

I found also useful to use:

export do="--dry-run=client -o yaml"
export d="--dry-run=client"
export oy="-o yaml"
source <(kubectl completion bash)
echo "source <(kubectl completion bash)" >> ~/.bashrc
alias k=kubectl
complete -F __start_kubectl k

Additionally, in vim you can indent/unident lines:
5>> to indent five lines
5<< to unindent five lines
3>>. to indent three lines, indent once more
Shift+V then up or down or jj then > to indent marked block

When there are tabs instead of space characters:
:set list - identify tabs,
:retab! - fix tabs

When every pasted line indents:
:set paste - before pasting
:set nopaste - after pasting
Or add use:
:set pastetoggle=<F2> - press i and then F2, paste and after that press F2

On my Windows laptop I have no Insert button, so:
Right Ctrl+fn+E - copy
Right Shift+fn+E - paste

Check connectivity:
wget -O-
curl 80
nc -vz 80


kubectl explain Pods.spec.containers --recursive

kubectl run # without flag creates a deployment
kubectl run — restart=Never #Creates a Pod
kubectl run — restart=OnFailure #Creates a job
kubectl run — restart=OnFailure — schedule=”* * * * *” # Creates a cronjob

Some useful aliases & stuffs

alias k=‘kubectl’
alias kgp=‘kubectl get pods’
alias kgd=‘kubectl get deployment’
alias kgs=‘kubectl get service’

alias kga=‘kubectl get all’
alias kgaa=‘kubectl get all -A’

alias kdp=‘kubectl delete pod --grace-period=0 --force’

alias kcf=‘kubectl create -f’
alias kaf=‘kubectl apply -f’

export drc=’–dry-run=client -o yaml’

Identify your shell

echo $SHELL

source <(kubectl completion bash)
alias k=kubectl
complete -F __start_kubectl k
export do="–dry-run=client -o yaml"
export fg="–force --grace-period=0"
export kc=’‘kubectl config set-context $(kubectl config current-context) --namespace’’
vi ~/.vimrc
set ts=2 sw=2 expandtab ruler
set backspace=indent,eol,start

Here is how we could get only that pod that uses most CPU:
k top pod -n kube-system --sort-by=cpu | head -2 | tail -n 1


Posting in this thread directly because we’ve had to remove posts / ban users after posting in here several times now.

This is not a place for exam notes. You cannot use this on the CKA/CKAD. Posting such content will result in an immediate ban.

Posts containing exam content from the CKA/CKAD will be immediately removed and the information passed to the CNCF with a likely result of having your certificate being revoked.

1 Like


it was not my intention to use the forum improperly.
I have consulted your forum a lot for the study of k8s. I apologize if I made you work today to remove posts and utilities.
I hope you won’t delete this user account, because it has been very useful to me to study and discover things, and I would like to consult it and vice-versa in an active way.
Good work and good life

1 Like

I suggest also for example pod
Kubect explain pod --recursive | less
To see the structure or
Kubectl explain pod --recursive | grep -I version
Too looking for the value of APIversion for example

We put together this kubectl cheat sheet, thought it might be helpful to learn some initial tips and tricks:

1 Like

I practice a lot in Katacoda (it’s a temporary - 60mins - workspace). That’s why every time I need to download the latest kubectl client and set up .bashrc and .vimrc. Pasting those lines saves time:

curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/linux/amd64/kubectl
chmod +x ./kubectl
sudo mv ./kubectl $(which kubectl)
echo 'source <(kubectl completion bash)' >> ~/.bashrc
echo 'alias k=kubectl' >> ~/.bashrc
echo 'complete -F __start_kubectl k' >> ~/.bashrc
source .bashrc
echo 'set nu ts=2 sw=2 expandtab ruler' > ~/.vimrc
echo 'set backspace=indent,eol,start' >> ~/.vimrc
source ~/.vimrc
export do="--dry-run=client -oyaml"
export now="--grace-period=0 --force"
1 Like

I find useful the below lines:
alias k=kubectl
source <(k completion bash)
source <(k completion bash | sed s/kubectl/k/g)

vi ~/.vimrc

autocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab ruler incsearch
set number
set ignorecase
set backspace=indent,eol,start
set cursorline
set list

If you explain a little more about these things. It will help a lot to us.

Thank you Aydarsh

I found very useful your set of tricks and tips and he has helped me a lot to define my own set and to figure it out the way I faced the exam.

I am sharing some of my thoughts on them.

First of all, I prefer to deal with a limited set of alias, easy to remember and that saves a lot of time. I also look for the very basic configuration of my editor (line number, tabs as spaces, etc). Choose the ones you think would help and practice with them all the time. I am listing below the ones that were useful for me.

  echo "set tabsize 2" | tee -a ~/.nanorc
  echo "set tabstospaces" | tee -a ~/.nanorc
  echo "set linenumbers" | tee -a ~/.nanorc

  alias k=kubectl
  alias kn='k config set-context --current --namespace'
  alias kcc='k config get-contexts'
  alias kd='k --force --grace-period=0 delete po'
  alias ka='k get all'
  alias kaa='k get all -A'
  alias kcf='k create -f'
  . <(kubectl completion bash)
  complete -F __start_kubectl k
  export do='-o yaml --dry-run=client'
  export KUBE_EDITOR=nano

When time is an important variable to consider, and you are like me --not a born in the terminal guy-- Nano is your editor, here the most recommended shortcuts to practice with.

Remember you can always use F1/^G

Useful Keyboard Shortcuts

Goto, Find, Replace

^_ (M-G) Go to line and column number
^W (F6) Search forward for a string or a regular expression
^\ (M-R) Replace a string or a regular expression

Copy and paste

^K (F9) Cut current line (or marked region) and store it in cutbuffer
^U (F10) Paste the contents of cutbuffer at current cursor position


M-6 (M-^) Copy current line (or marked region) and store it in cutbuffer
M-A (^6) Mark text starting from the cursor position


M-} (Tab) Indent the current line (or marked lines)
M-{ (Sh-Tab) Unindent the current line (or marked lines)

Reading, Writing, Exiting

^X (F2) Close the current buffer / Exit from nano
^O (F3) Write the current buffer (or the marked region) to disk
^R (Ins) Insert another file into current buffer (or into new buffer)

I will just add to the connectivity commands recommended by aydarsh, the ones I think should help to create test pod on-demand or connect quickly to running containers

wget -O-
curl 80
nc -vz 80
k exec -it pod -- [command]
k run bash -it --image=bash --rm -- [command]

My config, if anyone interested:

set nu tabstop=2 shiftwidth=2 expandtab

source <(kubectl completion bash)
alias k=kubectl
complete -F __start_kubectl k
export do="-o yaml --dry-run=client"
export gf="–grace-period=0 --force"
alias kn='kubectl config set-context --current --namespace ’

1 Like

here is my .vimrc file, hope it will be helpful.

syntax enable
set tabstop=2       " number of visual spaces per TAB
set softtabstop=2   " number of spaces in tab when editing
set expandtab       " tabs = spaces

set number		" show line numbers
set cursorline		" highlight the current line
set showcmd		" show command in bottom bar
filetype indent on	" load filetype specific indent files in ~/.vim/indent/*.vim
set wildmenu
set lazyredraw
set showmatch		" show matches of {} [] ()

set incsearch		" search as characters are entered
set hlsearch		" highlight matches
set ignorecase		" ignore upper/lower case when searching
let mapleader = "," 	" leader is comma
" turn off search highlight, mapping to ,<space>
nnoremap <leader><space> :nohlsearch<CR>

set backspace=indent,eol,start   " allows backspace to delete words

Enable the kubelet autocomplete

source <(kubectl completion bash) # setup autocomplete in bash into the current shell, bash-completion package should be installed first.
echo "source <(kubectl completion bash)" >> ~/.bashrc # add autocomplete permanently to your bash shell.

alias k=kubectl
complete -F __start_kubectl k

Also some commands I found tricky:

Core Concepts:
kubectl get pods -o=jsonpath="{.items[ * ][‘metadata.name’, ‘metadata.namespace’]}" <- list all pod with name and namespace
kubectl set image pod/nginx nginx=nginx:1.17.1
kubectl get po nginx -o jsonpath=’{.spec.containers[\ * ].image}{"\n"}’
kubectl logs busybox -p <- check previous logs
kubectl exec -it busybox – wget -o- --timeout=3
kubectl get po nginx --v=7
kubectl get po -o=custom-columns=“POD_NAME:.metadata.name, POD_STATUS:.status.containerStatuses[ ].state”
kubectl get pods --sort-by=.metadata.name

kubectl get secret mysecret2 -o jsonpath=’{.data.username}{"\n"}’ | base64 -d

Multi-Container Pods:
apt-get update && apt-get install -y curl
curl localhost:30080 -m 3
kubectl top pod busybox --containers

kubectl explain Pod.spec.containers.livenessProbe
kubectl explain Pod.spec.containers.readinessProbe
kubectl get events --sort-by=.metadata.creationTimestamp > file.log
kubectl logs --follow hello
kubectl top pod --all-namespaces | sort --reverse --key 3 --numeric | head -3 > cpu-usage.txt

Pod Design:
kubectl get pods --show-labels
kubectl label pod/nginx-dev3 env=uat --overwrite
k label po --all env-
kubectl get pod nginx{1…3}
kubectl annotate pod nginx-dev{1…3} name=webapp
k rollout status
history [–revision]
undo [–to-revision]
kubectl autoscale deploy webapp --min=10 --max=20 --cpu-percent=85
kubectl get hpa

spec: <- job spec
completions: 10
parallelism: 10

kubectl create cronjob date-job --image=busybox --schedule="*/1 * * * *" - every minute

Services and Networking:
kubectl run nginx --image=nginx --restart=Never --port=80 --expose <- expose creates clusterip automatically :slight_smile:
kubectl expose deploy foo --port=6262 --target-port=8080 <- match all pods with label app=foo

State persistance:
cat /etc/passwd | cut -f 1 -d ‘:’ > /etc/foo/passwd <- copies first column from file with : delimiter

1 Like

Reposting this further down in the thread because it continues to be a problem:

Posting in this thread directly because we’ve had to remove posts / ban users after posting in here several times now.

This is not a place for exam notes. You cannot use this on the CKA/CKAD. Posting such content will result in an immediate ban.

Posts containing exam content from the CKA/CKAD will be immediately removed and the information passed to the CNCF with a likely result of having your certificate being revoked.

If this continues, we’ll move to lock the thread.

Couple things I have found useful. Using ‘-h’ with a command. Provides a great source for examples.

kubectl create -h

Another is using labels with logs. Especially nice if you have a bunch of pods using the same label

kubectl -n <namespace> logs -l label=somename

You can use this also

set expandtab
set tabstop=2
set shiftwidth=2
set autoindent
set smartindent
set bg=dark
set nowrap
set paste