Skip to content

Instantly share code, notes, and snippets.

@mmehta-10
Last active April 15, 2024 12:03
Show Gist options
  • Save mmehta-10/c9de8daaf31d3d21c132129083fdabea to your computer and use it in GitHub Desktop.
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
#!/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"
@mmehta-10
Copy link
Author

mmehta-10 commented Mar 22, 2024

Before running the script, make sure to point kube context to the intended cluster.

Sample output should look something like this -


node                          allowed_pods  running_pods  attached_ips  unused_ips
ip-10-4-xx-xxx.ec2.internal   58                  24      33            9
ip-10-4-xxx-xxx.ec2.internal  234                 81      94            13
ip-10-4-aa-aa.ec2.internal    58                  17      28            11
ip-10-4-bb-bbb.ec2.internal   58                  29      45            16

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment