Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find region from within an EC2 instance

People also ask

How do I get AWS region from command line?

aws configure get region will get you the current region at that point in your script. If you are using a profile, then type aws configure get region --profile $PROFILE_NAME . This will return the region of the configuration, not the region that your aws cli invocation was performed from.

How do I know which AWS region to use?

Assess potential Regions for the right optionCheck feature availability of each service and versions available, if your workload has specific requirements. Calculate the cost of the workload on each Region using the AWS Pricing Calculator. Test the network latency between your user base location and each AWS Region.

How do I launch an EC2 instance of a specific region?

Right-click the instance and select Create Image to make an AMI from the instance. Go to the AMI page, right-click on the new AMI and select Launch Instance. In the new instance settings, choose a specific (different) availability zone.

How do I see all EC2 instances in all regions?

Go to VPC dashboard https://console.aws.amazon.com/vpc/home and click on Running instances -> See all regions .


That URL (http://169.254.169.254/latest/dynamic/instance-identity/document) doesn't appear to work anymore. I get a 404 when I tried to use it. I have the following code which seems to work though:

EC2_AVAIL_ZONE=`curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone`
EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed 's/[a-z]$//'`"

Hope this helps.

EDIT: Improved sed based on comments


There is one more way of achieving that:

REGION=`curl http://169.254.169.254/latest/dynamic/instance-identity/document|grep region|awk -F\" '{print $4}'`

echo $REGION

us-east-1

If you are OK with using jq, you can run the following:

curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq .region -r

I guess it's the cleanest way.


ec2-metadata --availability-zone | sed 's/.$//'

For debian based systems, the command is without dash.

ec2metadata --availability-zone | sed 's/.$//'

If you want to avoid regular expression, here's a one-liner you can do with Python:

curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | python -c "import json,sys; print json.loads(sys.stdin.read())['region']"