Skip to content

Instantly share code, notes, and snippets.

@JonTheNiceGuy
Created June 5, 2014 20:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JonTheNiceGuy/a26b3c0072dbf470d3a3 to your computer and use it in GitHub Desktop.
Save JonTheNiceGuy/a26b3c0072dbf470d3a3 to your computer and use it in GitHub Desktop.
This code snippet lets you start an EC2 instance using the PHP SDK (and means you don't need to spin up a JVM for it)
<?php
// This code is released under a CC-Zero license
// https://creativecommons.org/publicdomain/zero/1.0/
// You need the AWS SDK - get the zip file from here:
// http://pear.amazonwebservices.com/get/aws.zip
// And then unpack it to this directory.
require dirname(__FILE__) . '/aws-autoloader.php';
// Use the Ec2Client libraries by referring just to Ec2Client
use Aws\Ec2\Ec2Client;
// Technically, at this point, nothing has "failed", but
// nothing has succeeded
$failed = true;
// Try 5 times to start the instance
for ($try = 0; $failed && $try < 5; $try++) {
try {
// Create an Ec2Client object using the credentials below
$client = Ec2Client::factory(array(
// Credentials obtained by creating a user account in:
// https://console.aws.amazon.com/iam/home?#users
// Remember to add a full admin access user policy to the user
'key' => '',
'secret' => '',
'region' => 'us-east-1'
));
// Now start the instance
$result = $client->startInstances(array(
// You must put an instance ID here
'InstanceIds' => array('')
));
$failed = false;
} catch (Exception $e) {
// If either the credentials are wrong, or EC2 has a problem
// this will tell you what has happened.
echo "Failed: " . $e->getMessage() . "\r\n";
sleep(20);
}
}
// If you've actually managed to start an instance
// this will tell you that it's started
if (!$failed) {
$arrResult = $result['StartingInstances'][0];
$was = $arrResult['PreviousState']['Name'];
$is = $arrResult['CurrentState']['Name'];
echo "Instance was: $was\r\nInstance is: $is\r\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment