← All Articles

Kubernetes and GCloud bash prompts

Khash SajadiKhash Sajadi
Oct 18th 17Updated Jul 6th 22

Kubernetes and GCloud bash prompts

It's no secret we are Kubernetes and GCloud fans at Cloud 66. We use Kubernetes for our own production environment and GCloud / GKE, Google Cloud's Kubernetes as a Service for many uses, including as a "playground" cluster for our developers and CI/CD destination for Cloud 66 Skycap.

While both Kubernetes and GCloud provide fine grained access control rights based on roles or G Suite groups, it is possible for an Ops person to have access to the production Kubernetes cluster as well as a non-production cluster. This, combined with the power of Kubernetes configuration files means they might just apply a configuration file to the wrong environment.

While this is no failsafe method for protecting your production environment against human errors, knowing which GCloud and/or Kubernetes context you are on in your bash prompt can only be helpful. I strongly suggest using other methods to protect against mistakenly working against a sensitive cluster / GCloud account as well. Just a disclaimer! (Obviously you can use Cloud 66 Skycap and Cloud 66 Maestro with full ACL and great UI if you wish!).

Now, on to the scripts. Here is how your bash prompt will look if you use the scripts:

Kubernetes Bash Prompt

And here is how you can do it:

Create file called ~/.kube-prompt.sh with this content and update your .profile as well to update the prompt.

#!/bin/bash

__parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/[\1]/'
}

__kube_ps1()
{
    # Get current context
    CONTEXT=$(cat ~/.kube/config | grep "current-context:" --color=NO | sed "s/current-context: //")

    if [-n "$CONTEXT"]; then
        if ["$CONTEXT" = "production"]; then
            echo -e "${BRIGHT}${WHITE}${RED_BG}${BLINK}${CONTEXT}${NORMAL}"
        else
            echo -e "${YELLOW}${CONTEXT}${NORMAL}"
        fi
    fi
}

__gcloud_ps1()
{
    CONTEXT=$(cat ~/.config/gcloud/active_config)

    if [-n "$CONTEXT"]; then
        if ["$CONTEXT" = "production"]; then
            echo -e "${BRIGHT}${WHITE}${RED_BG}${BLINK}${CONTEXT}${NORMAL}"
        else
            echo -e "${YELLOW}${CONTEXT}${NORMAL}"
        fi
    fi
}

Use Kubernetes and GCloud responsibly!


Try Cloud 66 for Free, No credit card required