“Running everywhere at such a speed
‘Till they find there is no need (There’s no need)”
from The Beatles song “I’m Only Sleeping”, “Revolver”, 1966
Amazon AWS instance may become very expensive when running 24/7. Our solution? An automatic shutdown when there is no need to have that server online. This recipe is simple when implemented with AWS’s functionality added not so long ago which was called CloudWatch monitoring. Before CloudWatch we used a clumsy Task Scheduler “inside” job (in case of a Windows server): a periodic shutdown command configured with “Run only when computer is idle” setting. That job was not always working as we intended.
Now scheduling an automatic instance shutdown from the EC2 web console is fairly easy:
- Select the targeted instance from the instance list and click on Monitoring tab.
- Click on Create Alarm button.
- Enable Take Action, choosing Stop this instance option for the action.
- We recommend following Alarm conditions, that worked for us in most cases:
Whenever Maximum of CPU Utilization is <= 1.24 Percent
For at least: 6 consecutive period(s) of 15 minutes
- Useful, but optional add-on: you should name this alarm something like:
awsec2-i-4f65f3d0-Low-CPU-NameOfTheServer This way, if you enable optional email notification as well, you would get notified with a meaningful message letting you know which server was shutdown automatically.
- When activated properly this alarm would gracefully shut down your instance exactly after one and half hour of CPU idling.
Besides idle CPU conditional stop, you may configure an automatic startup and shutdown by a schedule, too. For instance, if a bigger (meaning expensive) server is used during the daytime and not overnight, you may have following simple commands scheduled in your crontab on a smaller (inexpensive) Linux instance:
0 9 * * 1-5 /usr/bin/aws ec2 start-instances --instance-ids i-abcd1234 30 17 * * 1-5 /usr/bin/aws ec2 stop-instances --instance-ids i-abcd1234
That would start up the server at 9am, shut it down at 5:30pm, both rules applied on weekdays only.
Note: you may need to setup aws tool before it can be used on your Linux server. For that please follow our instruction from this previous recipe.