Skip to content

Instantly share code, notes, and snippets.

@dragonde
Last active February 1, 2024 17:11
Show Gist options
  • Save dragonde/d911a2098d5befdf6640e09bd8ea591d to your computer and use it in GitHub Desktop.
Save dragonde/d911a2098d5befdf6640e09bd8ea591d to your computer and use it in GitHub Desktop.
kube ps1 switch color terminal

how can i switch the color of my terminal when i switch kubernetes context and kube-ps1 detect it?

Here's a step-by-step guide on how to achieve this:

Install kube-ps1: If you haven't already installed kube-ps1, you can do so from its GitHub repository: https://github.com/jonmosco/kube-ps1

Configure your shell to use kube-ps1: Add the following lines to your shell configuration file (.bashrc, .zshrc, etc.) to initialize kube-ps1:

source "/path/to/kube-ps1.sh" PROMPT='$(kube_ps1)'$PROMPT Replace "/path/to/kube-ps1.sh" with the actual path where kube-ps1 is located.

Modify kube-ps1 prompt: Customize the kube-ps1 prompt to change colors based on the current Kubernetes context. You can do this by modifying the kube-ps1 function in your .bashrc or .zshrc file. Here's an example of how you can do this for bash:

function kube_ps1() {

Get the current Kubernetes context

local ctx=$(kubectl config current-context)

Define colors

local red='[\033[0;31m]' local green='[\033[0;32m]' local blue='[\033[0;34m]' local reset='[\033[0m]'

Choose color based on context name

case "$ctx" in production-context) # Set color to red for production color=$red ;; staging-context) # Set color to blue for staging color=$blue ;; *) # Set color to green for other contexts color=$green ;; esac

Construct the kube-ps1 prompt with the chosen color

echo -n "${color}(k8s: ${ctx})${reset} " }

Update PS1 to include the kube_ps1 function

PS1='$(kube_ps1)'$PS1 For zsh, use %F{color} for setting colors and %f for resetting them.

Reload your shell configuration: After making changes to your shell configuration file, apply them by either restarting your terminal or sourcing the configuration file:

source ~/.bashrc # or source ~/.zshrc if you're using zsh

Switch Kubernetes contexts: Now, when you switch Kubernetes contexts using kubectl, your terminal prompt should change colors based on the context you are currently using.

Remember that you may need to adjust the script above to fit the specific syntax of your shell, and also replace the context names (production-context, staging-context, etc.) with the actual context names you use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment