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


当前回答

最新的Java SDK有EC2MetadataUtils:

在Java中:

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

在Scala中:

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

其他回答

运行这个:

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

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

使用此链接查看更多信息

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()

对于AWS elastic beanstalk eb cli,请执行eb tags——list

Python:

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

这可以归结为一句话:

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

除了local_hostname,你还可以使用public_hostname,或者:

boto.utils.get_instance_metadata()['placement']['availability-zone'][:-1]

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