Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use autocompletion for kubectl in zsh?

Tags:

I daily find myself doing...

$ kubectl --context=foo get pods   < copy text manually > $ kubectl --context=foo logs dep1-12345678-10101 

I would like to cycle through matching resources with

$ kubectl --context=foo logs dep1<TAB> 

but this doesn't seem to do anything with my stock setup. Any ideas?

osx 10.12.3 kubectl v1.4.5 zsh zsh 5.2 (x86_64-apple-darwin16.0)

like image 748
Plato Avatar asked Feb 21 '17 00:02

Plato


People also ask

How do I use autocomplete in zsh?

zsh-autocomplete adds real-time type-ahead autocompletion to Zsh. Find as you type, then press Tab to insert the top completion, Shift Tab to insert the bottom one, or ↓ / PgDn to select another completion.


2 Answers

Both bash and zsh supports scripts that completes printed command when you press <TAB>. The feature is called Programmable completion, and you can find more details about that here: zsh completion.

Fortunately, you don't need to write your own script - kubectl provides it for zsh > 5.2. Try running this command: source <(kubectl completion zsh).

Another option is to use this tool: https://github.com/mkokho/kubemrr (disclaimer: I'm the author). The reason it exists is because standard completion script is too slow - it might take seconds before Kubernetes cluster replies will all pod names. But kubemrr keeps the names locally, so the response comes back almost immediately.

like image 150
mkokho Avatar answered Sep 28 '22 00:09

mkokho


I add this function to my $HOME/.zshrc.

It will lazy load complete function of kubectl

kubectl () {     command kubectl $*     if [[ -z $KUBECTL_COMPLETE ]]     then         source <(command kubectl completion zsh)         KUBECTL_COMPLETE=1      fi } 

The oneline version:

(( ${+commands[kubectl]} )) && alias kubectl='test -z $C_KUBE && C_KUBE=1 && source <(command kubectl completion zsh); command kubectl' 
like image 31
wweir Avatar answered Sep 28 '22 02:09

wweir