I am currently determining the private IP like so in a bash script that is run via cron @reboot
:
ec2_ip=$(echo $HOSTNAME | grep -Eo '[[:digit:]] -[[:digit:]] -[[:digit:]] -[[:digit:]] ' | head -n 1 | tr '-' '.')
This works fine but is not very elegant. Is there a simpler way to get the EC2 instance's private IP? And also perhaps its public IP?
CodePudding user response:
You can use the metadata service for this.
Private ip:
ec2_private_ip = $(curl http://169.254.169.254/latest/meta-data/local-ipv4)
Public ip:
ec2_public_ip = $(curl http://169.254.169.254/latest/meta-data/public-ipv4)
CodePudding user response:
If you have access to the aws cli
and know the instance-id, you can get the private ip address via:
aws ec2 describe-instances --instance-ids i-02c55bf68498143b3 --query 'Reservations[0].Instances[0].NetworkInterfaces[0].PrivateIpAddress' --output text
Or the public ip address via:
aws ec2 describe-instances --instance-ids $1 --query 'Reservations[0].Instances[0].PublicIpAddress' --output text
(Although it is arguable as to whether this is any more elegant.)