☸️ Kubernetes: A Pragmatic Kubectl Aliases Collection
Tags: kubernetes, kubectl, tutorial, devops
Published: 2024-01-06 15:16:24

---
title: '☸️ Kubernetes: A Pragmatic Kubectl Aliases Collection'
tags:
  - kubernetes
  - kubectl
  - tutorial
  - devops
license: public-domain
cover_image: 'https://raw.githubusercontent.com/bcouetil/articles/main/images/kubernetes/boat/tools-1.jpg'
published: true
id: 1576526
date: '2024-01-06T15:16:24Z'
---

<!--
watch "kubectl get event --all-namespaces --sort-by='.metadata.managedFields[0].time' | tail -10"

-->

<!-- TOC start (generated with https://github.com/derlin/bitdowntoc) -->

- [Initial thoughts](#initial-thoughts)
- [Prerequisites](#prerequisites)
- [The alias list](#the-alias-list)
- [Use cases explained](#use-cases-explained)
  - [1. Write basic commands faster](#1-write-basic-commands-faster)
  - [2. Get sorted and filtered events](#2-get-sorted-and-filtered-events)
  - [3. Display every resources (really)](#3-display-every-resources-really)
  - [4. Display nodes resources requests and limits](#4-display-nodes-resources-requests-and-limits)
  - [5. Start a swiss-army-knife debug pod](#5-start-a-swissarmyknife-debug-pod)
  - [6. Get pod's containers list](#6-get-pods-containers-list)
  - [7. Ping a service](#7-ping-a-service)
  - [8. Get a runnable manifest of an deployed resource](#8-get-a-runnable-manifest-of-an-deployed-resource)
  - [9. Delete failed (and evicted) pods](#9-delete-failed-and-evicted-pods)
- [Wrapping up](#wrapping-up)
- [Further reading](#further-reading)

<!-- TOC end -->

# 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:

- [Kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl)
- [Krew plugins manager](https://krew.sigs.k8s.io/docs/user-guide/setup/install/)
- [Kubectl-neat Krew plugin](https://github.com/itaysk/kubectl-neat)
- a `~/.kube` folder

# The alias list

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

```shell
# 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'
```

![man repairing a blue ship, (wrench), ((repairman)), ((tools)), (blue ship)](https://raw.githubusercontent.com/bcouetil/articles/main/images/kubernetes/boat/tools-2.jpg)

# 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](https://github.com/ahmetb/kubectl-aliases) contains a script that generates hundreds of basic aliases, included in the above list.

Some of the 800 generated aliases are:

```shell
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'
...
```

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

```shell
$> 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
```

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:

```shell
$> 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
```

## 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.

```shell
$> 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
```

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

```shell
$> 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
```

## 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.

```shell
$> 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%)
```

![man repairing a blue ship, (wrench), ((repairman)), ((tools)), (blue ship)](https://raw.githubusercontent.com/bcouetil/articles/main/images/kubernetes/boat/tools-3.jpg)

## 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:

```shell
$> 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
```

## 7. Ping a service

Testing the availability of a Kubernetes service can be challenging. The `kping` alias uses the [HTTP Ping Docker image](https://github.com/BretFisher/httping-docker) to ping a service and check its availability:

```shell
$> 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
```

## 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](https://github.com/itaysk/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)](https://raw.githubusercontent.com/bcouetil/articles/main/images/kubernetes/boat/tools-4.jpg)

_Illustrations generated locally by Automatic1111 using MajicMixFantasy model_

# Further reading

{% embed https://dev.to/zenika/why-managed-kubernetes-is-a-viable-solution-for-even-modest-but-actively-developed-applications-357g %}

{% embed https://dev.to/zenika/kubernetes-from-your-docker-compose-file-to-a-cluster-with-kompose-1gn0 %}

{% embed https://dev.to/zenika/web-application-on-kubernetes-a-tutorial-to-observability-with-the-elastic-stack-2p8a %}

{% embed https://dev.to/zenika/kubernetes-nginx-ingress-controller-10-complementary-configurations-for-web-applications-ken %}

{% embed https://dev.to/zenika/kubernetes-awesome-maintained-links-you-will-keep-using-next-year-48o8 %}

{% embed https://dev.to/zenika/managed-kubernetes-our-dev-is-on-aws-our-prod-is-on-ovh-3nbf %}

{% embed https://dev.to/zenika/how-to-deploy-a-secured-ovh-managed-kubernetes-cluster-using-terraform-in-2023-17o7 %}

{% embed https://dev.to/zenika/how-to-deploy-a-cost-efficient-awseks-kubernetes-cluster-using-terraform-in-2023-3903 %}

{% embed https://dev.to/zenika/eks-10-tips-to-reduce-the-bill-up-to-90-on-aws-managed-kubernetes-clusters-epe %}

_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._