Find region from within an EC2 instance

前端 未结 28 1403
谎友^
谎友^ 2020-12-02 06:24

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.

相关标签:
28条回答
  • 2020-12-02 07:10

    If you are looking to get region using JS, this should work :

    meta.request("/latest/meta-data/placement/availability-zone",function(err,data){
            if(err)
                    console.log(err);
            else{
                    console.log(data);
                    str = data.substring(0, data.length - 1);
                    AWS.config.update({region:str});
                    ec2 = new AWS.EC2();
                }
         });
    

    This was the mapping found from AWS DOCS, in response to metadata API call, just trim the last character should work.

      eu-west-1a :eu-west-1
      eu-west-1b :eu-west-1
      eu-west-1c :eu-west-1
      us-east-1a :us-east-1
      us-east-1b :us-east-1
      us-east-1c :us-east-1
      us-east-1d :us-east-1
      ap-northeast-1a :ap-northeast-1
      ap-northeast-1b :ap-northeast-1
      us-west-1a :us-west-1
      us-west-1b :us-west-1
      us-west-1c :us-west-1
      ap-southeast-1a :ap-southeast-1
      ap-southeast-1b :ap-southeast-1
    
    0 讨论(0)
  • 2020-12-02 07:11

    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.

    0 讨论(0)
  • 2020-12-02 07:11

    very simple one liner

    export AVAILABILITY_ZONE=`wget -qO- http://instance-data/latest/meta-data/placement/availability-zone`
    export REGION_ID=${AVAILABILITY_ZONE:0:${#AVAILABILITY_ZONE} - 1}
    
    0 讨论(0)
  • 2020-12-02 07:11

    Thanks to https://unix.stackexchange.com/a/144330/135640, with bash 4.2+ we can just strip the last char from the availability zone:

    $ region=`curl -s 169.254.169.254/latest/meta-data/placement/availability-zone`
    $ region=${region::-1}
    $ echo $region
    us-east-1
    

    This assumes AWS continues to use a single character for availability zones appended to the region.

    0 讨论(0)
提交回复
热议问题