Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the instance id from within an ec2 instance?

How can I find out the instance id of an ec2 instance from within the ec2 instance?

like image 639
flybywire Avatar asked Mar 09 '09 10:03

flybywire


People also ask

How do I find my instance ID?

Resolution. Your Amazon Connect instance ID is the 36-character string at the end of your instance's Amazon Resource Name (ARN). To see your instance's ARN, follow the instructions in Find your Amazon Connect instance ID/ARN.

How do I find the instance metadata on an EC2 instance?

To view instance metadata, you can only use the link-local address of 169.254. 169.254 to access. Requests to the metadata via the URI are free, so there are no additional charges from AWS. Using the curl tool on Linux or the PowerShell cmdlet Invoke-WebRequest on Windows, you will first create your token.

How do I find my EC2 instance AMI ID?

To find a Linux AMI using the AMIs pageOpen the Amazon EC2 console at https://console.aws.amazon.com/ec2/ . From the navigation bar, select the Region in which to launch your instances. You can select any Region that's available to you, regardless of your location. In the navigation pane, choose AMIs.


1 Answers

See the EC2 documentation on the subject.

Run:

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

If you need programmatic 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: $?\"`" 

Here is 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.

like image 70
vladr Avatar answered Sep 28 '22 14:09

vladr