Skip to content

Instantly share code, notes, and snippets.

@larkinwc
Created November 19, 2024 16:04
Show Gist options
  • Save larkinwc/754e7a417116717a1e83aa48eefe7f56 to your computer and use it in GitHub Desktop.
Save larkinwc/754e7a417116717a1e83aa48eefe7f56 to your computer and use it in GitHub Desktop.
EKS Cluster fetching script
#!/bin/bash
# Function to handle keyboard input
function select_option {
# Initialize variables
local selected=0
local options=("$@")
local key=""
# Hide cursor
tput civis
function print_menu {
local idx=0
echo -e "\nAvailable clusters:"
for item in "${options[@]}"; do
if [ $idx -eq $selected ]; then
echo "➜ $item"
else
echo " $item"
fi
((idx++))
done
}
# Clear screen before first print
clear
print_menu
# Handle keyboard input
while true; do
# Read a single character
read -rsn1 key
case $key in
$'\x1B') # Handle ESC sequences
read -rsn1 key
if [[ $key = "[" ]]; then
read -rsn1 key
case $key in
"A") # Up arrow
if [ $selected -gt 0 ]; then
((selected--))
fi
;;
"B") # Down arrow
if [ $selected -lt $((${#options[@]}-1)) ]; then
((selected++))
fi
;;
esac
fi
;;
"") # Enter key
echo
tput cnorm # Show cursor
return $selected
;;
esac
# Clear screen and reprint menu
clear
print_menu
done
}
# Ensure AWS CLI is configured
if ! command -v aws &> /dev/null; then
echo "AWS CLI is not installed. Please install it first."
exit 1
fi
# Get clusters and store in array (macOS compatible version)
echo "Fetching EKS clusters..."
# Convert AWS output into array, splitting on whitespace
CLUSTERS=($(aws eks list-clusters --output text --query 'clusters[*]' | tr '\t' '\n'))
if [ ${#CLUSTERS[@]} -eq 0 ]; then
echo "No EKS clusters found in the current region."
exit 1
fi
# Show selector menu
echo "Use ↑↓ arrows to select a cluster and press Enter to confirm"
select_option "${CLUSTERS[@]}"
selected_idx=$?
CLUSTER_NAME="${CLUSTERS[$selected_idx]}"
echo "Selected cluster: $CLUSTER_NAME"
# Update kubeconfig for the selected cluster
echo "Updating kubeconfig for cluster: $CLUSTER_NAME"
aws eks update-kubeconfig --name "$CLUSTER_NAME"
if [ $? -eq 0 ]; then
echo "Successfully configured kubectl for cluster: $CLUSTER_NAME"
echo "You can now use kubectl commands to interact with the cluster"
echo -e "\nCluster info:"
kubectl cluster-info
else
echo "Failed to update kubeconfig. Please check if the cluster name is correct."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment