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 06:59

    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')

    • Doesn't make an API call, uses EC2 instance meta-data
    • Only uses curl, and basic sed, so no dependencies on SDKs or tools not likely to be installed.
    • Doesn't attempt to parse the Availability Zone name, so no worries if AWS changes AZ/Region name format
    0 讨论(0)
  • 2020-12-02 06:59

    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.)

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

    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.

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

    Easiest I found so far

     curl -s 169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/.$//'
    
    0 讨论(0)
  • 2020-12-02 07:04

    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

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

    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/.

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