Skip to content

Instantly share code, notes, and snippets.

@nicam
Created March 29, 2011 06:12
Show Gist options
  • Save nicam/891880 to your computer and use it in GitHub Desktop.
Save nicam/891880 to your computer and use it in GitHub Desktop.
This Script can be used to start / stop instances on amazon EC2
<?php
require_once 'sdk/sdk.class.php';
$hosts = array(
'linux' => array('id' => 'i-123ee456', 'ip' => '1.2.3.4'),
'windows' => array('id' => 'i-123ee457', 'ip' => '1.2.3.5'),
);
$ec2 = new AmazonEC2();
$ec2->set_region(AmazonEC2::REGION_EU_W1);
switch ($argv[1]) {
case 'start':
start($ec2, $hosts);
break;
case 'stop':
stop ($ec2, $hosts);
break;
default:
echo "Enter start or stop as parameter\n";
break;
}
function stop($ec2, $hosts) {
outPut("Going to stop ".count($hosts)." instances, please Wait...\n");
foreach ($hosts as $host) {
$response = $ec2->stop_instances($host['id']);
if (!$response->isOK()) {
outPut("Something went wrong\n");
var_dump($response);
die();
}
$stopped = false;
outPut("Waiting for ".$host['id']." to stop");
while(!$stopped) {
$response = $ec2->describe_instances(array("InstanceId" => $host['id']));
$status = (string) $response->body->reservationSet->item[0]->instancesSet->item[0]->instanceState->name;
if ((string)$status !== 'stopped') {
outPut(".");
sleep(5);
continue;
}
$stopped = true;
outPut("\nHost".$host['id']." successfully stopped\n");
}
$ec2->disassociate_address($host['ip']);
}
}
function start($ec2, $hosts) {
outPut("Going to start ".count($hosts)." instances, please Wait...\n");
foreach ($hosts as $host) {
print "\n";
if (GetPing($host['ip'])) {
outPut($host['id']." is Already online\n");
continue;
}
$response = $ec2->start_instances($host['id']);
if (!$response->isOK()) {
outPut("Something went wrong\n");
var_dump($response);
die();
}
$started = $online = false;
outPut("Waiting till ".$host['id']." is booted");
while (!$started) {
$response = $ec2->describe_instances(array("InstanceId" => $host['id']));
$status = (string) $response->body->reservationSet->item[0]->instancesSet->item[0]->instanceState->name;
if ((string)$status !== 'running') {
outPut(".");
sleep(5);
continue;
}
print "\n";
$started = true;
}
$response = $ec2->associate_address($host['id'], $host['ip']);
if (!$response->isOK()) {
outPut("Something went wrong\n");
die();
}
outPut("Waiting for ".$host['id']." to respond to pings");
while (!$online) {
if (GetPing($host['ip'])) {
print "\n";
outPut($host['id']."is now Online\n");
$online = true;
} else {
outPut(".");
sleep(5);
}
}
}
}
function GetPing($ip) {
$exec = exec("ping -c 2 -s 64 -t 64 ".$ip);
if (strpos($exec, '0 packets received') !== false) {
return false;
}
return true;
}
function outPut($str) {
print $str;
flush();
@ob_flush();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment