Wednesday, April 13, 2011

Find out the instance id from within an ec2 machine

How can I find out, from within an ec2 machine (user root) what is my instance id?

From stackoverflow
  • See this post - note that the IP address in the URL given is constant (which confused me at first), but the data returned is specific to your instance.

  • See the EC2 documentation on the subject.

    Run:

    wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
    

    If you need programatic access to the instance ID from within a script,

    die() { status=$1; shift; echo "FATAL: $*"; exit $status; }
    EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id || die \"wget instance-id has failed: $?\"`"
    

    An example of a more advanced use (retrieve instance ID as well as availability zone and region, etc.):

    EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id || die \"wget instance-id has failed: $?\"`"
    test -n "$EC2_INSTANCE_ID" || die 'cannot obtain instance-id'
    EC2_AVAIL_ZONE="`wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone || die \"wget availability-zone has failed: $?\"`"
    test -n "$EC2_AVAIL_ZONE" || die 'cannot obtain availability-zone'
    EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"
    

    You may also use curl instead of wget, depending on what is installed on your platform.

    Cheers, V.

    flybywire : works as advertised - great!

0 comments:

Post a Comment