Kubernetes tips: enable kubectl auto-completion on your machine

Hello friends,

Today I wanna share a quick tip on how to set up the auto-completion feature for kubectl in our local machine. It will help us type the command faster and also reduce typo mistakes.

Don’t know how to set up a Kubernetes cluster locally? Check out my post here: How to setup a single node Kubernetes cluster on local environment for testing purpose?

In case you’re using macOS and zsh.

The kubectl completion script for Zsh can be generated with the command kubectl completion zsh .

[email protected] ~ % vi ~/.zshrc
[email protected] ~ % cat ~/.zshrc
autoload -Uz compinit
source <(kubectl completion zsh)

Then exit the terminal and start it again, try the kubectl command and enjoy the auto-completion feature. For example, when I type the below command (1) and press the tab key, it will auto-complete the command like the (2) line.

(1) [email protected] ~ % kubectl get dep
(2) [email protected] ~ % kubectl get deployments.apps

Or the suggestions like the below case:

[email protected] ~ % kubectl get p

In case you use PowerShell on Windows.

Open your Powershell run the following command

kubectl completion powershell >> $PROFILE

Then restart your Powershell and enjoy the auto-completion feature.
In case you faced the below issue, make sure you have kubectl version >= 1.23.

PS C:\Users\trung> kubectl completion powershell >> $PROFILE
error: Unsupported shell type "powershell".
See 'kubectl completion -h' for help and examples

Happy learning,

Thanks for sharing this awesome k8s tips. :grin: :+1:

1 Like