EC2 Startup (PHP)

<?php
require_once '/usr/share/php/AWSSDKforPHP/sdk.class.php';

define('AWS_KEY', 'XXXX');
define('AWS_SECRET_KEY', 'YYYY');

$ec2 = new AmazonEC2();

$filename = "startup.zip";
$userdata = base64_encode(file_get_contents($filename));

if (filesize($filename) > 16383 ) { die('Startup package exceeeds 16KB. Please adjust and try again'); }

$startup_opts = array (
"KeyName" => 'keypair'],
"SecurityGroup" => 'security'],
"InstanceType" => 'm1.small',
"UserData" => $userdata
);

$ec2->set_region('us-east-1');

$startup_response = $ec2->run_instances($ami,1,1,$startup_opts);
if ($startup_response->status != "200") {
print_r($startup_response);
die('Error starting up.');
}

# Get instance ID
$instance_id = $startup_response->body->instancesSet->item->instanceId;

# Set instance tags
# These tags are arbitrary key/value pairs
$tags = array (
array("Key"=>'Name', "Value" => 'Name'),
array("Key"=>'Type', "Value" => 'Type'),
array("Key"=>'Client', "Value" => 'Client')
);

$tags_response = $ec2->create_tags($instance_id,$tags);
$tags_status = $tags_response->status;

if ($tags_status != "200")
{ print "Tags error : $tags_response\n"; }

# Query every few seconds and see if the instance is running yet 

print "Waiting for instance to enter running state ...";
$running = false;
while (! $running ) {
 $describe_opts = array( "InstanceId" => $instance_id);
 $response = $ec2->describe_instances($describe_opts);

 $state = $response->body->reservationSet->item->instancesSet->item->instanceState->name;

 if ($state == 'running') {
  $running = TRUE;
  #print "Complete.\n";
 }
 else {
  #print ".";
  sleep (5);
 }

}

# Optionally associate Elastic IP
$elastic_ip = '1.2.3.4';
$ip_response = $ec2->associate_address($instance_id,$elastic_ip);
if ($ip_response->status != "200") {print "IP Address allocation error"; }
flush();

?>