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


当前回答

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文档。

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

简单的一行

猫/ sys /设备/虚拟/ dmi / id / board_asset_tag

or

Curl_cli -s http://169.254.169.254/latest/meta-data/instance-id

来源:https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/identify_ec2_instances.html

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

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