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


当前回答

PHP的替代方法:

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

这将提供大量关于实例的数据,所有数据都很好地打包在一个数组中,没有外部依赖。 因为这是一个从未失败或延迟的请求,所以这样做应该是安全的,否则我将使用curl()

其他回答

您可以通过传递元数据参数发出HTTP请求来获取任何元数据。

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

您不会为获取元数据和用户数据的HTTP请求收费。

Else

您可以使用EC2实例元数据查询工具,这是一个简单的bash脚本,它使用curl从文档中提到的正在运行的EC2实例中查询EC2实例元数据。

下载工具:

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

现在运行命令获取所需的数据。

$ec2metadata -i

参考:

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

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

乐意帮忙。:)

所有与EC2资源相关的元数据都可以由EC2实例本身通过执行以下命令来访问:

旋度:

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

对于您的情况:"metadata-requested"应该是instance-id, "api-version"通常是可以使用的最新版本。

附加注意:您还可以使用上述命令获取与以下EC2属性相关的信息。

ami id, ami-launch-index, ami-manifest-path, block-device-mapping /, 主机名、 我/, instance-action, 实例id, 实例类型, local-hostname, local-ipv4, mac, 指标/, 网络/, 位置/, 配置文件, public-hostname, public-ipv4, 公钥/, 预订标识, 安全组, 服务/

欲了解更多详情,请点击此链接:https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html

简单的一行

猫/ sys /设备/虚拟/ dmi / id / board_asset_tag

or

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

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

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

运行这个:

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

您将能够看到aws提供的不同类型的属性。

使用此链接查看更多信息