Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@koenbollen
Last active August 13, 2020 10:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koenbollen/342c138b6a77d3de6869aad68c193617 to your computer and use it in GitHub Desktop.
Save koenbollen/342c138b6a77d3de6869aad68c193617 to your computer and use it in GitHub Desktop.
kns - Quick kubectl namespace switcher
#!/bin/bash
# kns lets you select a kubernetes namespace in seconds. Autocomplete,
# type-ahead, everything! (tested in bash and zsh)
kns() {
local current
local namespace
local selected
if [[ ! -x "$(which fzf 2>/dev/null)" ]]; then
echo "please install: github.com/junegunn/fzf" >&2
return 1
fi
current="$(kubectl config current-context)"
namespace="$(kubectl config get-contexts "$current" | awk "/$current/ {print \$5}")"
if [[ -z "$namespace" ]]; then
namespace="default"
fi
selected=$( (kubectl get namespaces -o name | sed "s-namespaces/--"; echo $namespace ) | fzf -0 -1 --tac --prompt "$current> ")
if [[ ! -z "$selected" ]]; then
kubectl config set-context "$current" "--namespace=$selected"
echo "Set to \"$selected\"."
fi
}
# I love this alias:
#alias k=kubectl
@4n3w
Copy link

4n3w commented Apr 13, 2017

This is great.

@niels-s
Copy link

niels-s commented Apr 20, 2017

For it to work with Kubectl 1.6 you will need to update this line https://gist.github.com/koenbollen/342c138b6a77d3de6869aad68c193617#file-kns-bash-L18 to

selected=$( (kubectl get namespaces -o name | sed "s-namespace/--"; echo $namespace ) | fzf -0 -1 --tac --prompt "$current> ")

Remove the s from namespaces when you sed 👍

@koenbollen
Copy link
Author

Thanks @niels-s!

@koenbollen
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment