Get Amazon EC2 Instance ID via PHP Get Amazon EC2 Instance ID via PHP curl curl

Get Amazon EC2 Instance ID via PHP


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";?>


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 0if (empty($instance_id)) {    $instance_id = 0;}echo $instance_id;


If you can get the instance id via the command line, you can get the results of the latter in PHP using the PHP's exec function. When you get the result, just echo it.

$instance_id = exec([your command here]);echo $instance_id;

Alternatively, after reading the post you linked to, you can also do it this way:

$instance_id = file_get_contents(     "http://169.254.169.254/latest/meta-data/instance-id");echo $instance_id;