kubectl autocomplete with ZSH and aliases

19 Aug 2023 in TIL

This took me way too long to figure out.

How to make the k alias for kubectl autocomplete in zsh:

  1. Ensure that setopt COMPLETE_ALIASES is not set (I’m not sure why) TODO: CHECK THIS
  2. Define your alias alias k=kubectl
  3. Load the kubectl completions withsource <(kubectl completion zsh) 
  4. Run compdef k='kubectl' to associate the autocomplete for kubectl with k

Here’s a complete .zshrc that works for me:

autoload -Uz compinit
alias k=kubectl
source <(kubectl completion zsh)
compdef k='kubectl'

PS: Make sure that the aliases are set before calling compdef. That’s an hour of my time I’m never getting back.