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


当前回答

类型:

ec2metadata --instance-id

其他回答

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

对于。net用户:

string instanceId = new StreamReader(
      HttpWebRequest.Create("http://169.254.169.254/latest/meta-data/instance-id")
      .GetResponse().GetResponseStream())
    .ReadToEnd();

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

动机:用户想检索aws实例元数据。

解决方案: IP地址169.254.169.254是一个链接本地地址(仅对实例有效)aws为我们提供了用于检索运行实例的元数据的专用Restful API的链接(注意,用于检索实例元数据和用户数据的HTTP请求不会收费)。其他文件

例子:

//Request:
curl http://169.254.169.254/latest/meta-data/instance-id

//Response
ami-123abc

你可以使用这个链接http://169.254.169.254/latest/meta-data/<metadata-field>获得你实例的额外元数据标签,只需选择正确的标签:

ami id ami-launch-index ami-manifest-path 块设备 映射 事件 冬眠 主机名 我 身份凭证 instance-action 实例id 实例类型 local-hostname local-ipv4 mac 指标 网络 放置 配置文件 预订标识 安全组 服务