Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

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

Posted on • Edited 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 & helmsource <(kubectl completion zsh)source <(helm completion zsh)aliask=kubectl# when using below aliases, print kubectl command and then execute itfunctionkctl(){echo"+ kubectl$@"&&commandkubectl$@}# 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.shsource ~/.kube/aliases.sh# set default namespacealiaskn='kctl config set-context --current --namespace'# get events sorted by last timestampaliaskgel='kctl get events --sort-by=.lastTimestamp'# get events sorted by creation timestampaliaskgec='kctl get events --sort-by=.metadata.creationTimestamp'# get pod's descending eventsfunctionkger(){ kctl get events--sort-by=.lastTimestamp--field-selector involvedObject.name="$@"}# get 'real' allaliaskgworld='kctl get $(kubectl api-resources --verbs=list --namespaced -o name | paste -sd ",")'# display all nodes resources request and limitsaliaskgnr="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)aliaskdebug="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 listfunctionkgpc(){ kctl get pod-ojsonpath="{.spec.containers[*].name}""$@"&&echo""}# ping a service, ex: 'kping whoami:8080'aliaskping='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'functionkyaml(){ kubectl get"$@"-o yaml | kubectl-neat}# display and delete failed pods in current namespacealiaskrmfailed='kctl delete pods --field-selector=status.phase=Failed'
Enter fullscreen modeExit 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

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

Some of the 800 generated aliases are:

aliask='kubectl'aliaskg='kubectl get'aliaskgpo='kubectl get pod'aliasksysgpo='kubectl --namespace=kube-system get pod'aliaskrm='kubectl delete'aliaskrmf='kubectl delete -f'aliaskrming='kubectl delete ingress'aliaskrmingl='kubectl delete ingress -l'aliaskrmingall='kubectl delete ingress --all-namespaces'aliaskgsvcoyaml='kubectl get service -o=yaml'aliaskgsvcwn='kubectl get service --watch --namespace'aliaskgsvcslwn='kubectl get service --show-labels --watch --namespace'aliaskgwf='kubectl get --watch -f'...
Enter fullscreen modeExit 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 modeExit 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 modeExit 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 modeExit fullscreen mode

Additionally, you can filter events for a specific resource using thekger 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 modeExit fullscreen mode

3. Display every resources (really)

Thekubectl get all command does not actually display all resources. To overcome this limitation, we created thekgworld alias. This alias retrieves all resources usingkubectl 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 thekgnr 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 modeExit 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.

Thekdebug 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 thekgpc 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-ojsonpath={.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 modeExit fullscreen mode

7. Ping a service

Testing the availability of a Kubernetes service can be challenging. Thekping alias uses theHTTP 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 modeExit fullscreen mode

8. Get a runnable manifest of an deployed resource

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

It depends onkubectl-neat mentioned in pre-requisites.

9. Delete failed (and evicted) pods

Failed pods can clutter your cluster and affect performance. Thekrmfailed 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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

More fromZenika

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp