Skip to main content

Kube Menu Selector

This is a continuation of the Kube project shell plugin I wrote. This allows you to select contexts and projects dynamically from a dmenu compatible launcher! In my example I am using Fuzzel by dnkl.

  1. Getting the current context.

    1
    
    kubectl config current-context

    You can issue the command kubecontext to interactively select one using fuzzel

    1
    
    kubecontext
  2. Getting the current project.

    1
    2
    3
    
    kubectl project
    Current project: default
    Usage: kubectl project <namespace>
  3. Getting the pods in the project

    1
    2
    
    kubectl get pods
    No resources found in default namespace.
  4. Switching project

    1
    2
    
    kubectl project test
    Set current project to test

    You can also issue the command kubeproject to interactively select one using fuzzel

    1
    
    kubeproject
  5. All subsequent commands inherit the project's namespace.

    1
    2
    3
    
    kubectl get pods
    NAME                              READY   STATUS    RESTARTS   AGE
    test-fddbfcd5c-kjmvk              1/1     Running   1          13m

The alias is simple as the following lines:

1
2
alias kubecontext='kubectl config use-context `\kubectl config get-contexts -oname | fuzzel -w 100 -d --log-level=none`'
alias kubeproject='kubectl project `\kubectl get ns -oname | sed "s/namespace\///g" | fuzzel -w 100 -d --log-level=none`'

The plugin that can be added to your shell init. It also is using kubecolor to output in pretty colors! If you don't have kubecolor installed, just replace kubecolor with kubectl below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Kubectl project plugin
function _kcl() {
  # lazy-load kube completions (optional)
  if [ $commands[kubectl] ]; then
    source <(command kubectl completion zsh)
  fi

  if [[ -z "$1" && -z "$2" ]]; then
    command kubecolor -n $KUBESPACE "$@"
    return 0
  fi
  if [[ ! -z "$1" && "$1" == "project" && -z "$2" ]]; then
      printf 'Current project: \033[31m%s\n' $KUBESPACE
      printf '\033[0m'
      printf 'Usage: kubectl project \033[34m<namespace>\n'

      return 1
  fi
  if [[ ! -z "$1"  && "$1" == "project" && ! -z $2 ]]; then
    export KUBESPACE="$2"
    printf 'Set current project: \033[31m%s\n' $KUBESPACE
    printf '\033[0m'
    return 0
  else
    command kubecolor -n $KUBESPACE "$@"
    return 0
  fi
}
alias kubectl='_kcl'

You can follow along in my dotfiles Here!