Is there a way to look up the region of an instance from within the instance?
I\'m looking for something similar to the method of finding the instance id.
This is the cleanest solution I found:
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document |sed -n 's/ "region" : "\(.*\)"/\1/p'
E.g.,
export REGION=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document |sed -n 's/ "region" : "\(.*\)"/\1/p')
ec2metadata
(no dash) is the current command to provide you all the aws hosting info about your ec2 box. this is the most elegant and secure approach. (ec2-metadata
is the old, no longer valid command.)
Was also looking for a solution to find region from the instance and here is my pure Bash solution:
az=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
region=${az:0:${#az}-1}
unless there are regions where AZ has more than two letters, which I'm not aware of.
Easiest I found so far
curl -s 169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/.$//'
If you have jq installed, you can also go about it (probably the most "graceful" method) this way:
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq -c -r .region
This simply returns the raw value of "region" without any pretty-printing or other formatting. Reference: AWS Forum
At some point since most of these answers have been posted, AWS did the reasonable thing and implemented a new path: latest/meta-data/placement/region
.
This means getting the region should be as simple as
REGION="$(wget -q -O - http://169.254.169.254/latest/meta-data/placement/region)"
EDIT: It's also probably worth mentioning that this endpoint was made available in the 2019-10-01 release of the metadata API. Make sure your instance supports that version or later before using this by checking http://169.254.169.254/
.