|
| 1 | +#!/bin/bash |
| 2 | +# |
| 3 | +# This script is used to list all VPCs in the AWS account. |
| 4 | +################################################################################ |
| 5 | +# |
| 6 | +usage () { |
| 7 | + cat 1>&2 <<EOF |
| 8 | +Usage: $(basename $0) [-a] [-r region] [-s] |
| 9 | +where: -a list - All regions |
| 10 | + -r region - List VPCs in the specified region |
| 11 | + -s - List all the subnets in the VPC |
| 12 | + -q - Supress extraineous output |
| 13 | + -h - Print this help message |
| 14 | +EOF |
| 15 | + exit 1 |
| 16 | +} |
| 17 | + |
| 18 | +# Check if the required tools are installed |
| 19 | +for tool in aws jq; do |
| 20 | + if which $tool > /dev/null 2>&1; then |
| 21 | + : |
| 22 | + else |
| 23 | + echo "Error, $tool command is rquired to run this script." |
| 24 | + exit 1 |
| 25 | + fi |
| 26 | +done |
| 27 | + |
| 28 | +allRegions=False |
| 29 | +regions="" |
| 30 | +subnets=False |
| 31 | +quiet=False |
| 32 | +while getopts "qsar:h" opt; do |
| 33 | + case $opt in |
| 34 | + a) allRegions=True |
| 35 | + ;; |
| 36 | + r) regions=$OPTARG |
| 37 | + ;; |
| 38 | + s) subnets=True |
| 39 | + ;; |
| 40 | + q) quiet=True |
| 41 | + ;; |
| 42 | + *) usage |
| 43 | + ;; |
| 44 | + esac |
| 45 | +done |
| 46 | + |
| 47 | +tmpout=/tmp/list_aws_vpcs.$$ |
| 48 | +trap 'rm -f $tmpout' exit |
| 49 | + |
| 50 | +if [ "$allRegions" == "True" ]; then |
| 51 | + regions=$(aws ec2 describe-regions --query "Regions[].RegionName" --output=text) |
| 52 | +else |
| 53 | + if [ -z "$regions" ]; then |
| 54 | + regions=$(aws configure get region) |
| 55 | + fi |
| 56 | +fi |
| 57 | + |
| 58 | +vpcFormatStr="%21s %19s %s\n" |
| 59 | +for region in $regions; do |
| 60 | + [ "$quiet" != "True" ] && printf "\nRegion: $region\n" |
| 61 | + first=True |
| 62 | + aws ec2 describe-vpcs --region $region | jq -r '.Vpcs[] | .VpcId + " " + .CidrBlock + " " + (if (.Tags != null) then (.Tags[] | (select(.Key == "Name") .Value)) else "" end)' | \ |
| 63 | + while read vpcId cidr name; do |
| 64 | + if [ "$quiet" != "True" -a "$first" == "True" ]; then |
| 65 | + printf "\n$vpcFormatStr" "VPC IP" "CIDR" "Name" |
| 66 | + first=False |
| 67 | + fi |
| 68 | + echo "$vpcId,$cidr,$name" | awk -F, '{printf "'"$vpcFormatStr"'", $1, $2, $3}' |
| 69 | + |
| 70 | + if [ "$subnets" == "True" ]; then |
| 71 | + printf "\n\tSubnets:\n" |
| 72 | + aws ec2 describe-subnets --filters '[{"Name": "vpc-id", "Values": ["'$vpcId'"]}]' | jq -r '.Subnets[] | .VpcId + " " + .SubnetId + " " + .CidrBlock + " " + (first(.Tags[] | select(.Key == "Name").Value) // "")' | awk 'BEGIN {formatStr="\t\t%24s %18s %s\n"; printf(formatStr, "Subnet ID", "CIDR", "Name")} {name=$4; for (i=5; i<=NF; i++) {name=name " " $(i)}; printf(formatStr , $2, $3, name)}' |
| 73 | + first=True |
| 74 | + fi |
| 75 | + done |
| 76 | +done |
0 commit comments