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

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

The following examples show how to:

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

Credentials

Before running the example code, configure your AWS credentials, as described in Credentials. Then import the AWS 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);