Created
November 26, 2019 13:43
-
-
Save jamesmcdonald/f69d172047d7397bae9d4806ae040f11 to your computer and use it in GitHub Desktop.
nicer kn for your bashrc
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
# kn <context> [namespace] lets you quickly change kubectl's context and | |
# optionally namespace. Tab completion is supported for both. If you just want | |
# to change namespace in the same context, you can use context ".". | |
function kn() { | |
local context=$1 | |
local namespace=$2 | |
if [[ -z "$context" ]]; then | |
echo "usage: kn <context> [namespace]" >&2 | |
return 1 | |
fi | |
[[ "$context" = "." ]] && context=$(kubectl config current-context) | |
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) | |
[[ "$prev" = "." ]] && prev=$(kubectl config current-context) | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment