Skip to content

Instantly share code, notes, and snippets.

@bitti
Last active June 20, 2023 10:26
Show Gist options
  • Save bitti/183771a7308b030d933dbe4ea9c5cc9f to your computer and use it in GitHub Desktop.
Save bitti/183771a7308b030d933dbe4ea9c5cc9f to your computer and use it in GitHub Desktop.
Set a current kubeconfig context only for the current shell session
bash_setup() {
cat <<SETUP
alias kctx='. $(readlink -f "$0")'
__kctx () { mapfile -t COMPREPLY < <(compgen -W "\$(kubectl config get-contexts -o name) --help --unset" -- "\${COMP_WORDS[1]}"); }
complete -F __kctx kctx
SETUP
}
usage() {
cat <<EOF
usage: kctx [option] context
-h, --help show this message
-u, --unset back to global context
EOF
}
set_context_env() {
local -r context=$1
[[ -z $context ]] && { usage >&2; return 1; }
kubectl config get-contexts "$context" >/dev/null || return
cache=${XDG_CACHE_HOME:-$HOME/.cache}/kctx
mkdir -p "$cache"
export KUBECONFIG
: "${KUBECONFIG:=$HOME/.kube/config}"
context_config="$cache/${context}.yaml"
if [[ ! -f $context_config ]]
then
cat >"$context_config" <<CONF
apiVersion: v1
kind: Config
current-context: $context
CONF
chmod -w "$context_config" # Prevent overwrites by kubectx etc.
fi
KUBECONFIG="$context_config:${KUBECONFIG/$cache\/*.yaml:}"
}
case $1 in
-h|--help)
usage
;;
--bash-config)
bash_setup
;;
-u|--unset)
KUBECONFIG="${KUBECONFIG/$cache\/*.yaml:}"
;;
*)
set_context_env "$1"
esac
@bitti
Copy link
Author

bitti commented Jun 13, 2022

Setup

The script needs to be sourced in order to be able to change the current shell environment. For this it's easiest to define a shell alias. An alias for bash is provided which you may add to your ~/.bashrc:

$ bash kctx.bash --bash-config >>~/.bashrc

Afterwards you should have a kctx alias available in a new bash session. Note: if you move the kctx.bash script to another path you need to regenerate the alias.

Usage

Call the kctx alias with a context name

$ kctx a-context

Switch back to global context with -u

$ kctx -u

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