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();

?>
  • Sajan Parikh

    Awesome! Thanks for the script.  Haven’t tried it just yet, but it looks good.  Do you know how to return the public hostname of the EC2 instance once it is started up?

  • Sajan Parikh

    Awesome! Thanks for the script.  Haven’t tried it just yet, but it looks good.  Do you know how to return the public hostname of the EC2 instance once it is started up?

    • http://blog.ianbeyer.com Ian B

      ec2-describe-instances will do it, I think. 

  • http://twitter.com/VolksWatson Ben Watson

    two questions:

    1. Is keypair necessary, or just basically a 2nd measure of security?
    2. How would I specify an AMI from the community listing on this script?

    • http://ianbeyer.com Ian Beyer

      a keypair is only necessary if you need to log into the machine.

      the AMI ID is in the string variable $ami.

Go to Top