Skip to content

Instantly share code, notes, and snippets.

@ffledgling
Last active February 27, 2019 11:55
Show Gist options
  • Save ffledgling/3258ea3f9ac43eedd309912dd02d3797 to your computer and use it in GitHub Desktop.
Save ffledgling/3258ea3f9ac43eedd309912dd02d3797 to your computer and use it in GitHub Desktop.
Dead simple PS1 prompt add-on for bash to display the current kubernetes namespace and context
#!/bin/bash
# Simple prompt addon to display kubernetes ns and cluster context
# To use, add the following in your .bashrc:
# ```
# source $PATH_TO_FILE/kube-prompt.sh
# KUBE_PROMPT_COLORS=y
# PS1='{$(__kube_ps1)}'$PS1
# ```
__kube_ps1_getns() {
local cur_ctx="$1"
local ns="$(kubectl config view -o=jsonpath="{.contexts[?(@.name==\"${cur_ctx}\")].context.namespace}")"
ns="${ns:=default}"
printf '%s' "${ns}"
}
__kube_ps1() {
local red="$(tput setaf 9)"
local green="$(tput setaf 10)"
local white="$(tput setaf 7)"
local reset="$(tput sgr0)"
local kctx=$(kubectl config current-context)
local err=$?
if [[ $err -ne 0 ]];
then
echo '`kubectl config current-context` failed'
return ''
fi
local ns="$(__kube_ps1_getns ${kctx})"
local kctx_ps1_string_prefix="${ns}@"
local kctx_ps1_string_suffix="${kctx}"
if [[ -v KUBE_PROMPT_COLORS ]]
then
if ${is_admin}
then
kctx_ps1_string="${kctx_ps1_string_prefix}${red}${kctx_ps1_string_suffix}${reset}"
else
kctx_ps1_string="${kctx_ps1_string_prefix}${green}${kctx_ps1_string_suffix}${reset}"
fi
else
kctx_ps1_string="${kctx_ps1_string_prefix}${kctx_ps1_string_suffix}"
fi
printf '%s' "${kctx_ps1_string}"
}
## Uncomment for standalone testing
#__kube_ps1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment