How to get the instance id from within an ec2 inst

2019-01-01 16:27发布

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

27条回答
无与为乐者.
2楼-- · 2019-01-01 16:59

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
查看更多
怪性笑人.
3楼-- · 2019-01-01 17:00

For Python:

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

which boils down to the one-liner:

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

Instead of local_hostname you could also use public_hostname, or:

boto.utils.get_instance_metadata()['placement']['availability-zone'][:-1]
查看更多
只靠听说
4楼-- · 2019-01-01 17:01

on AWS Linux:

ec2-metadata --instance-id | cut -d " " -f 2

Output:

i-33400429

Using in variables:

ec2InstanceId=$(ec2-metadata --instance-id | cut -d " " -f 2);
ls "log/${ec2InstanceId}/";
查看更多
零度萤火
5楼-- · 2019-01-01 17:02

If you wish to get the all available instance id list using 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'])
查看更多
泛滥B
6楼-- · 2019-01-01 17:02

To get the instance metadata use

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

查看更多
呛了眼睛熬了心
7楼-- · 2019-01-01 17:04

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.

查看更多
登录 后发表回答