Kubens. DIY with FZF

yamaha

In my work daily routine, I often need to switch between namespaces(less frequently contexts) in kubernetes and I used to use kubectx/kubens tools. Recently I started using FZF, mostly as a file finder and for fuzzy search in command line history.

I was wonder if I can apply FZF somewhere else. I tried to make my own kubens. What requirements do I have?

  • show all namespaces for the current context
  • select with fuzzy search
  • switch to selected
  • highlight current namespace (optional)

For intermediate scripts I use fish shell, a final script I show in fish shell and bash/zsh.

Show namespaces

Default kubectl command:

1
kubectl get namespace

To select namespace we pipe previous command with FZF:

1
kubectl get namespace | fzf

with headers

We have to get rid of headers and choose only namespace name column:

1
kubectl get namespace --no-headers | fzf | awk '{ print $1}'

no headers

Swith to selected

1
2
3
kubectl config set-context --current \
	--namespace=(kubectl get namespace \
	--no-headers | fzf | awk '{ print $1}')

bash/zsh:

1
2
3
kubectl config set-context --current \ 
	--namespace=$(kubectl get namespace \
	--no-headers | fzf | awk '{ print $1}') 

asciicast

Conclusion

We can add it to fish functions and invoke by name(knmps).

Add knmsp.fish to ~/.config/fish/functions/knmsp.fish

1
2
3
4
5
function knmsp -d "run vim with fzf"
  kubectl config set-context --current \ 
  	--namespace=(kubectl get namespace \
  	--no-headers | fzf | awk '{ print $1}')
end