⚡ Blazing fast kubectl completion ⚡

By on ・ completion kubectl à la vitesse de l'éclair ・

TL; DR

You can use cache_builder from kubectl-fzf to speed-up completion and use a systemd unit to start it on login.

The premise

At the time of the writing, my .kube/config has a dozen of clusters configured; some of them are on slow networks. Striking the tab key with kubectl can lead to veeerrrryyy slow completion and freeze the terminal till the completion functions finish.

The solution

A simple web search on kubectl cache led me to that project : https://github.com/bonnefoa/kubectl-fzf ; which uses fzf to search from a cache.

kubectl-fzf can be installed locally or on the target cluster. Since I’m dealing with plenty of ephemeral clusters I opted-in for the local approach.

The two twists I’m adding to the standard installation process documented here are:

1. Load kubectl-fzf as an oh-my-zsh plugin:

To do so just copy kubectl_fzf.plugin.zsh under ~/.oh-my-zsh/plugins/kubectl_fzf.

And replace the first line to put the cache in the home directory:

sed -i '1 s@export KUBECTL_FZF_CACHE@export KUBECTL_FZF_CACHE=$HOME/tmp/kubectl_fzf_cache@' ~/.oh-my-zsh/plugins/kubectl_fzf

2. Add a systemd service for the local user:

To help building the cache as soon as I log in.

To do so you can add the following config to : $HOME/.local/share/systemd/user/cache-builder.service

As you can see, systemd prefers Specifiers over environment variables like $HOME or $USER.

Now comes the time to enable our cache-builder service

systemctl --user enable cache-builder.service
systemctl --user restart cache-builder.service
systemctl --user status cache-builder.service

systemctl --user restart cache-builder is useful to force rebuilding the cache when you switch kubeconfig for example.

Conclusion

The cache_builder from kubectl-fzf, fzf itself & systemd are !

There is still plenty to tune in each of these modules like & non-exclusively :