Getting Public IP of Running EC2 Instance: Linux Commands

Command to Retrieve Public IP of a Running Linux EC2 Instance

Prev Question Next Question

Question

Which of the following commands can be issued on your linux EC2 Instance to get the public IP of the instance while it is in the running state.

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

Answer - C.

The URL: for Instance metadata is.

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

The different properties that can be retrieved via the Instance metadata is.

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/

For more information on Instance metadata, please visit the below URL:

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html

The correct answer is C. curl http://169.254.169.254/latest/meta-data/public-ipv4.

Explanation:

When an EC2 instance is launched, it is assigned a private IP address and optionally an Elastic IP address. However, the public IP address is dynamically assigned to the instance at launch time, and can change if the instance is stopped and started again.

To retrieve the public IP address of an EC2 instance while it is running, the instance can query the metadata service at http://169.254.169.254. This service is available only within the EC2 instance, and provides a way for the instance to retrieve metadata about itself, including its public IP address.

The correct command to retrieve the public IP address is:

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

Option A (curl http://254.169.254.169/latest/meta-data/public-ipv4) is incorrect because the IP address 254.169.254.169 is not a valid IP address range for EC2 metadata service.

Option B (curl http://127.0.0.1/latest/meta-data/public-ipv4) is incorrect because 127.0.0.1 refers to the loopback interface of the instance, which means it is trying to connect to itself, not the metadata service.

Option D (curl http://10.0.1.0/latest/meta-data/public-ipv4) is incorrect because the IP address 10.0.1.0 is a private IP address range and is not valid for accessing the metadata service.