如何从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
推荐文章
- 亚马逊ECS和亚马逊EC2有什么区别?
- 我如何知道我在S3桶中存储了多少对象?
- S3 Bucket操作不应用于任何资源
- 将AWS凭证传递给Docker容器的最佳方法是什么?
- 当权限为S3时,AccessDenied for ListObjects for S3 bucket:*
- 电子邮件地址未验证(AWS SES)
- 使用Boto3将S3对象作为字符串打开
- AWS VPC - Internet网关vs. NAT
- 如何在AWS Lambda中加载npm模块?
- 亚马逊S3 -如何修复“我们计算的请求签名与签名不匹配”错误?
- 警告:未受保护的私钥文件!当尝试SSH到Amazon EC2实例时
- 使用boto3连接CloudFront时,如何选择AWS配置文件
- 在亚马逊云服务器上设置FTP
- 使用scp将文件复制到Amazon EC2实例?
- 无法将图像推送到Amazon ECR -由于“没有基本的身份验证凭据”而失败