如何从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,这取决于您的平台上安装了什么。

其他回答

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

所有与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

如果你想在python中获取所有实例id列表,下面是代码:

import boto3

ec2=boto3.client('ec2')
instance_information = ec2.describe_instances()

for reservation in instance_information['Reservations']:
   for instance in reservation['Instances']:
      print(instance['InstanceId'])

运行这个:

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

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

使用此链接查看更多信息

一个更现代的解决方案。

在Amazon Linux中已经安装了ec2-metadata命令。

从终点站

ec2-metadata -help

会给你可用的选项吗

ec2-metadata -i

将返回

instance-id: yourid