如何从ec2实例中找到ec2实例的实例id ?
当前回答
请参阅有关该主题的EC2文档。
Run:
wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
如果您需要从脚本中编程访问实例ID,
die() { status=$1; shift; echo "FATAL: $*"; exit $status; }
EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id || die \"wget instance-id has failed: $?\"`"
下面是一个更高级的使用示例(检索实例ID以及可用性区域和区域等):
EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id || die \"wget instance-id has failed: $?\"`"
test -n "$EC2_INSTANCE_ID" || die 'cannot obtain instance-id'
EC2_AVAIL_ZONE="`wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone || die \"wget availability-zone has failed: $?\"`"
test -n "$EC2_AVAIL_ZONE" || die 'cannot obtain availability-zone'
EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"
您也可以使用curl而不是wget,这取决于您的平台上安装了什么。
其他回答
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]
对于所有ec2机器,实例id可以在以下文件中找到:
/var/lib/cloud/data/instance-id
实例id也可以通过如下命令获取:
ec2metadata --instance-id
你可以试试这个:
#!/bin/bash
aws_instance=$(wget -q -O- http://169.254.169.254/latest/meta-data/instance-id)
aws_region=$(wget -q -O- http://169.254.169.254/latest/meta-data/hostname)
aws_region=${aws_region#*.}
aws_region=${aws_region%%.*}
aws_zone=`ec2-describe-instances $aws_instance --region $aws_region`
aws_zone=`expr match "$aws_zone" ".*\($aws_region[a-z]\)"`
在围棋中,你可以使用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();
推荐文章
- 如何重命名AWS S3 Bucket
- AWS ECS中的任务和服务之间有什么区别?
- 亚马逊SimpleDB vs亚马逊DynamoDB
- 亚马逊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配置文件