Last active
September 4, 2025 14:45
-
-
Save bmmalone/88dbe1b43efec9a76610f9160cf61ce6 to your computer and use it in GitHub Desktop.
Helpers for working with kubernetes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# A shell function to connect to a running pod for a given application. | |
# | |
# Usage: | |
# source get_pod_name.sh # Or add to your .bashrc/.zshrc | |
# kubessh <app-name> | |
# | |
# Example: kubessh nginx | |
kubessh() { | |
# Check if an application name was provided. | |
if [ -z "$1" ]; then | |
echo "Usage: kubessh <app-name>" | |
return 1 | |
fi | |
local APP_NAME=$1 | |
echo "Attempting to connect to a pod with the 'app=${APP_NAME}' label..." | |
# Get the name of a running pod for the specified application label. | |
# We use a label selector and JSONPath to filter for the first pod name. | |
# The --field-selector is added to only get pods that are "Running". | |
local POD=$(kubectl get pods --field-selector=status.phase=Running \ | |
--selector=app=${APP_NAME} \ | |
-o=jsonpath='{.items[0].metadata.name}' 2>/dev/null) | |
# Check if a pod name was found. | |
if [ -z "$POD" ]; then | |
echo "Error: No running pod found with label 'app=${APP_NAME}'." | |
echo "Please check the application name and try again." | |
return 1 | |
fi | |
echo "Found pod: ${POD}" | |
# Execute a bash shell inside the found pod. | |
echo "Connecting to pod..." | |
kubectl exec -it ${POD} -- /bin/bash | |
} | |
# A shell function to stream the logs from a running pod for a given application. | |
# | |
# Usage: | |
# kubelogs <app-name> | |
# | |
# Example: kubelogs nginx | |
kubelogs() { | |
# Check if an application name was provided. | |
if [ -z "$1" ]; then | |
echo "Usage: kubelogs <app-name>" | |
return 1 | |
fi | |
local APP_NAME=$1 | |
echo "Attempting to get logs for a pod with the 'app=${APP_NAME}' label..." | |
# Get the name of a running pod for the specified application label. | |
local POD=$(kubectl get pods --field-selector=status.phase=Running \ | |
--selector=app=${APP_NAME} \ | |
-o=jsonpath='{.items[0].metadata.name}' 2>/dev/null) | |
# Check if a pod name was found. | |
if [ -z "$POD" ]; then | |
echo "Error: No running pod found with label 'app=${APP_NAME}'." | |
echo "Please check the application name and try again." | |
return 1 | |
fi | |
echo "Found pod: ${POD}" | |
# Stream the logs from the found pod using the -f (follow) flag. | |
echo "Streaming logs from pod..." | |
kubectl logs -f ${POD} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make sure to "source" this from .bashrc.