Tips and tricks

Namespace switching

The CoCalc OnPrem deployment is namespace-agnostic, but this documentation assumes it has been installed in the cocalc namespace and hence you find -n cocalc added to some kubectl/helm commands. If you issue these commands, you have to explicitly specify the namespace all the time.

However, it’s possible to switch the default namespace configuration of your current kubectl context by running:

kubectl config set-context --current --namespace=cocalc

This will allow you to run commands without the -n cocalc flag.

More general, here is a simple bash function, called ns, to either list all available namespaces, or it lets you select a namespace to switch to, by providing the start of the namespace’s name (it matches based on the beginning of the string):

ns() {
    NSs=$(kubectl get namespaces -o json | jq -r '.items[].metadata.name')
    if [[ -z "$1" ]]; then
        echo "Select one of these namespaces (first substring that matches is enough):"
        echo "$NSs"
        return
    fi
    for n in $NSs; do
        if [[ "$n" =~ ^.*$1.*$ ]]; then
            echo "switching to $n"
            kubectl config set-context --current --namespace=$n
            return
        fi
    done
    echo "NO MATCH FOR '$1'"
}

Note

Then use it like ns coc to switch to the cocalc namespace or ns def to go back to the default namespace.

Additionally, you can adjust your $PS1 prompt to show the context and current namespace. This gives you a visual indication of the current namespace and context, which is very helpful when working with multiple clusters and namespaces:

_context() {
    command kubectl config current-context
}

_namespace() {
    command kubectl config view --minify --output 'jsonpath={..namespace}'
}

export PS1='[`_context`/`_namespace`] \[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]> '

How to use this? Put all of the above into a file, let’s call it activate.sh, and then source it in your shell:

. activate.sh

Now you can use the ns function to switch namespaces and your prompt will show the current context and namespace.