简体   繁体   中英

Can two EC2 instances have the same $_SERVER['SERVER_ADDR']? Or how to uniquely identify each, in EC2?

I need a unique identifier for each EC2 instance of my scaling group on AWS for a prefix for uniqid() .

Can I use $_SERVER['SERVER_ADDR'] for this?

The following code can fetch the instance id of your ec2 instance:

#!/usr/bin/php
<?php
$instance_id = file_get_contents("http://instance-data/latest/meta-data/instance-id");
echo $instance_id;
?>

The instance ID from the ec2 metadata is a good answer, but stashing its value in the environment seems like a cleaner solution.

Wherever you set environment variables in your setup -- in the startup script for the web server itself (one example, not universally applicable, would be /etc/init.d/apache2 ), fetch the value and store it in the environment.

export EC2_INSTANCE_ID=$(ec2metadata --instance-id)

$_ENV["EC2_INSTANCE_ID"] should then contain the value, much less tedious than caching it in a file, and not subject to rate limiting (which is documented as being imposed, but without specific thresholds being mentioned).


Note that the following three examples for fetching the instance ID are functionally equivalent:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM