How to Get the EC2 Instance ID from Within an EC2 Instance?

Every EC2 instance has associated metadata, which AWS makes available to all users & applications inside the instance. The instance ID is part of this metadata. Here’s a complete list of everything included in the metadata β€” Instance metadata categories. Run the following at a Bash prompt to get the instance ID:

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

The same can be captured in a variable for use in shell scripts like so:

EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id`"

You can get a lot more info about the instance from its metadata, like its availability zone, region, etc.:

EC2_AVAIL_ZONE="`wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone`"
EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"

cURL can also be used instead of wget:

curl http://169.254.169.254/latest/meta-data/

You can also use http://instance-data/ in place of http://169.254.169.254/ but only if you’re using Amazon’s DNS. If you need to fetch various details about the instance, try /dynamic/instance-identity/document instead of making multiple calls to the metadata URL:

$ wget -q -O - http://169.254.169.254/latest/dynamic/instance-identity/document

{
    "devpayProductCodes" : null,
    "privateIp" : "10.1.2.3",
    "region" : "us-east-1",
    "kernelId" : "aki-12345678",
    "ramdiskId" : null,
    "availabilityZone" : "us-east-1a",
    "accountId" : "123456789012",
    "version" : "2010-08-31",
    "instanceId" : "i-12345678",
    "billingProducts" : null,
    "architecture" : "x86_64",
    "imageId" : "ami-12345678",
    "pendingTime" : "2020-01-01T05:01:23Z",
    "instanceType" : "t2.small"
}

These HTTP calls are not billed. The instance ID is also stored in /var/lib/cloud/data/instance-id.

ec2-metadata

On Amazon Linux AMIs, you can use:

$ ec2-metadata -i
instance-id: i-1234567890abcdef0

To catch it in a variable:

EC2_INSTANCE_ID=$(ec2-metadata --instance-id | cut -d " " -f 2);

Or on Ubuntu & other Linux flavors:

ec2metadata --instance-id

You might need to install this utility first:

sudo apt-get install cloud-utils

A LOT more is available using these utils:

ec2metadata --help
Syntax: /usr/bin/ec2metadata [options]

Query and display EC2 metadata.

If no options are provided, all options will be displayed

Options:
    -h --help               show this help

    --kernel-id             display the kernel id
    --ramdisk-id            display the ramdisk id
    --reservation-id        display the reservation id

    --ami-id                display the ami id
    --ami-launch-index      display the ami launch index
    --ami-manifest-path     display the ami manifest path
    --ancestor-ami-ids      display the ami ancestor id
    --product-codes         display the ami associated product codes
    --availability-zone     display the ami placement zone

    --instance-id           display the instance id
    --instance-type         display the instance type

    --local-hostname        display the local hostname
    --public-hostname       display the public hostname

    --local-ipv4            display the local ipv4 ip address
    --public-ipv4           display the public ipv4 ip address

    --block-device-mapping  display the block device id
    --security-groups       display the security groups

    --mac                   display the instance mac address
    --profile               display the instance profile
    --instance-action       display the instance-action

    --public-keys           display the openssh public keys
    --user-data             display the user data (not actually metadata)

.NET

Hit the same endpoint programmatically to fetch this info:

string instanceId = new StreamReader(HttpWebRequest
  .Create("http://169.254.169.254/latest/meta-data/instance-id")
  .GetResponse().GetResponseStream()).ReadToEnd();

Python

import boto.utils
region = boto.utils.get_instance_metadata()['local-hostname'].split('.')[1]

Or at the command line as:

python -c "import boto.utils; print boto.utils.get_instance_metadata()['local-hostname'].split('.')[1]"

Another example:

boto.utils.get_instance_metadata()['placement']['availability-zone'][:-1]

JavaScript

new AWS.MetadataService().request('instance-id',
  (error, data) => instanceID = data)

PowerShell

(New-Object System.Net.WebClient)
.DownloadString("http://169.254.169.254/latest/meta-data/instance-id")

Or simply:

$instanceId=(Invoke-WebRequest -Uri
'http://169.254.169.254/latest/meta-data/instance-id').Content

Ruby

require 'rubygems'
require 'aws-sdk'
require 'net/http'

metadata_endpoint = 'http://169.254.169.254/latest/meta-data/'
instance_id = Net::HTTP.get( URI.parse( metadata_endpoint + 'instance-id' ) )

ec2 = AWS::EC2.new()
instance = ec2.instances[instance_id]

Java

import com.amazonaws.util.EC2MetadataUtils;
String myId = EC2MetadataUtils.getInstanceId();

Scala

import com.amazonaws.util.EC2MetadataUtils
val myid = EC2MetadataUtils.getInstanceId

Go

import ("github.com/mitchellh/goamz/aws")
idBytes, err := aws.GetMetaData("instance-id")
id = string(idBytes)

PHP

$instance = json_decode(file_get_contents(
'http://169.254.169.254/latest/dynamic/instance-identity/document'),true);
$id = $instance['instanceId'];
print_r($instance);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.