AWS: listing your EC2 instances IP addresses from command line

From lxadm | Linux administration tips, tutorials, HOWTOs and articles
Jump to: navigation, search

Increasing number of instances running on Amazon AWS / EC2, ever wondered how to get their list of IP addresses, including elastic IPs, from CLI (i.e. to make sure you don’t have any servers with proxy or SMTP open relay)?

Here is a small bash script that will do it.


 
#!/bin/bash
 
# Gets IPs of Amazon instances
KEY=/path/to/your.key
CERT=/path/to/your.crt
 
 
# No need to change anything below
set -u
export JAVA_HOME=/usr/lib/jvm/java-6-sun-1.6.0.26/
export EC2_HOME=/path/to/ec2-api-tools-1.4.4.3/
IPS=
 
# This one lists all regions
REGIONS=$($EC2_HOME/bin/ec2-describe-regions -K $KEY -C $CERT | awk '{print $2}')
 
# Finally, get public IPs from all regions, for you all instances
for REGION in $REGIONS; do
    IPS="$IPS $($EC2_HOME/bin/ec2-describe-instances --region $REGION -K $KEY -C $CERT | grep -o -P "\d+\.\d+\.\d+\.\d+" | grep -v '^10\.')"
done
 
echo $IPS


The newer aws command (from awscli package) might be easier to use:

aws ec2 describe-instances|grep PublicIpAddress