Creating & Deleting Amazon RDS MySQL Instances – AWS SDK & PHP

30 Jan

I have to sometimes automatically stand up (create) and shut down temporary MySQL instances in order to run some scripts and commands on them. Instead of having to keep an instance running forever, I was able to make sure of Amazon’s RDS service for cloud MySQL instances, using its AWS SDK in PHP.I was able to use the excellent AWS SDK in PHP for setting up and shutting down the temporary MySQL servers. Some notes about this code:

  • It assumes you already have AWS SDK for PHP set up and configured correctly.
  • Make sure your AWS credentials for the SDK are correctly set up.
<?php
/**
 * Author: Suman Srinivasan
 * Date: January 30, 2012
 */
// The directory where you have the AWS credentials set up
putenv('HOME=/home/username');
require_once 'AWSSDKforPHP/sdk.class.php';
require_once 'AWSSDKforPHP/services/rds.class.php';

// Sleep time in seconds, to give RDS time to start up
$sleepSecs = 90;

// Specify DB variables
$username = "user";
$password = "pass";
$dbType = "db.m1.small";

// Change this to a specific string if you prefer
$dbId = genRandomString();		
// Output RDS ID
echo "RDS ID for this instance: $dbId\n";

// Create the RDS class instance
$rds = new AmazonRDS();

// Set the security group for this
// Allows current host to access the RDS instance
echo "Creating security settings...\n";
$myIp = gethostbyname (gethostname());
$rds->create_db_security_group($dbId, "Allow $myIp access to $dbId");
$rds->authorize_db_security_group_ingress($dbId, array(
	"CIDRIP" => "$myIp/32"
));

// Create the RDS instance
echo "Creating RDS instance...\n";
$rds->create_db_instance ($dbId, 5, "$dbType", "MySQL", $username, $password, 
	array("DBSecurityGroups" => $dbId)
);

// Try to get the details for instance from Amazon AWS
echo "Trying to get RDS info...\n";
$result = array();
$currentStatus = "";
while (strcmp($currentStatus, "available") != 0) {
	// If not available, sleep for some time
	echo "RDS instance not available yet. Waiting $sleepSecs seconds...\n";
	sleep($sleepSecs);
	// Try again
	$result = $rds->describe_db_instances(array(
		"DBInstanceIdentifier" => $dbId,
	));
	$currentStatus = $result->body->DescribeDBInstancesResult->DBInstances->DBInstance->DBInstanceStatus;
}

// Get the hostname
$hostname = $result->body->DescribeDBInstancesResult->DBInstances->DBInstance->Endpoint->Address;
echo "RDS instance created...\n";
echo "Hostname: $hostname\n";

$con = mysql_connect($hostname, $username, $password);
// ...
// Do whatever with the RDS and $con
// Run mysql_query(), etc
// ...
mysql_close ($con);

// Delete the DB instance
echo "Deleting security settings...\n";
$rds->delete_db_security_group($dbId);
echo "Deleting RDS instance...\n";
$rds->delete_db_instance($dbId, array(
	// *No* final snapshot, since this is a temp DB
	"SkipFinalSnapshot" => true
));

// Generate random string
// code from: http://www.lost-in-code.com/programming/php-code/php-random-string-with-numbers-and-letters/
// modified slightly
function genRandomString() {
    $length = 10;
    $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
    $string = "";  
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters)-1)];
    }
    return $string;
}
?>
Advertisements

3 Responses to “Creating & Deleting Amazon RDS MySQL Instances – AWS SDK & PHP”

  1. John September 4, 2012 at 1:50 pm #

    Your article title in incorrect. You are deleting the instance, not shutting down.

    • sumanrs September 4, 2012 at 10:34 pm #

      Yup, you’re right, sorry about that. Edited.

  2. Shalin June 13, 2016 at 4:41 am #

    Hi Sumanrs, Where can I find some aws examples other than from this diagram community ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: