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

Pra*_*mar 1 php amazon-ec2 amazon-web-services 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";
}
Run Code Online (Sandbox Code Playgroud)

需要检查哪个实例请求即将到来。

Joh*_*ein 5

如果您希望找到运行某些代码的实例ID,则可以访问实例元数据

要通过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");

?>
Run Code Online (Sandbox Code Playgroud)