Skip to content

Instantly share code, notes, and snippets.

@skoenig
Last active July 5, 2023 16:22
Show Gist options
  • Save skoenig/e7de3e8437b23437daf5eca42e679a1a to your computer and use it in GitHub Desktop.
Save skoenig/e7de3e8437b23437daf5eca42e679a1a to your computer and use it in GitHub Desktop.
Enhance your Kubernetes experience with custom kubectl plugins. Streamlining, automating and simplifying everyday tasks for efficient cluster management.

Custom Kubectl Subcommands

With the introduction of custom subcommands in Kubernetes version 1.12, the kubectl command line tool became even more powerful for DevOps engineers. These plugins extend kubectl’s functionality, allowing you to streamline repetitive tasks, partially automate processes, and improve your day-to-day workflow as a Kubernetes operator.

To create or install a plugin for kubectl, simply place an executable or script in your system’s PATH or a directory specified by the $PATH environment variable. For example, kubectl-all installed in /usr/local/bin, can effortlessly invoked as a subcommand: kubectl all. No additional configuration or registration is necessary. Detailed instructions can be found in the official documentation.

An ecosystem has already developed around the Krew plugin manager, and there are many great plugins available, but here are some neat subcommands that I use frequently myself for day-to-day troubleshooting, monitoring, and operational tasks.

#!/usr/bin/env bash
# Get all Pods across all namespaces, including status and node name.
kubectl get pod -o=custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName --all-namespaces
#!/usr/bin/env bash
# Kills a pod forcibly without waiting.
set -eo pipefail
if [[ -z "${1// /}" ]]
then
echo >&2 "error: resource(s) were provided, but no name was specified"
exit 1
fi
kubectl delete pod "${1}" --grace-period=0 --force
#!/usr/bin/env bash
# Lists deployments which have less than desired pods ready/available.
set -eo pipefail
if ! command -v jq &>/dev/null
then
echo >&2 "error: unable to find 'jq', please install it to use this plugin."
exit 1
fi
kubectl get deployments -o json | jq -r '.items[] | select(.status.unavailableReplicas > 0) | .metadata.name'
#!/usr/bin/env bash
# Start a one-off containers for inspection and debugging, image and command is configurable.
set -eo pipefail
image=${1:-alpine}
command=${2:-sh}
kubectl run -it --rm --restart=Never "shell-$(date +%s)" --image="${image}" -- ${command}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment