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:05

    Or don't make Ubuntu or this tool a requirement and simply do:

    : "${EBS_VOLUME_AVAILABILITY_ZONE:=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)}"
    : ${EBS_VOLUME_REGION:="${EBS_VOLUME_AVAILABILITY_ZONE%%*([![:digit:]])}"}
    
    0 讨论(0)
  • 2020-12-02 07:05

    If you work with json - use right tools. jq much powerful in this case.

    # curl -s curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r '.region'
    eu-west-1
    
    0 讨论(0)
  • 2020-12-02 07:06

    For anyone wanting to do this with good ol powershell

    $var = (curl http://169.254.169.254/latest/dynamic/instance-identity/document | Select-String-Pattern "Zone" | ConvertFrom-Json | Select-Object -ExpandProperty "region")
    echo $var
    
    0 讨论(0)
  • 2020-12-02 07:08

    For finding out information about the EC2 you are logged into, you can use the ec2-metadata tool.

    You can install the tool by following this link. After installing the tool, you can run

    # ec2-metadata -z

    to find out the region.

    This tools comes installed with the latest (10.10) Ubuntu AMIs,

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

    A method using only egrep, which should work on most any linux instance spun up without having to install any extra tooling. I tested this against a list of all current AWS regions and they all match.

    curl http://169.254.169.254/latest/meta-data/placement/availability-zone | egrep -o '(\w)+-(\w)+-[0-9]'

    Explanation of the REGEX:

    • "(\w)+" This matches any number of letters
    • "-" matches only a single dash
    • "[0-9]" matches any 1 number

    If you want this into a variable do:

    region=$(curl http://169.254.169.254/latest/meta-data/placement/availability-zone | egrep -o '(\w)+-(\w)+-[0-9]')

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

    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
    
    0 讨论(0)
提交回复
热议问题