使用第 3 AWS SDK for PHP 版管理 Amazon EC2 執行個體 - AWS SDK for PHP

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

使用第 3 AWS SDK for PHP 版管理 Amazon EC2 執行個體

下列範例示範如何:

所有的範例程式碼都可以AWS SDK for PHP在這裡取得 GitHub。

登入資料

在執行範例程式碼之前,請依照中的說明設定您的AWS認證憑證。然後匯入AWS SDK for PHP,如中所述基本使用

描述執行個體

匯入

require 'vendor/autoload.php'; use Aws\Ec2\Ec2Client;

範例程式碼

$ec2Client = new Aws\Ec2\Ec2Client([ 'region' => 'us-west-2', 'version' => '2016-11-15', 'profile' => 'default' ]); $result = $ec2Client->describeInstances(); echo "Instances: \n"; foreach ($result['Reservations'] as $reservation) { foreach ($reservation['Instances'] as $instance) { echo "InstanceId: {$instance['InstanceId']} - {$instance['State']['Name']} \n"; } }

啟用和停用監視

匯入

require 'vendor/autoload.php';

範例程式碼

$ec2Client = new Aws\Ec2\Ec2Client([ 'region' => 'us-west-2', 'version' => '2016-11-15', 'profile' => 'default' ]); $instanceIds = ['InstanceID1', 'InstanceID2']; $monitorInstance = 'ON'; if ($monitorInstance == 'ON') { $result = $ec2Client->monitorInstances([ 'InstanceIds' => $instanceIds ]); } else { $result = $ec2Client->unmonitorInstances([ 'InstanceIds' => $instanceIds ]); } var_dump($result);

啟動及停止 執行個體

匯入

require 'vendor/autoload.php';

範例程式碼

$ec2Client = new Aws\Ec2\Ec2Client([ 'region' => 'us-west-2', 'version' => '2016-11-15', 'profile' => 'default' ]); $action = 'START'; $instanceIds = ['InstanceID1', 'InstanceID2']; if ($action == 'START') { $result = $ec2Client->startInstances([ 'InstanceIds' => $instanceIds, ]); } else { $result = $ec2Client->stopInstances([ 'InstanceIds' => $instanceIds, ]); } var_dump($result);

重新啟動執行個體

匯入

require 'vendor/autoload.php';

範例程式碼

$ec2Client = new Aws\Ec2\Ec2Client([ 'region' => 'us-west-2', 'version' => '2016-11-15', 'profile' => 'default' ]); $instanceIds = ['InstanceID1', 'InstanceID2']; $result = $ec2Client->rebootInstances([ 'InstanceIds' => $instanceIds ]); var_dump($result);