DEV Community

Cover image for ☸️ Kubernetes: A Pragmatic Kubectl Aliases Collection
Benoit COUETIL 💫 for Zenika

Posted on • Updated on

☸️ Kubernetes: A Pragmatic Kubectl Aliases Collection

Initial thoughts

Managing Kubernetes clusters and performing administrative tasks can be complex and time-consuming. However, with the right set of kubectl aliases, you can streamline your Kubernetes administration and make your tasks more efficient. In this article, we will explore a collection of useful kubectl aliases that can help you perform common tasks faster and with greater ease. From retrieving resource information to troubleshooting pods and managing nodes, these aliases will become invaluable tools in your Kubernetes toolkit. So, let's dive in and discover the kubectl aliases you need to simplify your Kubernetes administration!

Prerequisites

Before you can start using these helpful kubectl aliases, make sure you have the following prerequisites on your workstation:

The alias list

Here is a list of useful kubectl aliases that you can add to your shell configuration:

# autocomplete kubectl & helm
source <(kubectl completion zsh)
source <(helm completion zsh)

alias k=kubectl

# when using below aliases, print kubectl command and then execute it
function kctl() { echo "+ kubectl $@" && command kubectl $@ }

# add aliases collection like 'kgpo' for 'kubectl get pods` from https://github.com/ahmetb/kubectl-aliases
[ ! -f ~/.kube/aliases.sh ] && curl -fsSL "https://raw.githubusercontent.com/ahmetb/kubectl-aliases/master/.kubectl_aliases" > ~/.kube/aliases.sh && sed -i -e 's/kubectl/kctl/g' ~/.kube/aliases.sh
source ~/.kube/aliases.sh

# set default namespace
alias kn='kctl config set-context --current --namespace'
# get events sorted by last timestamp
alias kgel='kctl get events --sort-by=.lastTimestamp'
# get events sorted by creation timestamp
alias kgec='kctl get events --sort-by=.metadata.creationTimestamp'
# get pod's descending events
function kger() { kctl get events --sort-by=.lastTimestamp --field-selector involvedObject.name="$@" }
# get 'real' all
alias kgworld='kctl get $(kubectl api-resources --verbs=list --namespaced -o name | paste -sd ",")'
# display all nodes resources request and limits
alias kgnr="k get nodes --no-headers | awk '{print \$1}' | xargs -I {} sh -c 'echo {} ; kubectl describe node {} | grep Allocated -A 5 | grep -ve Event -ve Allocated -ve percent -ve -- ; echo '"
# start a debug pod (including lots of troubleshooting tools)
alias kdebug="kctl -n default run debug-$USER --rm -it --tty --image leodotcloud/swiss-army-knife:v0.12 --image-pull-policy=IfNotPresent -- bash"
# get pod's containers list
function kgpc() { kctl get pod -o jsonpath="{.spec.containers[*].name}" "$@" && echo "" }
# ping a service, ex: 'kping whoami:8080'
alias kping='kctl run httping -it --image bretfisher/httping --image-pull-policy=IfNotPresent --rm=true --'
# get existing pod's yaml without forbidden fields, ex: 'kyaml pod whoami'
function kyaml() { kubectl get "$@" -o yaml | kubectl-neat }
# display and delete failed pods in current namespace
alias krmfailed='kctl delete pods --field-selector=status.phase=Failed'
Enter fullscreen mode Exit fullscreen mode

man repairing a blue ship, (wrench), ((repairman)), ((tools)), (blue ship)

Use cases explained

Let's dive into some of the use cases and explanations for these aliases.

1. Write basic commands faster

The kubectl-aliases Github repo contains a script that generates hundreds of basic aliases, included in the above list.

Some of the 800 generated aliases are:

alias k='kubectl'
alias kg='kubectl get'
alias kgpo='kubectl get pod'

alias ksysgpo='kubectl --namespace=kube-system get pod'

alias krm='kubectl delete'
alias krmf='kubectl delete -f'
alias krming='kubectl delete ingress'
alias krmingl='kubectl delete ingress -l'
alias krmingall='kubectl delete ingress --all-namespaces'

alias kgsvcoyaml='kubectl get service -o=yaml'
alias kgsvcwn='kubectl get service --watch --namespace'
alias kgsvcslwn='kubectl get service --show-labels --watch --namespace'

alias kgwf='kubectl get --watch -f'
...
Enter fullscreen mode Exit fullscreen mode

However, it can be challenging to recall what a command is for:

$> kgcmslwn main

# NAME                   DATA   AGE    LABELS
# kube-root-ca.crt       1      144d   <none>
# logstash-config        1      100d   app=logstash,chart=logstash,heritage=Helm,release=ls
# logstash-pipeline      1      100d   app=logstash,chart=logstash,heritage=Helm,release=ls
# ls-finance-config      1      61d    app=ls-finance,chart=logstash,heritage=Helm,release=ls-finance
# ls-finance-pipeline    1      61d    app=ls-finance,chart=logstash,heritage=Helm,release=ls-finance
Enter fullscreen mode Exit fullscreen mode

To address this, we added a function that displays the full command before executing it. This provides clarity and helps you understand what the command does:

$> kgcmslwn main
+ kubectl get configmap --show-labels --watch --namespace main

# NAME                   DATA   AGE    LABELS
# kube-root-ca.crt       1      144d   <none>
# logstash-config        1      100d   app=logstash,chart=logstash,heritage=Helm,release=ls
# logstash-pipeline      1      100d   app=logstash,chart=logstash,heritage=Helm,release=ls
# ls-finance-config      1      61d    app=ls-finance,chart=logstash,heritage=Helm,release=ls-finance
# ls-finance-pipeline    1      61d    app=ls-finance,chart=logstash,heritage=Helm,release=ls-finance
Enter fullscreen mode Exit fullscreen mode

2. Get sorted and filtered events

Sorting events in a Kubernetes cluster can be challenging. We added aliases to sort events by last seen date and creation timestamp.

$> kgel -A
+ kubectl get events --sort-by=.lastTimestamp -A

# NAMESPACE            LAST SEEN   TYPE      REASON                 OBJECT                                            MESSAGE
# illu-for-designers   22m         Warning   Unhealthy              pod/auth-server-67c944c549-7qmmj                  Startup probe failed: Get "http://10.0.8.148:8080/auth-server/actuator/health/liveness": dial tcp 10.0.8.148:8080: connect: connection refused
# fix-analytics-env    3m23s       Warning   BackOff                pod/marketplace-test-6b9955d469-9zq2n             Back-off restarting failed container
# elk                  2m44s       Normal    WaitForFirstConsumer   persistentvolumeclaim/ls-logstash-ls-logstash-0   waiting for first consumer to be created before binding
# illu-for-designers   2m4s        Warning   BackOff                pod/backoffice-5c88b6d84-mv88z                    Back-off restarting failed container

$> kgec -A
+ kubectl get events --sort-by=.metadata.creationTimestamp -A

# NAMESPACE            LAST SEEN   TYPE      REASON                 OBJECT                                            MESSAGE
# elk                  4m4s        Normal    WaitForFirstConsumer   persistentvolumeclaim/ls-logstash-ls-logstash-0   waiting for first consumer to be created before binding
# fix-analytics-env    4m43s       Warning   BackOff                pod/marketplace-test-6b9955d469-9zq2n             Back-off restarting failed container
# illu-for-designers   3m20s       Warning   BackOff                pod/bff-66b6b7bc4b-l8s82                          Back-off restarting failed container
# illu-for-designers   23m         Warning   Unhealthy              pod/auth-server-67c944c549-7qmmj                  Startup probe failed: Get "http://10.0.8.148:8080/auth-server/actuator/health/liveness": dial tcp 10.0.8.148:8080: connect: connection refused
Enter fullscreen mode Exit fullscreen mode

Additionally, you can filter events for a specific resource using the kger alias:

$> kger auth-server-67c944c549-7qmmj
+ kubectl get events --sort-by=.lastTimestamp --field-selector involvedObject.name=auth-server-67c944c549-7qmmj

# LAST SEEN   TYPE      REASON      OBJECT                             MESSAGE
# 26m         Warning   Unhealthy   pod/auth-server-67c944c549-7qmmj   Startup probe failed: Get "http://10.0.8.148:8080/auth-server/actuator/health/liveness": dial tcp 10.0.8.148:8080: connect: connection refused
# 99s         Warning   BackOff     pod/auth-server-67c944c549-7qmmj   Back-off restarting failed container
Enter fullscreen mode Exit fullscreen mode

3. Display every resources (really)

The kubectl get all command does not actually display all resources. To overcome this limitation, we created the kgworld alias. This alias retrieves all resources using kubectl get $(kubectl api-resources --verbs=list --namespaced -o name | paste -sd ",").

4. Display nodes resources requests and limits

To view the resource requests and limits for nodes in your cluster, you can use the kgnr alias. This alias provides a clear overview of CPU and memory allocations for each node.

$> kgnr

# ip-10-0-17-119.eu-west-1.compute.internal
#   Resource                    Requests       Limits
#   cpu                         935m (23%)     6300m (160%)
#   memory                      11952Mi (80%)  10948Mi (73%)
# ip-10-0-31-235.eu-west-1.compute.internal
#   Resource                    Requests       Limits
#   cpu                         1415m (36%)    8900m (227%)
#   memory                      14259Mi (96%)  15326Mi (103%)
Enter fullscreen mode Exit fullscreen mode

man repairing a blue ship, (wrench), ((repairman)), ((tools)), (blue ship)

5. Start a swiss-army-knife debug pod

Debugging pods can be challenging when they lack the necessary troubleshooting tools.

The kdebug alias solves this problem by starting a debug pod with all the essential tools pre-installed: arping, arptables, bridge-utils, ca-certificates, conntrack, curl, docker, dnsutils, ethtool, iperf, iperf3, iproute2, ipsec-tools, ipset, iptables, iputils-ping, jq, kmod, kubectl, ldap-utils, less, libpcap-dev, man, manpages-posix, mtr, net-tools, netcat, netcat-openbsd, openssl, openssh-client, psmisc, socat, tcpdump, telnet, tmux, traceroute, tcptraceroute, tree, ngrep, vim, wget, yq.

6. Get pod's containers list

To retrieve a list of containers within a pod, you can use the kgpc alias. This is useful when you need to work with specific containers within a pod:

$> kgpc ebs-csi-controller-b77c4f786-dxv4g -n kube-system
+ kubectl get pod -o jsonpath={.spec.containers[*].name} ebs-csi-controller-b77c4f786-dxv4g -n kube-system

# ebs-plugin csi-provisioner csi-attacher csi-snapshotter csi-resizer liveness-probe
Enter fullscreen mode Exit fullscreen mode

7. Ping a service

Testing the availability of a Kubernetes service can be challenging. The kping alias uses the HTTP Ping Docker image to ping a service and check its availability:

$> kgsvc
+ kubectl get service

# NAME                   TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
# api                    ClusterIP   172.20.251.151   <none>        80/TCP     12d
# auth-server            ClusterIP   172.20.241.45    <none>        80/TCP     144d
# backend                ClusterIP   172.20.89.116    <none>        80/TCP     144d
# webapp                 ClusterIP   172.20.68.65     <none>        80/TCP     144d

$> kping auth-server:80
+ kubectl run httping -it --image bretfisher/httping --image-pull-policy=IfNotPresent --rm=true -- auth-server:80

# If you don't see a command prompt, try pressing enter.
# connected to 172.20.241.45:80 (159 bytes), seq=1 time=  4.63 ms
# connected to 172.20.241.45:80 (159 bytes), seq=2 time=  2.07 ms
# connected to 172.20.241.45:80 (159 bytes), seq=3 time=  1.90 ms
# connected to 172.20.241.45:80 (159 bytes), seq=4 time=  2.30 ms
Enter fullscreen mode Exit fullscreen mode

8. Get a runnable manifest of an deployed resource

When retrieving the YAML of a deployed resource using kubectl get pod -o=yaml, certain fields are unnecessary and can cause issues when redeploying the YAML. The kyaml alias solves this problem by providing a runnable manifest that excludes unnecessary fields.

It depends on kubectl-neat mentioned in pre-requisites.

9. Delete failed (and evicted) pods

Failed pods can clutter your cluster and affect performance. The krmfailed alias allows you to easily delete failed pods in the current namespace.

Wrapping up

These kubectl aliases provide a convenient way to streamline your Kubernetes administration tasks. By using these aliases, you can save time and effort when working with kubectl commands. Whether you need to retrieve specific information, troubleshoot pods, or manage resources, these aliases have got you covered.

So go ahead, give these a try, and enjoy a more efficient Kubernetes administration experience!

Some useful aliases are missing ? please advise in the comments 🤓

man repairing a blue ship, (wrench), ((repairman)), ((tools)), (blue ship)

Illustrations generated locally by Automatic1111 using MajicMixFantasy model

Further reading

This article was enhanced with the assistance of an AI language model to ensure clarity and accuracy in the content, as English is not my native language.

Top comments (0)