如何在PHP中获取AWS EC2实例ID

时间:2018-06-09 11:15:16

标签: php amazon-web-services amazon-ec2 aws-sdk

我在AWS EC2中有2个实例,我希望通过实例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";
}

需要检查哪个实例请求即将发布。

1 个答案:

答案 0 :(得分:4)

如果您希望找到运行某些代码的实例ID,您可以访问Instance Metadata

要从PHP执行此操作,请使用(来自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");

?>