Skip to content

Instantly share code, notes, and snippets.

@fnavalca
Last active October 16, 2020 09:03
Show Gist options
  • Save fnavalca/91c60bb9f5ef0a5ccd90a3ff72330c67 to your computer and use it in GitHub Desktop.
Save fnavalca/91c60bb9f5ef0a5ccd90a3ff72330c67 to your computer and use it in GitHub Desktop.
AWS resources finder by subnet IDs
#!/usr/bin/env bash
# Add all the subnet ID you want to find resources
declare -a subnets=("subnet-id")
echo "Removing all previous data"
rm -rf rds_*.txt ec2_*.txt redshift_*.txt elasticache_*.txt codebuild_*.txt lambda_*.txt
find_rds () {
echo "Finding RDS for $1"
aws rds describe-db-instances | jq -r --arg subnet "$1" '.[][] | select(.DBSubnetGroup.Subnets[].SubnetIdentifier == $subnet).DBInstanceIdentifier' > rds_$1.txt
}
find_ec2 () {
echo "Finding EC2 for $1"
aws ec2 describe-instances | jq -r --arg subnet "$1" '.Reservations[].Instances[] | select(.NetworkInterfaces[].SubnetId == $subnet).Tags|from_entries|.Name' > ec2_$1.txt
}
find_redshift () {
echo "Finding Redshift for $1"
subnet_groups=$(aws redshift describe-cluster-subnet-groups | jq -r --arg subnet "$1" '.[][] | select(.Subnets[].SubnetIdentifier == $subnet).ClusterSubnetGroupName')
touch redshift_$1.txt
for subnet_group in ${subnet_groups}; do
aws redshift describe-clusters | jq -r --arg subnetgroup "${subnet_group}" '.[] | select(.[].ClusterSubnetGroupName == $subnetgroup)' >> redshift_$1.txt
done
}
find_elasticache () {
echo "Finding ElastiCache for $1"
subnet_groups=$(aws elasticache describe-cache-subnet-groups | jq -r --arg subnet "$1" '.[][] | select(.Subnets[].SubnetIdentifier == $subnet).CacheSubnetGroupName')
touch elasticache_$1.txt
for subnet_group in ${subnet_groups}; do
aws elasticache describe-cache-clusters | jq -r --arg subnetgroup "${subnet_group}" '.[] | select(.[].CacheSubnetGroupName == $subnetgroup) | .[].CacheClusterId' >> elasticache_$1.txt
done
}
find_codebuild () {
echo "Finding CodeBuild for $1"
codebuild_projects=($(aws codebuild list-projects | jq -r '.projects[]' | tr '\n' ' '))
touch codebuild_$1.txt
for codebuild_project in ${codebuild_projects[@]}; do
if [[ $(aws codebuild batch-get-projects --names ${codebuild_project} --query "contains(projects[*].vpcConfig.subnets[], '$1')") == "true" ]]; then
echo ${codebuild_project} >> codebuild_$1.txt
fi
done
}
find_lambda () {
echo "Finding Lambda for $1"
aws lambda list-functions --query "Functions[?VpcConfig.SubnetIds[? @ == '$1']].FunctionName" > lambda_$1.txt
}
for subnet in ${subnets[@]}; do
find_rds ${subnet}
find_ec2 ${subnet}
find_redshift ${subnet}
find_elasticache ${subnet}
find_codebuild ${subnet}
find_lambda ${subnet}
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment