To watch out server instance running time is a bit annoying when using Amazon Server. In this quick post, I would like to introduce some approaches to automatically start and stop Amazon Instance programmatically.
When searching in Google, you may often find yourself getting more result for using Amazon Auto Scaling Groups or Amazon command line tools that can be used to interact with Amazon server instance. However, we can also write some simple script by using AWS SDK available in both PHP and JAVA. Here I will have an example used in old version AWS SDK in PHP.
The old version in PHP is available in Github: https://github.com/amazonwebservices/aws-sdk-for-php
To use such library to start/stop instance is very easy. First of all, make sure you obtain your Amazon Web Service / Secret Key in the AWS Security Credentials (Not sure what it is, then google it). Once Amazon Web Service / Secret Key is obtained, put them into “config.inc.php” listed in the root directory in this PHP library. And you can copy “config-sample.ic.php” as reference.
The next step is to create a PHP file as following (I call it test.php):
// Instantiate the class $ec2 = new AmazonEC2(); $response = $ec2->stop_instances('i-1f549375'); // Success? var_dump($response->isOK());
In Linux server, make sure this file (test.php) is executable. Simply run “php test.php”.
And you can check with var_dump result. And then go to Amazon Server EC2 panel to see it stopping. Thus we can setup other Linux server using PHP and Cron job to turn on / off specific Amazon Server Instance.
Another idea is to set up some chain action to trigger the final PHP script to turn off the instance where server is installed within. YES, we can turn off server instance from within by PHP script when it is successfully triggered. It can be done in Linux by using Cron job or it can be done in Windows server by scheduled batch file.
So right now, we can host the simple script in a Tier 1 free instance in Amazon to schedule the action to turn on other server instances; and let other server instances turn off by script inside.
- AWS SDK documentation: http://docs.aws.amazon.com/AWSSDKforPHP/latest/
- New version of PHP SDK: https://github.com/aws/aws-sdk-php
Hope this helps you with more money saving plan when using Amazon server.
Cheers and Happy Web Development.