Get Public IP Address on current EC2 Instance

Amazon Web-ServicesAmazon Ec2

Amazon Web-Services Problem Overview


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.

Amazon Web-Services Solutions


Solution 1 - Amazon Web-Services

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

Solution 2 - Amazon Web-Services

curl http://checkip.amazonaws.com

this returns the public ip address.

Solution 3 - Amazon Web-Services

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.

Solution 4 - Amazon Web-Services

From inside instnace type following command :

  curl -s v4.ident.me

Solution 5 - Amazon Web-Services

Get attached InstanceID with PublicIP.

aws ec2 describe-network-interfaces --query NetworkInterfaces[*].[Attachment.[InstanceId],Association.[PublicIp]] --output=json

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionobautistaView Question on Stackoverflow
Solution 1 - Amazon Web-ServicesJohn RotensteinView Answer on Stackoverflow
Solution 2 - Amazon Web-ServicesDuke DougalView Answer on Stackoverflow
Solution 3 - Amazon Web-ServicesmarkroxorView Answer on Stackoverflow
Solution 4 - Amazon Web-ServicescryptoKTMView Answer on Stackoverflow
Solution 5 - Amazon Web-ServicesRaghvendra SoniView Answer on Stackoverflow