Find region from within an EC2 instance

前端 未结 28 1402
谎友^
谎友^ 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:44

    This works for eu-central-1 as well as the various letter zones. (I don't have enough rep to reply to the sed answer above)

    ec2-metadata --availability-zone | sed 's/[a-z]$//'
    
    0 讨论(0)
  • 2020-12-02 06:47

    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']"
    
    0 讨论(0)
  • 2020-12-02 06:48

    You might get instance region using this curl request

    $ curl http://169.254.169.254/latest/meta-data/placement/region
    us-east-1
    
    0 讨论(0)
  • 2020-12-02 06:50

    Get the region from the availability zone, strip off the last letter of it.

    ec2-metadata -z | awk '{print $2}' | sed 's/[a-z]$//'
    
    0 讨论(0)
  • 2020-12-02 06:51

    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

    0 讨论(0)
  • 2020-12-02 06:52

    You can use ec2-metadata:

    ec2-metadata -z | grep -Po "(us|sa|eu|ap)-(north|south|central)?(east|west)?-[0-9]+"
    
    0 讨论(0)
提交回复
热议问题