This quick post is an update to the previous post “Automatically Start and Stop Amazon Instance Programmatically“.
There are two cases to handle Amazon Server instance: start instance (server) and stop instance.
Actually, in order to stop instance, one way is to use AWS SDK to control server instance remotely from other other server or run the PHP script by AWS SDK locally within the server instance itself. However, there is another quick and dirty way to just use batch file in Windows server or Linux command line to turn off server itself, which stops instance in Amazon.
The easy batch file can be just one line of batch command as following:
“shutdown /t 0 /s /f”. The flag /t is used to set seconds count down to wait for other processes to end; the /s is used to issue command to shut down server completely; /f is used to do the action by force.
So above command is used to shut down server by force entirely without any second spent waiting any process to finish.
The batch file can be triggered by other task if all tasks are done in Windows server.
If using Linux server, just edit cron job to fire ssh command “
/sbin/shutdown -r now“.
For starting up Amazon server remotely, we can still use AWS SDK. I will use two pieces of PHP script to do so.
<?php // Instantiate the class $ec2 = new AmazonEC2(); $response = $ec2->stop_instances('i-1f549375'); // Success? var_dump($response->isOK()); ?>
Second script is to associate elastic IP address with running server instance. There will be about 1 minute period for server instance running from pending to initialing stage. So run the second script after about 1 minute to associate elastic IP address specified in Amazon EC2 panel.
<?php // Instantiate the class $ec2 = new AmazonEC2(); $response = $ec2->associate_address('i-1f549375', '22.214.171.124'); // Success? var_dump($response->isOK()); ?>
Make sure you have config.inc.php configured with AWS web access / secret key generated from your amazon account. And above code is using version 1 of AWS SDK for PHP. The resource can be found below:
In summary, we can stop amazon server from within server instance itself by using Windows batch file or Linux shutdown command with Cron Job. And we can use AWS SDK for PHP to remotely launch Amazon Server instance in PHP script, which can also be triggered by Cron job in Linux or Task Scheduler in Windows.
Cheers and Happy Web Development.