Monday, August 10, 2020

Show count and instance IDs of existing EC2 instances in all regions of AWS:

I'm kicking myself for not posting this earlier in my past life-- but here's a handy shell script that can list the number of instances in each region in AWS.


Show count and instance IDs of existing EC2 instances in all regions of AWS:


Single line:

Set my AWS profile to my personal account rather than work.  
To setup, use aws --profile personal configure   

$ export aws_profile=personal


If the buffer space can handle long entries, you can run this in a single line, otherwise there's a multi line below to run as a script.

    $ for i in $(aws --profile $aws_profile ec2 describe-regions --output json | grep "RegionName" | cut -d '"' -f4 | sort); do export buf=$(aws --profile $aws_profile ec2 --region $i describe-instances --output json | grep InstanceId | cut -d '"' -f4); export buf_num=$(echo $buf | grep -c .); echo "=== $i -> $buf_num instance(s) ===";echo $buf ; done

    Multi Line:

    Good for placing into a script to run, also listed this way for readability:
    1. #!/bin/bash export aws_profile=personal for i in $(aws --profile $aws_profile ec2 describe-regions --output json| grep "RegionName" | cut -d '"' -f4 | sort); do export buf=$(aws ec2 describe-instances \ --profile $aws_profile \ --region $i \ --output json | \ grep InstanceId | \ cut -d '"' -f4); export buf_num=$(echo $buf | grep -c .); echo "=== $i -> $buf_num instance(s) ==="; echo $buf; done

    Sample Output:

    1. === ap-northeast-1 -> 0 instances === === ap-northeast-2 -> 0 instances === === ap-south-1 -> 0 instances === === ap-southeast-1 -> 0 instances === === ap-southeast-2 -> 0 instances === === ca-central-1 -> 0 instances === === eu-central-1 -> 0 instances === === eu-north-1 -> 0 instances === === eu-west-1 -> 0 instances === === eu-west-2 -> 0 instances === === eu-west-3 -> 0 instances === === sa-east-1 -> 0 instances === === us-east-1 -> 0 instances === === us-east-2 -> 0 instances === === us-west-1 -> 0 instances === === us-west-2 -> 1 instances === i-012345678901234ab