Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Amazon EC2 Instance ID via PHP

I'm looking to create a PHP script that will echo the unique ID of an Amazon EC2 instance. Anyone know how to do this?

Found a way via command line: http://af-design.com/blog/2010/07/27/testing-your-aws-elastic-load-balancer/

Can I just use PHP w/ CURL to submit the query?

like image 939
Trent Scott Avatar asked Oct 02 '11 01:10

Trent Scott


People also ask

Is ec2 instance ID unique?

Your instance IDs are globally unique, for as long as you have access to the resource.


2 Answers

If the entire goal of your PHP script is to run another command, why not just run the other command directly? Why wrap it in PHP?

If you need to use PHP for some reason (e.g., to do something with the instance id other than to echo it out, you could improve performance by using PHP's built in HTTP ability instead of running another process:

#!/usr/bin/php
<?php
$instance_id = file_get_contents("http://instance-data/latest/meta-data/instance-id");
echo $instance_id, "\n";
?>
like image 125
Eric Hammond Avatar answered Sep 30 '22 04:09

Eric Hammond


You can use shell_exec to get the instance-id if you are using Amazon Linux AMI.

$instance_id = shell_exec('ec2-metadata --instance-id 2> /dev/null | cut -d " " -f 2');
// if its not set make it 0
if (empty($instance_id)) {
    $instance_id = 0;
}
echo $instance_id;
like image 26
Tegan Snyder Avatar answered Sep 30 '22 05:09

Tegan Snyder