List all Public IP Addresses Across All of your AWS Accounts

Gathering all EC2 Public IPs

Recently I needed to automate pulling all public IP addresses across all of the EC2 accounts I have access to. I wrote the following script to deal with that problem.

Note: Thank you to Daniel Miessler for the script to pull the IPs. My Script makes that work across all accounts.

https://danielmiessler.com/blog/getawspublicips-aws-public-ip-internet/

Requirements

You will need to have the awscli installed and all of your accounts configured in ~/.aws/config

aws-all-ips-all-accounts.sh

#!/bin/bash
# Author: Steve Stonebraker
# Date: 2020-06-19
# Purpose: Outputs a list of public IP Addresses used by the ec2 instances across all accounts specified in your ~/.aws/config file


OUTDIR="${PWD}/output_all_pulic_ips"
echo $OUTDIR

[ ! -d ./${OUTDIR} ] && /bin/mkdir ${OUTDIR}  || /bin/rm -f ./${OUTDIR}/*

aws_profiles=$( \
        grep '\[profile' ~/.aws/config \
        | awk '{sub(/]/, "", $2); print $2}' \
)

# Iterate through all profiles in ~/.aws/config
for profile in ${aws_profiles}
do
    echo "[*] - Processing profile [$profile]"
    aws ec2 describe-instances   --profile ${profile} --query "Reservations[*].Instances[*].PublicIpAddress"   --output=text > ${OUTDIR}/${profile}_.txt
    echo file written to ${OUTDIR}/${profile}_.txt
done

    echo "[*] - Processing default instance"
# Don't forget about the default instance
     profile="default"
     aws ec2 describe-instances   --query "Reservations[*].Instances[*].PublicIpAddress"   --output=text > ${OUTDIR}/${profile}_.txt
     ehco "file written to ${OUTDIR}/${profile}_.txt"

echo "[*] - combining all output"

cat ${OUTDIR}/*.txt | sort | uniq > ${OUTDIR}/all_public_ips.txt
echo "[*] -  located at ${OUTDIR}/all_public_ips.txt"

Leave a Reply

Your email address will not be published. Required fields are marked *

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