Managing Amazon EC2 Instances

The examples below 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.

Describe Instances

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

$ec2Client = new Ec2Client([
    'region' => 'us-west-2',
    'version' => '2016-11-15',
    'profile' => 'default'
]);
$result = $ec2Client->describeInstances();
var_dump($result);

Enable and Disable Monitoring

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

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

Start and Stop an Instance

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

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

Reboot an Instances

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

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