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


当前回答

在Ubuntu上你可以:

sudo apt-get install cloud-utils

然后你就可以:

EC2_INSTANCE_ID=$(ec2metadata --instance-id)

你可以通过这种方式获取大多数与实例相关的元数据:

ec2metadata --help
Syntax: /usr/bin/ec2metadata [options]

Query and display EC2 metadata.

If no options are provided, all options will be displayed

Options:
    -h --help               show this help

    --kernel-id             display the kernel id
    --ramdisk-id            display the ramdisk id
    --reservation-id        display the reservation id

    --ami-id                display the ami id
    --ami-launch-index      display the ami launch index
    --ami-manifest-path     display the ami manifest path
    --ancestor-ami-ids      display the ami ancestor id
    --product-codes         display the ami associated product codes
    --availability-zone     display the ami placement zone

    --instance-id           display the instance id
    --instance-type         display the instance type

    --local-hostname        display the local hostname
    --public-hostname       display the public hostname

    --local-ipv4            display the local ipv4 ip address
    --public-ipv4           display the public ipv4 ip address

    --block-device-mapping  display the block device id
    --security-groups       display the security groups

    --mac                   display the instance mac address
    --profile               display the instance profile
    --instance-action       display the instance-action

    --public-keys           display the openssh public keys
    --user-data             display the user data (not actually metadata)

其他回答

你可以试试这个:

#!/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]\)"`

一个更现代的解决方案。

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

从终点站

ec2-metadata -help

会给你可用的选项吗

ec2-metadata -i

将返回

instance-id: yourid

请参阅这篇文章-注意URL中给出的IP地址是常量(这一开始让我感到困惑),但返回的数据是特定于您的实例的。

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