Last active
April 15, 2024 12:03
-
-
Save mmehta-10/c9de8daaf31d3d21c132129083fdabea to your computer and use it in GitHub Desktop.
Get count of spare IPs left on each EKS worker node, sorted from oldest to newest node
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 | |
REGION=us-east-1 | |
# Get a list of all the nodes in the cluster | |
NODES=$(kubectl get nodes --sort-by=.metadata.creationTimestamp -o=jsonpath='{.items[*].metadata.name}') | |
K8S_NODES_DATA=$(kubectl get no -ojson) | |
# Create a temporary file to store combined output | |
tempfile=$(mktemp) | |
# Create and store a list of ALL the pods running in the cluster | |
ALL_PODS=$(kubectl get pods -o wide --all-namespaces) | |
# Get a list of AWS instance IDs | |
# To be used as input for `aws describe-instances` | |
AWS_INSTANCE_ID_LIST=$(echo $K8S_NODES_DATA | jq '.items[].spec.providerID' | tr -d '"') | |
AWS_INSTANCE_ID_LIST=$(echo $AWS_INSTANCE_ID_LIST | sed 's/aws:\/\/\/[a-z]*-[a-z]*-[0-9][a-z]\///g') | |
# Prepare aws output for all instances | |
AWS_OUTPUT=$(aws ec2 describe-instances \ | |
--instance-ids $AWS_INSTANCE_ID_LIST \ | |
--output json \ | |
--region $REGION) | |
echo -e "node\tallowed_pods\trunning_pods\tattached_ips\tunused_ips" >>"$tempfile" | |
# Iterate over each node | |
for node in $NODES; do | |
allowed_pods=($(echo $K8S_NODES_DATA | jq ".items[] | select(.metadata.name == \"$node\")" | jq '.status.allocatable.pods' | tr -d '"')) | |
# Get no. of pods running on the node | |
running_pods=$(echo "$ALL_PODS" | grep $node | wc -l) | |
# Get count of allocated IPs (it should match IPs seen in AWS EC2 console) | |
attached_ips=($(echo $AWS_OUTPUT | jq ".Reservations[].Instances[] | select(.PrivateDnsName == \"$node\")" | jq '.NetworkInterfaces[].PrivateIpAddresses[].PrivateIpAddress' | wc -l)) | |
# Subtract above to get unused/available IPs | |
unused_ips=$(expr $attached_ips - $running_pods) | |
echo -e "$node\t$allowed_pods\t$running_pods\t$attached_ips\t$unused_ips" >>"$tempfile" | |
done | |
# Print the combined output in a table format using column command | |
column -t -s $'\t' "$tempfile" | |
# echo "$tempfile" | |
# Remove the temporary file | |
# rm "$tempfile" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Before running the script, make sure to point kube context to the intended cluster.
Sample output should look something like this -