List All Subnets Across Multiple AWS accounts/profiles

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

Leave a Reply

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  

  

  

This site uses Akismet to reduce spam. Learn how your comment data is processed.