Managing Amazon EC2 instances using the Amazon SDK for PHP Version 3 - Amazon SDK for PHP
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China (PDF).

Managing Amazon EC2 instances using the Amazon SDK for PHP Version 3

The following examples show how to:

All the example code for the Amazon SDK for PHP is available here on GitHub.

Credentials

Before running the example code, configure your Amazon credentials, as described in Credentials. Then import the Amazon SDK for PHP, as described in Basic usage.

Describe instances

Imports

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

Sample Code

$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"; } }

Enable and disable monitoring

Imports

require 'vendor/autoload.php';

Sample Code

$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);

Start and stop an instance

Imports

require 'vendor/autoload.php';

Sample Code

$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);

Reboot an instance

Imports

require 'vendor/autoload.php';

Sample Code

$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);