flybywire
flybywire

Reputation: 273422

How to get an AWS EC2 instance ID from within that EC2 instance?

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

Upvotes: 483

Views: 341872

Answers (30)

Riz
Riz

Reputation: 1167

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

won't work if you are using V2 of the meta data service(IMDSv2). For V2, you need to get a an authentication token first to get authenticated, otherwise you will get an error like

HTTP request sent, awaiting response... 401 Unauthorized
Username/Password Authentication Failed   

To get the instance id, you can run

TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`

and then use this token in your request.

curl http://169.254.169.254/latest/meta-data/instance-id -H "X-aws-ec2-metadata-token: $TOKEN"

Upvotes: 1

Lakshmikandan
Lakshmikandan

Reputation: 4619

TOKEN=`curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` 

AMI=`curl -H "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/ami-id`

echo $AMI

This should helps you,

Upvotes: 1

qoomon
qoomon

Reputation: 5298

Most simple approach is to use aws cli and sts get-caller-identity.

INSTANCE_ID=$(aws sts get-caller-identity --query UserId --output text | cut -d : -f 2)

  • This way you don't need to authorize against metadata endpoint manually.
  • It works on any unix AMI in contrast to ec2-metadata command that is only available for amazon linux AMIs

Upvotes: 3

Omer
Omer

Reputation: 3466

Simple one line

cat /sys/devices/virtual/dmi/id/board_asset_tag

or

curl_cli -s http://169.254.169.254/latest/meta-data/instance-id

source: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/identify_ec2_instances.html

Upvotes: 6

dgc
dgc

Reputation: 565

FWIW I wrote a FUSE filesystem to provide access to the EC2 metadata service: https://github.com/xdgc/ec2mdfs . I run this on all custom AMIs; it allows me to use this idiom: cat /ec2/meta-data/ami-id

Upvotes: 3

Noah Shay
Noah Shay

Reputation: 44

For .NET code it is very simple: var instanceId=Amazon.Util.EC2InstanceMetadata.InstanceId

Upvotes: 0

vladr
vladr

Reputation: 66661

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.

Upvotes: 651

Aviv
Aviv

Reputation: 14467

Motivation: User would like to Retrieve aws instance metadata.

Solution: The IP address 169.254.169.254 is a link-local address (and is valid only from the instance) aws gives us link with dedicated Restful API for Retrieving metadata of our running instance (Note that you are not billed for HTTP requests used to retrieve instance metadata and user data) . for Additional Documentation

Example:

//Request:
curl http://169.254.169.254/latest/meta-data/instance-id

//Response
ami-123abc

You able to get additional metadata labels of your instance using this link http://169.254.169.254/latest/meta-data/<metadata-field> just choose the right tags:

  1. ami-id
  2. ami-launch-index
  3. ami-manifest-path
  4. block-device
  5. mapping
  6. events
  7. hibernation
  8. hostname
  9. iam
  10. identity-credentials
  11. instance-action
  12. instance-id
  13. instance-type
  14. local-hostname
  15. local-ipv4
  16. mac
  17. metrics
  18. network
  19. placement
  20. profile
  21. reservation-id
  22. security-groups
  23. services

Upvotes: 2

Vikas Satpute
Vikas Satpute

Reputation: 174

If you wish to get the all instances id list in python here is the code:

import boto3

ec2=boto3.client('ec2')
instance_information = ec2.describe_instances()

for reservation in instance_information['Reservations']:
   for instance in reservation['Instances']:
      print(instance['InstanceId'])

Upvotes: 4

user2584621
user2584621

Reputation: 2713

For AWS elastic beanstalk eb cli run eb tags --list

Upvotes: 0

Kappacake
Kappacake

Reputation: 1937

For a Windows instance:

(wget http://169.254.169.254/latest/meta-data/instance-id).Content

or

(ConvertFrom-Json (wget http://169.254.169.254/latest/dynamic/instance-identity/document).Content).instanceId

Upvotes: 1

Soumya Ranjan Mohanty
Soumya Ranjan Mohanty

Reputation: 41

To get the instance metadata use

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

Upvotes: 1

Vipin Sharma
Vipin Sharma

Reputation: 107

All meta-data related to EC2 resource can be accessed by the EC2 instance itself with the help of the following command being executed:

CURL :

http://169.254.169.254/<api-version>/meta-data/<metadata-requested>

For your case: "metadata-requested" should be instance-id , "api-version" is usually latest that can be used.

Additional Note: You can also get information related to below EC2 attributes using the above command.

ami-id, ami-launch-index, ami-manifest-path, block-device-mapping/, hostname, iam/, instance-action, instance-id, instance-type, local-hostname, local-ipv4, mac, metrics/, network/, placement/, profile, public-hostname, public-ipv4, public-keys/, reservation-id, security-groups, services/,

For more details please follow this link : https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html

Upvotes: 0

Remigiusz
Remigiusz

Reputation: 470

You can also install awscli and use it to get all the info you wish:

AWS_DEFAULT_REGION=your-region aws ec2 describe-instances

You'll get lots of output so be sure to grep by your idetifier such as ip and print some more lines:

AWS_DEFAULT_REGION=your-region aws ec2 describe-instances | grep your-ip -A 10 | grep InstanceId

Upvotes: -2

Chinthaka Hasakelum
Chinthaka Hasakelum

Reputation: 171

Run this:

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

You will be able to see different types of attributes which are provided by aws.

Use this link to view more

Upvotes: 0

James
James

Reputation: 25513

On Amazon Linux AMIs you can do:

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

Or, on Ubuntu and some other linux flavours, ec2metadata --instance-id (This command may not be installed by default on ubuntu, but you can add it with sudo apt-get install cloud-utils)

As its name suggests, you can use the command to get other useful metadata too.

Upvotes: 227

Beachhouse
Beachhouse

Reputation: 5052

For PHP:

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

Edit per @John

Upvotes: 0

John
John

Reputation: 7826

Alternative approach for PHP:

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

That will provide a lot of data about the instance, all nicely packed in an array, no external dependencies. As it's a request that never failed or delayed for me it should be safe to do it that way, otherwise I'd go for curl()

Upvotes: 0

Konrad Kiss
Konrad Kiss

Reputation: 6877

Use the /dynamic/instance-identity/document URL if you also need to query more than just your instance ID.

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

This will get you JSON data such as this - with only a single request.

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

Upvotes: 68

Aman
Aman

Reputation: 1004

For all ec2 machines, the instance-id can be found in file:

    /var/lib/cloud/data/instance-id

You can also get instance id by running the following command:

    ec2metadata --instance-id

Upvotes: 58

In the question you have mentioned the user as root, one thing I should mention is that the instance ID is not dependent on the user.

For Node developers,

var meta  = new AWS.MetadataService();

meta.request("/latest/meta-data/instance-id", function(err, data){
    console.log(data);
});

Upvotes: 1

greg
greg

Reputation: 3495

Simply check the var/lib/cloud/instance symlink, it should point to /var/lib/cloud/instances/{instance-id} where {instance_id} is your instance-id.

Upvotes: 7

Sarat Chandra
Sarat Chandra

Reputation: 6120

You can just make a HTTP request to GET any Metadata by passing the your metadata parameters.

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

or

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

You won't be billed for HTTP requests to get Metadata and Userdata.

Else

You can use EC2 Instance Metadata Query Tool which is a simple bash script that uses curl to query the EC2 instance Metadata from within a running EC2 instance as mentioned in documentation.

Download the tool:

$ wget http://s3.amazonaws.com/ec2metadata/ec2-metadata

now run command to get required data.

$ec2metadata -i

Refer:

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html

https://aws.amazon.com/items/1825?externalID=1825

Happy To Help.. :)

Upvotes: 4

Scott Smith
Scott Smith

Reputation: 1020

The latest Java SDK has EC2MetadataUtils:

In Java:

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

In Scala:

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

Upvotes: 10

Mehdi LAMRANI
Mehdi LAMRANI

Reputation: 11597

For .NET People :

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

Upvotes: 27

Akash Arya
Akash Arya

Reputation: 149

Just Type:

ec2metadata --instance-id

Upvotes: 13

DetDev
DetDev

Reputation: 319

A more contemporary solution.

From Amazon Linux the ec2-metadata command is already installed.

From the terminal

ec2-metadata -help

Will give you the available options

ec2-metadata -i

will return

instance-id: yourid

Upvotes: 12

Medical physicist
Medical physicist

Reputation: 2594

For C++ (using cURL):

    #include <curl/curl.h>

    //// cURL to string
    size_t curl_to_str(void *contents, size_t size, size_t nmemb, void *userp) {
        ((std::string*)userp)->append((char*)contents, size * nmemb);
        return size * nmemb;
    };

    //// Read Instance-id 
    curl_global_init(CURL_GLOBAL_ALL); // Initialize cURL
    CURL *curl; // cURL handler
    CURLcode res_code; // Result
    string response;
    curl = curl_easy_init(); // Initialize handler
    curl_easy_setopt(curl, CURLOPT_URL, "http://169.254.169.254/latest/meta-data/instance-id");
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curl_to_str);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
    res_code = curl_easy_perform(curl); // Perform cURL
    if (res_code != CURLE_OK) { }; // Error
    curl_easy_cleanup(curl); // Cleanup handler
    curl_global_cleanup(); // Cleanup cURL

Upvotes: 5

Kevin Meyer
Kevin Meyer

Reputation: 2966

For 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]

Upvotes: 10

dmikalova
dmikalova

Reputation: 464

In Go you can use the goamz package.

import (
    "github.com/mitchellh/goamz/aws"
    "log"
)

func getId() (id string) {
    idBytes, err := aws.GetMetaData("instance-id")
    if err != nil {
        log.Fatalf("Error getting instance-id: %v.", err)
    }

    id = string(idBytes)

    return id
}

Here's the GetMetaData source.

Upvotes: 3

Related Questions