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


当前回答

对于所有ec2机器,实例id可以在以下文件中找到:

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

实例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"
}

对于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

在AWS Linux上:

Ec2-metadata——instance-id | cut -d " " -f

输出:

i - 33400429

在变量中使用:

ec2InstanceId=$(ec2-metadata --instance-id | cut -d " " -f 2);
ls "log/${ec2InstanceId}/";

动机:用户想检索aws实例元数据。

解决方案: IP地址169.254.169.254是一个链接本地地址(仅对实例有效)aws为我们提供了用于检索运行实例的元数据的专用Restful API的链接(注意,用于检索实例元数据和用户数据的HTTP请求不会收费)。其他文件

例子:

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

//Response
ami-123abc

你可以使用这个链接http://169.254.169.254/latest/meta-data/<metadata-field>获得你实例的额外元数据标签,只需选择正确的标签:

ami id ami-launch-index ami-manifest-path 块设备 映射 事件 冬眠 主机名 我 身份凭证 instance-action 实例id 实例类型 local-hostname local-ipv4 mac 指标 网络 放置 配置文件 预订标识 安全组 服务

你也可以安装awscli并使用它来获得你想要的所有信息:

AWS_DEFAULT_REGION=your-region aws ec2 describe-instances

你会得到很多输出,所以一定要通过你的标识符grep,如ip,并打印更多的行:

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