Friday, September 5, 2014

AWS - Auto schedule EC2 instance to start/stop

In order to reduce costs of running test and dev EC2 instances at Amazon I've created a simple script that will run and start or stop an instance based on a schedule.  This script is a PowerShell script that relies on the AWS modules to be installed  ("Import-Module AWSPowerShell")  Refer to the link to Configure PowerShell for AWS  (FYI - configure your default profile using AWS access keys as required)

The script is looking for a tag, 'RunningSchedule' and parsing the value that is set within, which is in a format similar to a cron like style using 24 hour clock : H:H:D or H:H:D-D  (I didn’t include a minutes field)

First 'H' = Start time Hour
Second 'H'  =  Stop time Hour
'D' is for day(s) to run, 1 = Monday, 2=Tues, etc.    So if you want it to run Mon-Fri, enter 1-5
To disable the schedule completely, use ‘Disabled’ for the value.

Example, to have the server start at 8am, stop at 5pm, and run Mon-Fri use:   8:17:1-5
To have the server run from 10am to 3pm on Wed use: 10:15:3

The script will then either start or stop the server based on the schedule.
It will then send an email with the servers listed that were either started or stopped.

To schedule the script itself, I configured a scheduled task in Windows on a server.  Simply run a program "Powershell", path is  'C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe'
Include the optional arguments for the path to your script:  'C:\Scripts\AWS-schedule-start-stop-instances.ps1'


Here is the script: