Kubectl Life Saver

Kubectl shortcut aliases and a interactive command builder.

GitHub Link.

Kubectl Shortcut Aliases Generator

A simple script generates useful aliases.

Usage

Kubectl shortcuts general rule:

k[n|a]<command><resource> [other-options]

k means kubectl, n means -n $NS, a means --all-namespaces. Set NS=xx before use kn aliases. Check namespace by ns or it’s equivalent echo $NS.

Examples:

kgn # kubectl get nodes
kgn -o wide # kubectl get nodes -o wide

NS=kube-system
kngp # kubectl -n $NS get pods
kngp --watch # kubectl -n $NS get pods --watch
knl podname # kubectl -n $NS logs podname
knx podname bash # kubectl -n $NS exec -it podname bash

The script may generate some invalid aliases or override some existed commands, use it at your own risk.

If you don’t want to use variable NS, case-sensitive search $NS and replace it.

All commands

You can add/edit/remove command aliases in the array _K8S_COMMAND_LIST with format <shortcut>/<command>.

  • g: get
  • d: describe
  • e: edit
  • r: delete
Special commands
  • x: exec -it, the only alias are kx and knx
  • l: logs, the only alias are kl and knl

All resources

Resources store in array _K8S_RESOURCE_LIST with same rule like commands.

  • n: Nodes
  • ns: Namespaces
  • l: LimitRanges
  • lr: LimitRanges
  • crb: ClusterRoleBindings
  • rb: RoleBindings
  • cr: ClusterRoles
  • r: Roles
  • ds: DaemonSets
  • d: Deployments
  • rs: ReplicaSets
  • ss: StatefulSets
  • rc: ReplicationControllers
  • p: Pods
  • j: Jobs
  • cj: Cronjob
  • pvc: PersistentVolumeClaims
  • pv: PersistentVolumes
  • q: ResourceQuotas
  • svc: Services
  • c: ConfigMaps
  • cm: ConfigMaps
  • i: Ingresses
  • e: Events
  • s: Secrets
  • sa: ServiceAccounts
  • sc: StorageClasses
  • np: NetworkPolicies

Script

Add this script to your .rc file (such as .bashrc or .zshrc):

Expand code
# kubectl completion
if [[ ! -f $HOME/.k8s_completion.sh ]]; then
  kubectl completion zsh > $HOME/.k8s_completion.sh
fi
source $HOME/.k8s_completion.sh

# Generate kubectl shortcut aliases
## k[n|a]<command><resource> [other-options]
# Usage:
# kubectl -n kube-system get pod => NS=kube-system; kngp
## [n|a] Note that not all commands can combine with --all-namespaces
### n as -n $NS
### a as --all-namespaces
## Command List
### l logs
### x exec -it
_K8S_COMMAND_LIST=(
  'g/get'
  'd/describe'
  'e/edit'
  'r/delete'
)
_K8S_RESOURCE_LIST=(
## Cluster Resources List
  'n/Nodes'
  'ns/Namespaces'
  'l/LimitRanges'
## RBAC Resources List
  'crb/ClusterRoleBindings'
  'rb/RoleBindings'
  'cr/ClusterRoles'
  'r/Roles'
## App Related Resources List
  'ds/DaemonSets'
  'd/Deployments'
  'rs/ReplicaSets'
  'ss/StatefulSets'
  'rc/ReplicationControllers'
  'p/Pods'
  'j/Jobs'
  'cj/Cronjob'
  'pvc/PersistentVolumeClaims'
  'pv/PersistentVolumes'
  'q/ResourceQuotas'
  'svc/Services'
  'c/ConfigMaps'
  'i/Ingresses'
  'e/Events'
  's/Secrets'
  'sa/ServiceAccounts'
  'sc/StorageClasses'
  'np/NetworkPolicies'
)
__generate_k8s_aliases() {
  local OUTPUT=${1:-"$HOME/.k8s_aliases.sh"}
  cat << 'EOF' >> $OUTPUT
export NS=default
alias ns='echo $NS'
alias k='kubectl'
alias kn='kubectl -n $NS'
alias kg='kubectl get'
alias kng='kubectl get -n $NS'
alias ke='kubectl edit'
alias kne='kubectl edit -n $NS'
alias kd='kubectl describe'
alias knd='kubectl describe -n $NS'
alias kr='kubectl delete'
alias knr='kubectl delete -n $NS'

# exec and logs doesn't need resource
alias kx='kubectl exec -it'
alias kl='kubectl logs'
alias knx='kubectl -n $NS exec -it'
alias knl='kubectl -n $NS logs'

EOF
  for command in "${_K8S_COMMAND_LIST[@]}"; do
    echo "# Command $command" >> $OUTPUT
    for resource in "${_K8S_RESOURCE_LIST[@]}"; do
      echo "## Resource $resource" >> $OUTPUT
      cmd_shortcut=$(echo "$command" | awk -F '/' '{print $1}')
      rs_shortcut=$(echo "$resource" | awk -F '/' '{print $1}')
      cmd=$(echo "$command" | awk -F '/' '{print $2}')
      rs=$(echo "$resource" | awk -F '/' '{print $2}')
      echo "alias k${cmd_shortcut}${rs_shortcut}='kubectl $cmd $rs'" >> $OUTPUT
      echo "alias kn${cmd_shortcut}${rs_shortcut}='kubectl -n \$NS $cmd $rs'" >> $OUTPUT
      echo "alias ka${cmd_shortcut}${rs_shortcut}='kubectl $cmd --all-namespaces $rs'" >> $OUTPUT
      echo "" >> $OUTPUT
    done
  done
}
if [[ ! -f "$HOME/.k8s_aliases.sh" ]]; then
  __generate_k8s_aliases $HOME/.k8s_aliases.sh
fi
source $HOME/.k8s_aliases.sh

Interactive command builder using peco

kp means kubectl-peco, it provides a interactive command builder using peco, you need install peco first.

Usage

kp will ask you four information, namespace, resource, name, and command.

lkp will display last-kp command.

rkp will re-run last kp command, and parameter can be 1~3. rkp N will provide first N parameters in last executed kp command.

Last executed info stored in folder $HOME/.kp.

Example

kp # run kp without parameters, will ask you 4 params
kp kube-system pod # provide N parameters will skip first N ask process
rkp 2 # In this situation, it equals to `kp kube-system pod`
rkp 1 # Equals to `kp kube-system`
lkp # Display last executed command

Script

Expand code
kp() {
  ns=$1
  rs=$2
  name=$3
  cmd=$4

  __backup_kp_cmd() {
    mkdir -p $HOME/.kp
    echo $ns > $HOME/.kp/last_ns
    echo $rs > $HOME/.kp/last_rs
    echo $name > $HOME/.kp/last_name
    echo $cmd > $HOME/.kp/last_cmd
  }

  exit_kp() {
    echo "Aborted."
    __backup_kp_cmd
  }

  # Get Namespace
  if [[ -z $ns ]]; then
    ns=$(echo "all\n$(kubectl get ns)" | peco | awk '{print $1}')
  fi
  echo Namespace: $ns
  if [[ -z $ns ]]; then
    echo "Aborted." # don't call exit_kp while kp is exited at first argument, keep last executed information
    return 0
  fi
  selected_ns="-n $ns"
  if [[ $ns = "all" ]]; then
    selected_ns="--all-namespaces"
  fi

  # Get Resource
  if [[ -z $rs ]]; then
    rs=$(echo "all\n$(kubectl api-resources)" | peco | awk '{print $1}')
  fi
  echo Resource: $rs
  if [[ -z $rs ]]; then
    exit_kp
    return 0
  fi
  
  # Get Name
  if [[ -z $name ]]; then
    data=$(kubectl get $rs -o wide ${=selected_ns} | peco)
    if [[ $ns = "all" ]]; then
      selected_ns="-n $(echo $data | awk '{print $1}')"
      name=$(echo $data | awk '{print $2}')
    else
      name=$(echo $data | awk '{print $1}')
    fi
  fi
  if [[ -z $name ]]; then
    exit_kp
    return 0
  fi

  echo Name: $name

  # Generate/Get commands
  cmd_list="describe\nedit\ndelete"
  if [[ $rs = "pods" ]] || [[ $rs = "all" && $name = "pod/"* ]] ; then
    cmd_list="${cmd_list}\nlogs\nexec"
    fi

    if [[ -z $cmd ]]; then
      cmd=$(echo "$cmd_list" | peco)
    fi
  echo Cmd: $cmd

    # Execute
  total_cmd="NOT_EXECUTED"
  if [[ ! -z $cmd ]]; then
    set -ex
    if [[ $cmd = "logs" ]]; then # logs doesn't need rs
      total_cmd="kubectl $cmd ${=selected_ns} $name"
    elif [[ $cmd = "exec" ]]; then # exec need -it and bash
      total_cmd="kubectl $cmd -it ${=selected_ns} $name bash"
    elif [[ $rs = "all" ]]; then # name contains resource type if rs=all
      total_cmd="kubectl $cmd ${=selected_ns} $name"
    else
      total_cmd="kubectl $cmd ${=selected_ns} $rs $name"
    fi
    set +ex
    else
      exit_kp
      return 0
    fi
    echo $total_cmd > $HOME/.kp/last_exec
    eval $total_cmd
    __backup_kp_cmd
}

lkp(){
    cat $HOME/.kp/last_exec
}

rkp(){
  revert_num=$1
  if [[ -z $revert_num ]]; then
    eval $(lkp)
  elif [[ $revert_num = "1" ]]; then
    kp $(cat $HOME/.kp/last_ns)
  elif [[ $revert_num = "2" ]]; then
    kp $(cat $HOME/.kp/last_ns) $(cat $HOME/.kp/last_rs)
  elif [[ $revert_num = "3" ]]; then
    kp $(cat $HOME/.kp/last_ns) $(cat $HOME/.kp/last_rs) $(cat $HOME/.kp/last_name)
  fi
}

Interactive exec/logs command

This two functions let you exec/logs pod without copy/paste, using peco.

Example:

iknx # default cmd is `bash`
iknx sh # args is okay
iknx cat /etc/hosts # more args is okay

iknl
iknl -f # args is okay

Script

Expand code
alias first='awk "{print \$1}"' # This alias existed in another post
iknx() { # inetractive knx
  local CMD=${1:-bash}
  local LEN=${#@}
  local ARGS=""
  if (( LEN > 1 )); then
    shift
    ARGS="$@"
  fi
  local POD=$(kngp | peco | first)
  if [[ -z $POD ]]; then
    echo "Aborted"
    return
  fi
  knx $POD ${=ARGS} $CMD
}
 
iknl () { # interactive knl
  local POD=$(kngp | peco | first)
  if [[ -z $POD ]]; then
    echo "Aborted"
    return
  fi
  knl $POD $@
}

Enjoy!