Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Public IP Address on current EC2 Instance

Using Amazon CLI, is there a way to get the public ip address of the current EC2? I'm just looking for the single string value, so not the json response describe-addresses returns.

like image 881
obautista Avatar asked Jul 30 '16 23:07

obautista


People also ask

Why public IP is not showing in EC2 instance?

The most common reason for no public IP address for your EC2 instance is that you are launching your EC2 instance using a private subnet. A private subnet means any EC2 instances located in that subnet aren't directly addressable from the public web.

Does EC2 instance need public IP?

For EC2 instances in a public subnet you will need an IP to receive web traffic. For security, make sure the security group associated with the public EC2 instance only allows traffic on the required ports.


3 Answers

The AWS Command-Line Interface (CLI) can be used to return information on any/all Amazon EC2 instances, eg:

$ aws ec2 describe-instances --instance-ids i-0c9c9b44b --query 'Reservations[*].Instances[*].PublicIpAddress' --output text

54.232.200.77

If you are seeking information about the EC2 instance from which you are executing the command, then the current IP address can be obtained via the instance metadata service:

$ curl http://169.254.169.254/latest/meta-data/

ami-id
ami-launch-index
ami-manifest-path
block-device-mapping/
hostname
iam/
instance-action
instance-id
instance-type
local-hostname
local-ipv4
mac
metrics/
network/
placement/
profile
public-hostname
public-ipv4
public-keys/
reservation-id
security-groups
services/

So, the private IP address is available via:

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

172.31.10.221

The public IP address is available via:

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

54.232.200.77
like image 127
John Rotenstein Avatar answered Oct 18 '22 05:10

John Rotenstein


curl http://checkip.amazonaws.com

this returns the public ip address.

like image 44
Duke Dougal Avatar answered Oct 18 '22 05:10

Duke Dougal


If you are inside the instance -

$ curl icanhazip.com
162.202.17.123

here is one more way

$ curl -s ifconfig.me
162.202.17.123

these methods are not limited to just AWS.

like image 12
markroxor Avatar answered Oct 18 '22 04:10

markroxor