如何从 ec2 实例中获取实例 ID? [英] How to get the instance id from within an ec2 instance?

查看:39
本文介绍了如何从 ec2 实例中获取实例 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 ec2 实例中找出 ec2 实例的 instance id?

How can I find out the instance id of an ec2 instance from within the ec2 instance?

推荐答案

参见 有关该主题的 EC2 文档.

运行:

wget -q -O - http://169.254.169.254/latest/meta-data/instance-id

如果您需要从脚本中以编程方式访问实例 ID,

If you need programmatic access to the instance ID from within a script,

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 以及可用区和区域等):

Here is an example of a more advanced use (retrieve instance ID as well as availability zone and region, etc.):

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,具体取决于您的平台上安装的内容.

You may also use curl instead of wget, depending on what is installed on your platform.

这篇关于如何从 ec2 实例中获取实例 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆