2

I have 2 Instance in AWS EC2 and I want check request by Instance id.

require_once 'vendor/autoload.php';

use Aws\Ec2\Ec2Client;
use Aws\Rds\RdsClient;
$instance_id = $ec2->describeInstances();

if($instance_id == 'i0-jkedsf54325123' || $instance_id == 'i0-jkedsf543251321'){
    echo "request instance id is allow";
}else{ 
    echo "request not allow";
}

Need to check which instance request is coming.

Praveen Kumar
  • 864
  • 2
  • 9
  • 33
  • Could you please clarify what you mean by "check request by Instance id" and "check which instance request is coming"? Are you saying that your PHP code is running on an instance and you want to know the ID of that instance? What is `i0-jkedsf54325123`? That doesn't look like a normal instance ID, which should start with `i-`. โ€“ John Rotenstein Jun 10 '18 at 05:24
  • @JohnRotenstein :- I have elb(load balance) with 3 Instance. I want to identify request. If I call my web URL :-www.abc.com than is call from 1 first than I got Instance ID "i-0156485DF12" if call from 2 Instance than got "i-0156485DF13". - Are you saying that your PHP code is running on an instance and you want to know the ID of that instance? - yes โ€“ Praveen Kumar Jun 10 '18 at 05:26
  • @JohnRotenstein :- "which should start with `i-` " Yes, In my question I put as simple example. โ€“ Praveen Kumar Jun 10 '18 at 05:36

1 Answers1

6

If you wish to find the Instance ID on which some code is running, you can access the Instance Metadata.

To do it from PHP, use (from Get Amazon AWS Instance ID (PHP / wget) ยท GitHub):

<?php
//---------------------------------------------------------------------------------
// You can get the metadata for an AWS instance by loading the following URL
// Note: This URL must be loaded from an AWS instance
//
//---------------------------------------------------------------------------------
// URL:
//      http://169.254.169.254/latest/meta-data/instance-id
//
//---------------------------------------------------------------------------------
// wget:
//      wget -q -O - http://169.254.169.254/latest/meta-data/instance-id
//
//---------------------------------------------------------------------------------

echo @file_get_contents("http://instance-data/latest/meta-data/instance-id");

?>
John Rotenstein
  • 241,921
  • 22
  • 380
  • 470