Skip to content

Instantly share code, notes, and snippets.

@tanelmae
Last active November 1, 2019 14:16
Show Gist options
  • Save tanelmae/b0dc522ab3984f290b0b25766128f61a to your computer and use it in GitHub Desktop.
Save tanelmae/b0dc522ab3984f290b0b25766128f61a to your computer and use it in GitHub Desktop.
BASH function for managing k3d cluster contexts
k3ctx() {
local CLUSTER_NAME=${1}
# Show the current context/namespace
local CTX=$(kubectl config current-context)
local NS=$(kubectl config view -o jsonpath="{.contexts[?(@.name=='$CTX')].context.namespace}")
if [[ -z $NS ]]; then
NS="default"
fi
echo "Current ctx/ns: $CTX/$NS"
# Let the user pick k3d context if none were passed in
if [[ -z $CLUSTER_NAME ]]; then
local OPTIONS=$(find $HOME/.config/k3d/ -maxdepth 1 -mindepth 1 -type d -exec basename {} \;)
OPTIONS+=' EXIT'
echo "Switch to which context? (or EXIT)"
select opt in $OPTIONS; do
if [ "$opt" = "EXIT" ]; then
echo "Staying in the current context"
return 0
else
local CLUSTER_NAME=${opt}
fi
break
done
fi
local CONF=$(k3d get-kubeconfig --name=${CLUSTER_NAME} 2> /dev/null)
# Possible if context name was passed in
if [ -z "${CONF}" ]; then
local ALL_CLUSTERS=$(k3d list 2> /dev/null)
if [ -z "${ALL_CLUSTERS}" ]; then
echo "No k3d clusters found"
else
echo "Cluster ${CLUSTER_NAME} not found"
printf "Existing clusters: \n ${ALL_CLUSTERS}\n"
fi
return 1
fi
export KUBECONFIG="${HOME}/.kube/config:${CONF}"
kubectl config use-context ${CLUSTER_NAME} 2> /dev/null
# On the first time the context name is 'default'
# Will be renamed after the cluster name
if [ $? -eq 1 ]; then
kubectl config rename-context "default" ${CLUSTER_NAME}
kubectl config use-context ${CLUSTER_NAME}
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment