Last active
October 19, 2023 18:58
-
-
Save electron0zero/298a563f44296528b37d0d8e1647c79e to your computer and use it in GitHub Desktop.
Context and namesapce aware kubectl aliaes
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
#@IgnoreInspection BashAddShebang | |
# Setup: | |
# 1. source this script in your ~/.bashrc | |
# source "~/kubectl_aliases.sh" | |
# Usage: | |
# - use kctx to set context | |
# - use kns to set namespace | |
# - kjmp to jump to a set list of cluster and namespace pair from a local text file | |
# - now use kctl instead of kubectl and all the commands will have correct namespace and context passed | |
# - try other shorthand aliases for frequently used commands | |
# | |
# NOTE: used and tested with bash and zsh | |
# see more tips: https://suraj.dev/blog/my-k8s-kubectl-cheat-sheet | |
# === Bash functions | |
# get bash shell on pod | |
function k8s_get_bash() { | |
kctl exec -it $1 bash | |
} | |
# get current context for a session | |
function get_k8s_context() { | |
# if kubectl context is not set, set it to current-context" | |
if [[ -z "${K8S_CONTEXT}" ]]; then | |
current_ctx="$(kubectl config current-context)" | |
export K8S_CONTEXT=${current_ctx} | |
fi | |
echo ${K8S_CONTEXT} | |
} | |
# get current namespace for a session | |
function get_k8s_namespace() { | |
# if kubectl namespace is not set, set it to default | |
if [[ -z "${K8S_NAMESPACE}" ]]; then | |
export K8S_NAMESPACE="default" | |
fi | |
echo ${K8S_NAMESPACE} | |
} | |
# handle kns command | |
function k8s_namespace() { | |
# show current namespace if now is passed | |
if [[ "$1" = "--now" ]] || [[ "$1" = "-n" ]]; then | |
echo "$(get_k8s_namespace)" | |
return 0 | |
fi | |
# if no arg is passed Allow user to select namespace from all namespaces | |
if [[ -z "$1" ]]; then | |
echo "Current namespace: $(get_k8s_namespace)" | |
echo "Usage: kns - Switch namespace" | |
echo " kns [ -n | --now ] - Print current namespace" | |
echo "" | |
echo "Available namespaces in context: $(get_k8s_context)" | |
all_ns=$(kctl get ns -o custom-columns='name:metadata.name' --no-headers=true) | |
echo "Select number to switch namespace..." | |
select ns in $all_ns; do | |
# wait for input and break when we get it | |
break | |
done | |
export K8S_NAMESPACE=$ns | |
echo "$(get_k8s_namespace)" | |
fi | |
} | |
# handle kctx command | |
function k8s_context() { | |
# show current context if now is passed | |
if [[ "$1" = "--now" ]] || [[ "$1" = "-n" ]]; then | |
echo "$(get_k8s_context)" | |
return 0 | |
fi | |
# if no arg is passed Allow user to select context from available contexts | |
if [[ -z "$1" ]]; then | |
echo "Current context: $(get_k8s_context)" | |
echo "Usage: kctx - Switch context" | |
echo " kctx [ -n | --now ] - Print current context" | |
echo "" | |
echo "Available contexts, select number to switch context..." | |
all_ctx=$(kubectl config get-contexts -o name --no-headers=true) | |
select ctx in $all_ctx; do | |
# wait for input and break when we get it | |
break | |
done | |
# set selected context | |
export K8S_CONTEXT=$ctx | |
echo "$(get_k8s_context)" | |
fi | |
} | |
# kctl is bash function because we need to evaluate it on each execution | |
# to get correct value of context and namespace | |
function kctl() { | |
# "$@" to pass all args to kubectl, see: https://stackoverflow.com/a/4824637 | |
kubectl --context=$(get_k8s_context) --namespace=$(get_k8s_namespace) "$@" | |
} | |
# HACK: enable kubectl auto complete for kctl command. | |
# See: https://github.com/kubernetes/kubectl/issues/120#issuecomment-344137671 | |
if [ $BASH ] | |
then | |
source <( kubectl completion bash | sed 's/kubectl/kctl/g' ) | |
elif [ $ZSH_NAME ] | |
then | |
source <( kubectl completion zsh | sed 's/kubectl/kctl/g' ) | |
setopt sh_word_split | |
fi | |
# func is used to quicky set the most commanly used cluster and namespace pairs | |
# useful when you have tons of clusters and each clster have many namespaces. | |
# it avids the need to call kctx, and kns and make the selection | |
# kjmp_namespace_clusters.txt file is just a text file where each line is "<cluster><space><namespace> as per your kubeconfig. | |
kjmp() { | |
# Read the file containing namespace and cluster pairs | |
local file="/home/suraj/kjmp_namespace_clusters.txt" | |
# Check if the file exists | |
if [ ! -f "$file" ]; then | |
echo "File $file not found." | |
return 1 | |
fi | |
# Read the file and store pairs in an array | |
local pairs=() | |
while IFS= read -r line; do | |
pairs+=("$line") | |
done < "$file" | |
# Display the available pairs to the user | |
echo "Available namespace-cluster pairs:" | |
for ((i=0; i<${#pairs[@]}; i++)); do | |
# we add empty lines to align cluster names with index so it's easy select | |
# e.g. you have `cluster-1`, `cluster-3` in file, then just leave a empty line | |
# and now you always have cluster-3 at index 3 and can select by typing 3 | |
# skip empty lines | |
if [[ -n "${pairs[i]}" ]]; then | |
echo "[$i] ${pairs[i]}" | |
fi | |
done | |
echo "----------------------------------" | |
echo "Current session:" $(get_k8s_context) $(get_k8s_namespace) | |
echo "----------------------------------" | |
# Ask the user to select a pair | |
read -p "Select a pair (enter the number): " selection | |
# Check if the selection is valid | |
if ! [[ "$selection" =~ ^[0-9]+$ ]]; then | |
echo "Invalid selection. Please enter a valid number." | |
return 1 | |
fi | |
if ((selection < 0)) || ((selection >= ${#pairs[@]})); then | |
echo "Invalid selection. Please choose a valid number." | |
return 1 | |
fi | |
# Extract the selected pair | |
local selected_pair="${pairs[selection]}" | |
# Split the pair into context and namespace | |
IFS=" " read -r K8S_CONTEXT K8S_NAMESPACE <<< "$selected_pair" | |
# Export the environment variables in the current session | |
export K8S_CONTEXT | |
export K8S_NAMESPACE | |
# Print the selected environment variables | |
echo "----------------------------------" | |
echo "Setting K8S_CONTEXT: $K8S_CONTEXT" | |
echo "Setting K8S_NAMESPACE: $K8S_NAMESPACE" | |
echo "----------------------------------" | |
} | |
# === Aliases | |
# aliases for kctl config functions | |
alias kns="k8s_namespace" | |
alias kctx="k8s_context" | |
# alias for kubectl | |
alias kl='kctl logs' | |
alias kp='kctl get pods --sort-by=.metadata.creationTimestamp' | |
alias kpr='kctl get pod --sort-by=.metadata.creationTimestamp --field-selector status.phase=Running' | |
# kpe will list pods that are not running or completed aka failed/errored pods | |
alias kpe='kctl get pod --sort-by=.metadata.creationTimestamp --field-selector status.phase=Failed' | |
alias kdp='kctl delete po' | |
alias pod='kctl get pods | grep -i' | |
alias ktop='kctl top pod' | |
alias kssh='k8s_get_bash' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment