Last active
October 23, 2019 13:10
-
-
Save jamesmcdonald/796a5149f3da4ae0371383404cc9bf6a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function kn() { | |
local context=$1 | |
shift | |
local namespace=$1 | |
shift | |
if [[ -z "$context" ]]; then | |
echo "usage: kn <context> [namespace]" >&2 | |
return 1 | |
fi | |
if ! kubectl config get-contexts $context >/dev/null 2>&1; then | |
echo "kn: context $context not found" >&2 | |
return 1 | |
fi | |
if [[ -n "$namespace" ]]; then | |
if ! kubectl --context="$context" get ns $namespace >/dev/null 2>&1; then | |
echo "kn: namespace $namespace not found in context $context" >&2 | |
return 1 | |
fi | |
kubectl config set-context $context --namespace $namespace | |
fi | |
if [[ $(kubectl config current-context) != $context ]]; then | |
kubectl config use-context $context | |
fi | |
} | |
function _kn() { | |
local cur prev opts | |
COMPREPLY=() | |
cur="${COMP_WORDS[COMP_CWORD]}" | |
prev="${COMP_WORDS[COMP_CWORD-1]}" | |
opts=$(kubectl config get-contexts -o name) | |
if kubectl config get-contexts -o name | grep -q "^$prev$" | |
then | |
opts=$(kubectl "--context=$prev" get namespaces -o go-template --template="{{range .items}}{{.metadata.name}} {{end}}") | |
fi | |
COMPREPLY=($(compgen -W "${opts}" -- ${cur})) | |
return 0 | |
} | |
complete -F _kn kn | |
alias k=kubectl | |
complete -F __start_kubectl k |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment