Tuesday, February 23, 2016

Finding public IP of EC2 instance

To find public IP of AWS EC2 instance, if we run ifconfig it does not returns the external public IP.  Running ifconfig gives the local loopback address and eth0 address. However the eth0 address is not accessible from outside.

One easy way is to look at AWS console which lists the public IP. However that's not an option when you want to find the public IP in a programmatic or scripting environment. For finding the public IP of EC2 instance in a shell environment, you can do the following way



curl ifconfig.me

This will return the public IP of ec2 instance.

The other way to do that is again using curl

curl http://169.254.169.254/latest/meta-data/public-ipv4

And for the local IP do the following

curl http://169.254.169.254/latest/meta-data/local-ipv4

Setting the public IP to a variable in shell script


publicIp=$(curl -s http://169.254.169.254/latest/meta-data/public-ipv4)

Echoing will give the public IP

echo $publicIP

No comments:

Post a Comment