Recently I needed to generate a list of all subnets across every AWS account in an organization.
I’ve documented an easy way to achieve this
Prerequisites
Set up your aws config for multiple profiles (one for each account)
[default]
region=us-east-1
output=json
[profile account1]
role_arn = arn:aws:iam::XXXXXXXXXXXX:role/OrganizationAccountAccessRole
source_profile = default
region=us-east-1
output=json
[profile account2]
role_arn = arn:aws:iam::XXXXXXXXXXXX:role/OrganizationAccountAccessRole
source_profile = default
region=us-east-1
output=json
[profile account3]
role_arn = arn:aws:iam::XXXXXXXXXXXX:role/OrganizationAccountAccessRole
source_profile = default
region=us-east-1
output=json
Instructions
Setup my script either via github or by copying and pasting
Via github
curl -O https://raw.githubusercontent.com/ssstonebraker/braker-scripts/master/working-scripts/aws-list-subnets-all-profiles.sh
Copy and Paste
#!/bin/bash
# Filename: aws-list-subnets-all-profiles.sh
# Description: print subnets from all vpcs across all profiles to a txt file
# Usage: ./aws-list-subets-all-profiles.sh
# Output: all_subnets.txt
# Author: Steve Stonebraker
aws_profiles=$( \
grep '\[profile' ~/.aws/config \
| awk '{sub(/]/, "", $2); print $2}' \
)
for profile in ${aws_profiles}
do
echo "[*] - Processing profile [$profile]"
aws ec2 describe-subnets --profile ${profile} | jq -r '.Subnets[]|[.CidrBlock]|@tsv' | sort > subnets_${profile}.txt
done
echo "[*] - Processing default "
aws ec2 describe-subnets | jq -r '.Subnets[]|[.CidrBlock]|@tsv' | sort > subnets_default.txt
echo "[*] - combining all output"
cat subnets*.txt | sort | uniq > all_subnets.txt
Run the script
chmod +x ./aws-list-subets-all-profiles.sh
./aws-list-subets-all-profiles.sh