Skip to content

Instantly share code, notes, and snippets.

@johnymachine
Last active September 22, 2023 16:08
Show Gist options
  • Select an option

  • Save johnymachine/29932f12815996c5fae5fdfbeea00e56 to your computer and use it in GitHub Desktop.

Select an option

Save johnymachine/29932f12815996c5fae5fdfbeea00e56 to your computer and use it in GitHub Desktop.
Get unused AWS Security Groups
#!/bin/bash
SECURITY_GROUPS=$(aws ec2 describe-security-groups --query "SecurityGroups[?GroupName!='default'].{Name: GroupName, Id: GroupId}" --output json)
# Iterate over each security group
echo "$SECURITY_GROUPS" | jq -c -r '.[]' | while read -r line; do
# Extract the security group ID, name, and association count
groupId=$(echo "$line" | jq -r '.Id')
groupName=$(echo "$line" | jq -r '.Name')
# Get a list of network interfaces associated with the security group
ASSOCIATED_INTERFACES=$(aws ec2 describe-network-interfaces --filters "Name=group-id,Values=$groupId" --query "NetworkInterfaces[*].NetworkInterfaceId" --output json | jq 'length')
# Print the result for the current security group
echo "Name: $groupName, Id: $groupId, Associations: $ASSOCIATED_INTERFACES"
# Check if association count is 0, and delete the security group if it is
if [ "$ASSOCIATED_INTERFACES" -eq 0 ]; then
echo "Associations count is 0. Deleting security group: $groupName"
#aws ec2 delete-security-group --group-id "$groupId"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment