Scheduling EC2 Instances using Lambda and CloudWatch Events

Over the past couple of months, MyBuilder has been transitioning from primarily a dedicated server stack (with orchestration through Puppet) to cloud infrastructure by way of Amazon Web Services. We have been a proponent of AWS for quite some time, taking advantage of services such as S3 and CloudFront in our current setup. We are also not unfamiliar with EC2, spreading some of our application requirements onto several instances over the past couple of years. However, we have not been fully embracing the ‘Cloud nature’ of the product and are still treating each server as something between a Snowflake and a Phoenix.

As the team and business needs expand, we felt this was an opportune time to embrace more of its offerings. I’ve recently discussed the reasoning behind this thought process on a podcast I co-host. Throughout this transition period, I wish to document our experiences moving solely over to the platform, sprinkling in a little Lambda along the way.

Starting and Stopping Instances

One of the key advantages of the Infrastructure as a Service (IaaS) movement is the ability to provision resources as and when you require them. A good use case for this added functionality is the ability to start and stop development resources based on typical workweek patterns, providing additional cost savings. In the video below, I highlight how you can start and stop EC2 instances in a scheduled (Cron-like) manner using Lambda, Node.js, and CloudWatch Events.

The associated code used in this video can be found here.

Scaling Instances

I would now like to expand upon this example by taking advantage of another IaaS benefit - scaling a given resource based on your current demands. In a similar manner to the first demonstration, I will now explain how you can scale an EC2 instance up and down based on a given schedule.

The associated code used in this video can be found here.

I hope these two short videos have highlighted some of the power that can be gained from using Function as a Service (FaaS) platforms such as Lambda in a server-management setting. Both use cases would not have been possible in our previous dedicated server setup and give a small glimpse into the world of automating cloud-based server resources.