如何从ec2实例中找到ec2实例的实例id ?
当前回答
在AWS Linux上:
Ec2-metadata——instance-id | cut -d " " -f
输出:
i - 33400429
在变量中使用:
ec2InstanceId=$(ec2-metadata --instance-id | cut -d " " -f 2);
ls "log/${ec2InstanceId}/";
其他回答
在围棋中,你可以使用goamz包。
import (
"github.com/mitchellh/goamz/aws"
"log"
)
func getId() (id string) {
idBytes, err := aws.GetMetaData("instance-id")
if err != nil {
log.Fatalf("Error getting instance-id: %v.", err)
}
id = string(idBytes)
return id
}
下面是GetMetaData源代码。
对于。net用户:
string instanceId = new StreamReader(
HttpWebRequest.Create("http://169.254.169.254/latest/meta-data/instance-id")
.GetResponse().GetResponseStream())
.ReadToEnd();
Ruby:
require 'rubygems'
require 'aws-sdk'
require 'net/http'
metadata_endpoint = 'http://169.254.169.254/latest/meta-data/'
instance_id = Net::HTTP.get( URI.parse( metadata_endpoint + 'instance-id' ) )
ec2 = AWS::EC2.new()
instance = ec2.instances[instance_id]
PHP:
$instance = json_decode(file_get_contents('http://169.254.169.254/latest/dynamic/instance-identity/document));
$id = $instance['instanceId'];
编辑@John
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()
推荐文章
- 亚马逊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 -由于“没有基本的身份验证凭据”而失败