How to get the instance id from within an ec2 inst

2019-01-01 16:27发布

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

27条回答
情到深处是孤独
2楼-- · 2019-01-01 17:17

For powershell people:

(New-Object System.Net.WebClient).DownloadString("http://169.254.169.254/latest/meta-data/instance-id")
查看更多
泪湿衣
3楼-- · 2019-01-01 17:18

FWIW I wrote a FUSE filesystem to provide access to the EC2 metadata service: https://bitbucket.org/dgc/ec2mdfs . I run this on all custom AMIs; it allows me to use this idiom: cat /ec2/meta-data/ami-id

查看更多
高级女魔头
4楼-- · 2019-01-01 17:19

For PHP:

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

Edit per @John

查看更多
初与友歌
5楼-- · 2019-01-01 17:20

Simply check the var/lib/cloud/instance symlink, it should point to /var/lib/cloud/instances/{instance-id} where {instance_id} is your instance-id.

查看更多
心情的温度
6楼-- · 2019-01-01 17:20

You can just make a HTTP request to GET any Metadata by passing the your metadata parameters.

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

or

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

You won't be billed for HTTP requests to get Metadata and Userdata.

Else

You can use EC2 Instance Metadata Query Tool which is a simple bash script that uses curl to query the EC2 instance Metadata from within a running EC2 instance as mentioned in documentation.

Download the tool:

$ wget http://s3.amazonaws.com/ec2metadata/ec2-metadata

now run command to get required data.

$ec2metadata -i

Refer:

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html

https://aws.amazon.com/items/1825?externalID=1825

Happy To Help.. :)

查看更多
素衣白纱
7楼-- · 2019-01-01 17:21

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.

查看更多
登录 后发表回答