How to get the instance id from within an ec2 instance?
如何从ec2实例中找出ec2实例的instance id
?
See the EC2 documentation on the subject.
Run:
wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
If you need programatic 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: $?"`"
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:'`"
You may also use curl
instead of wget
, depending on what is installed on your platform.
On Amazon Linux AMIs you can do:
$ ec2-metadata -i
instance-id: i-1234567890abcdef0
Or, on Ubuntu and some other linux flavours, ec2metadata --instance-id
(This command may not be installed by default on ubuntu, but you can add it with sudo apt-get install cloud-utils
)
As its name suggests, you can use the command to get other useful metadata too.
On Ubuntu you can:
sudo apt-get install cloud-utils
And then you can:
EC2_INSTANCE_ID=$(ec2metadata --instance-id)
You can get most of the metadata associated with the instance this way:
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)链接地址: http://www.djcxy.com/p/32430.html
上一篇: EC2上的“停止”实例是否收费?
下一篇: 如何从ec2实例中获取实例ID?