如何从ec2实例中找到ec2实例的实例id ?


当前回答

类型:

ec2metadata --instance-id

其他回答

如果您还需要查询实例ID以外的其他信息,请使用/dynamic/instance-identity/document URL。

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

这将为您提供这样的JSON数据——只需要一个请求。

{
    "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"
}

对于。net用户:

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

对于c++(使用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

我写了一个FUSE文件系统来提供对EC2元数据服务的访问:https://github.com/xdgc/ec2mdfs。 我在所有自定义ami上运行这个;它允许我使用这个习语:cat /ec2/meta-data/ami-id

在Amazon Linux ami上,你可以做:

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

或者,在Ubuntu和其他一些linux版本上,ec2metadata——instance-id(这个命令可能不会在Ubuntu上默认安装,但你可以用sudo apt-get install cloud-utils添加它)

顾名思义,您也可以使用该命令获取其他有用的元数据。