Sometimes we may get requirements to identify the public ip address of an ec2 instance from the command line. There are various ways to perform this operation.
- Using AWS CLI
- Using a simple REST call
aws ec2 describe-instances --instance-ids --query "Reservations[*].Instances[*].PublicIpAddress" --output text
If we are on the same EC2 host, we can obtain the details of the EC2 instance using 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/
Using this, for getting the private IP, the command will be
curl http://169.254.169.254/latest/meta-data/local-ipv4
For getting the public IP, the command will be
curl http://169.254.169.254/latest/meta-data/public-ipv4
Using AWS CLI : aws ec2 describe-instances –instance-ids –query “Reservations[*].Instances[*].PublicIpAddress”
You need ” ” double quotes.