Last active
October 7, 2021 14:03
-
-
Save rightsaidjames/d30df339b3dad5ffe2cc3f8ac1238828 to your computer and use it in GitHub Desktop.
Kubernetes Helper Script - Quickly bash into any environment without having to copy-and-paste namespace names or pod names.
This file contains 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 | |
# Created by the award-winning Rick Peacock, genericised and extended by James Sheasby Thomas. | |
#!Usage: ''$ ./kubehelper.sh' then follow prompts. | |
#! Ensure you have a context set, or hardcode '--context=[yourcontext]' into the kubectl commands in this script. | |
set -e -o pipefail | |
echo "Desired namespace (partial match is fine):" | |
read -r PREFIX | |
NAMESPACES=$(kubectl get namespaces | grep ^"$PREFIX" | grep Active | awk '{ print $1 }') | |
if [ -z "$NAMESPACES" ]; then echo "Couldn't find any matching namespaces, please check your prefix is correct or run 'kubectl get namespaces'" && exit 0;fi | |
echo "Enter the number of your required namespace or q to quit:" | |
select NAMESPACE in "Quit" $NAMESPACES | |
do | |
if [[ "$NAMESPACE" = "Quit" ]]; then exit 0; fi | |
break | |
done | |
echo "Selected namespace: $NAMESPACE" | |
PODS=$(kubectl --namespace="$NAMESPACE" get pods | grep Running | awk '{ print $1 }') | |
if [ -z "$PODS" ]; then echo "Couldn't find any running pods, please check the environment's health or run 'kubectl --namespace==$NAMESPACE get pods'" && exit 0;fi | |
echo "Enter the number of the required pod or q to quit:" | |
select POD in "Quit" $PODS | |
do | |
if [[ "$POD" = "Quit" ]]; then exit 0; fi | |
break | |
done | |
CONTAINERS=$(kubectl --namespace="$NAMESPACE" get pods $POD -o jsonpath='{.spec.containers[*].name}') | |
if [ -z "$CONTAINERS" ]; then echo "Couldn't find any running containers, please check the environment's health or run 'kubectl --namespace="$NAMESPACE" --pod=$POD get containers'" && exit 0;fi | |
echo "Enter the number of the required container or q to quit:" | |
select CONTAINER in "Quit" $CONTAINERS | |
do | |
if [[ "$CONTAINER" = "Quit" ]]; then exit 0; fi | |
break | |
done | |
echo "Connecting to $CONTAINER in pod: $POD" | |
# This command will fail if your chosen container does not come with a shell (common with Go services). | |
# If you know that the containers you're working with have Bash on them, you can change /bin/sh to /bin/bash | |
kubectl --namespace="$NAMESPACE" exec -it "$POD" --container=$CONTAINER -- /bin/sh |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment