amazon-web-servicesbashamazon-ec2

How to get (Private) IP of EC2 instance in bash script launched by cron?


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?


Solution

  • 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)