3

Given these parameters:

  1. An Ubuntu instance running anywhere (any region and any availability zone in that region)
  2. Only the AWS PHP SDK2 installed on the instance (no other EC2 Command line tools, etc.)
  3. CURL and WGET available

What is the most elegant way for an instance script to explicitly determine what Region it is running in?

* **Instance ID:** wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
* **Availability Zone:** wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone

The meta-data does not currently provide this information.

We are aware that currently, the trailing character can be stripped off the availability zone in order to naively determine the Region, however, there is no guarantee that Amazon will not change that in the future.

The ultimate goal is that our cron jobs and other custom services can figure out who and where they are, so that they can interact with other services and instances appropriately.

bubba
  • 3,839
  • 21
  • 25

3 Answers3

5

This should work for you:

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

echo $REGION

It's from this thread:

Find region from within an EC2 instance

Old Pro
  • 24,624
  • 7
  • 58
  • 106
jszobody
  • 28,495
  • 6
  • 61
  • 72
2

Using the PHP SDK you can do the following:

$instance = \Aws\Common\InstanceMetadata\InstanceMetadataClient::factory()
    ->get('dynamic/instance-identity/document')
    ->send()
    ->json();

echo $instance['region'];
Jeremy Lindblom
  • 6,437
  • 27
  • 30
  • 1
    The default SDK is loaded but I get Uncaught Error: Class 'Aws\Common\InstanceMetadata\InstanceMetadataClient' not found Example misses something. – John Dec 03 '17 at 17:26
1

As I have already answered on another question, AWS has implemented a clean way to figure out your region from the metadata server:

REGION="$(wget -q -O - http://169.254.169.254/latest/meta-data/placement/region)"

or

REGION="$(curl http://169.254.169.254/latest/meta-data/placement/region)

This will require usage of 2019-10-01 or later release of the metadata API. Make sure that's available by hitting the root endpoint and checking for it in the output.

My original answer

SteveGoob
  • 1,090
  • 9
  • 15