You can use AWS EC2 metadata service to get the EC2 instance public or private ip address from within an ec2 instance.
The link to EC2 metadata service is http://169.254.169.254/latest/meta-data/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
## ----------------- ## Public IP Address ## ----------------- ## for IMDSv1 (default) curl http://169.254.169.254/latest/meta-data/public-ipv4 ## for IMDSv2 TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \ && curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/public-ipv4 ## ------------------ ## Private IP Address ## ------------------ ## for IMDSv1 (default) curl http://169.254.169.254/latest/meta-data/local-ipv4 ## for IMDSv2 TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` \ && curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/local-ipv4 |