Last active
June 20, 2023 10:26
-
-
Save bitti/183771a7308b030d933dbe4ea9c5cc9f to your computer and use it in GitHub Desktop.
Set a current kubeconfig context only for the current shell session
This file contains hidden or 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
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 >>~/.bashrcAfterwards you should have a
kctxalias available in a new bash session. Note: if you move thekctx.bashscript to another path you need to regenerate the alias.Usage
Call the
kctxalias with a context name$ kctx a-contextSwitch back to global context with
-u$ kctx -u