My Bash Functions for kubectl

How to Configure

Just add them to the ~/.bashrc or ~/.bash_profile


Adding a new kubeconfig to existing config

This function is for adding a new kubeconfig to existing default config, ~/.kube/config

kubeadd (){ 
  cp ~/.kube/config ~/.kube/config.$(date +%F) 
  KUBECONFIG=~/.kube/config:$1 kubectl config view --flatten > /tmp/config 
  mv /tmp/config ~/.kube/config 
  chmod 600 ~/.kube/config 
} 

Usage

$ kubeadd cluster1.conf

Setting kubeconfig for each shell

Normally, people uses kubectl config use-context context_name to change the cluster, and that cluster will be the default for all Shell environments. However, we need to access multiple clusters in different shell sessions concurrently. This function can help to achieve that.

kubeswitch(){ 
  unset KUBECONFIG
  mkdir -p ${HOME}/.kube/contexts
  select context in $(kubectl config get-contexts -o name); do 
    kubectl config use-context $context &> /dev/null 
    kubectl config view --minify --context $context --flatten > ${HOME}/.kube/contexts/$context.conf 
    echo "export KUBECONFIG=${HOME}/.kube/contexts/$context.conf" 
    chmod 600 ${HOME}/.kube/contexts/$context.conf 
    break 
  done 
} 

alias kcs="source <(kubeswitch)" 

Usage

Running kcs alias command will show the cluster list from your ~/.kube/config and you just need to type in the number of the cluster that you want to use.

$ kcs
1) aks-cluster1
2) aks-cluster2
3) eks-cluster1
4) eks-cluster1
5) prod-cluster1
#?