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


当前回答

Ruby:

require 'rubygems'
require 'aws-sdk'
require 'net/http'

metadata_endpoint = 'http://169.254.169.254/latest/meta-data/'
instance_id = Net::HTTP.get( URI.parse( metadata_endpoint + 'instance-id' ) )

ec2 = AWS::EC2.new()
instance = ec2.instances[instance_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,这取决于您的平台上安装了什么。

对于Windows实例:

(wget http://169.254.169.254/latest/meta-data/instance-id).Content

or

(ConvertFrom-Json (wget http://169.254.169.254/latest/dynamic/instance-identity/document).Content).instanceId

对于AWS elastic beanstalk eb cli,请执行eb tags——list

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

PHP:

$instance = json_decode(file_get_contents('http://169.254.169.254/latest/dynamic/instance-identity/document));
$id = $instance['instanceId'];

编辑@John