Skip to content

Instantly share code, notes, and snippets.

@vrischmann
Created May 23, 2019 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrischmann/5b93db231cb8563190959a57239269d5 to your computer and use it in GitHub Desktop.
Save vrischmann/5b93db231cb8563190959a57239269d5 to your computer and use it in GitHub Desktop.
script for fish to switch kubernetes contexts and namespaces with support for auto completion

installation

  • Copy kctx.fish to $HOME/.config/fish/functions
  • Copy kctx_completions.fish to $HOME/.config/fish/completions
function kctx -d "set context"
if test (count $argv) -lt 1
printf "Usage: kctx <command>\n"
return 1
end
set -l command $argv[1]
if test "$command" = "down"
__devenv_compose_down ; or return 1
return 0
end
switch "$command"
case set
set -l context $argv[2]
kubectl config use-context $context
case ns
set -l namespace $argv[2]
kubectl config set-context --current --namespace=$namespace
end
end
function __kctx_is_file_ok -d "Check if a file is not too old"
set -l file $argv[1]
if test -e $file
set -l last_change_ts (stat -c "%Y" $file)
set -l now_ts (date "+%s")
set -l duration (math $now_ts - $last_change_ts)
# 20 minutes = 60*20
if test $duration -lt 1200
return 0
end
end
return 1
end
function __kctx_get_contexts -d "Get all contexts"
set -l kctx_dir $HOME/.local/share/fish/kctx
mkdir -p $kctx_dir
set -l file $kctx_dir/all_contexts
if __kctx_is_file_ok $file
cat $file
return 0
end
rm -f $file
for context in (kubectl config get-contexts -o name)
printf "$context\tuse $context\n" >> $file
end
cat $file
end
function __kctx_get_namespaces -d "Get all namespaces for the current context"
set -l kctx_dir $HOME/.local/share/fish/kctx
mkdir -p $kctx_dir
set -l context (kubectl config current-context)
set -l file $kctx_dir/(string replace '/' '_' $context)
if __kctx_is_file_ok $file
cat $file
return 0
end
rm -f $file
for namespace in (kubectl get namespaces -o name | cut -d '/' -f2)
printf "$namespace\tuse $namespace\n" >> $file
end
cat $file
end
function __kctx_complete
complete -x -c kctx -n "__fish_use_subcommand" -a set -d "Set the Kubernetes context"
complete -x -c kctx -n "__fish_use_subcommand" -a ns -d "Set the Kubernetes namespace"
complete -x -c kctx -n "__fish_seen_subcommand_from set" -a "(__kctx_get_contexts)" -d "Switch Kubernetes context"
complete -x -c kctx -n "__fish_seen_subcommand_from ns" -a "(__kctx_get_namespaces)" -d "Switch Kubernetes namespace"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment