Saturday, August 31, 2019

How to restart AWS Elastic BeanStalk instances on a schedule

We wanted to restart all AWS Elastic BeanStalk instances at a given time during the day, every day. To perform this task, there are many solutions. Some of them involve, setting up a lambda function and writing some code etc, what we wanted was something quick and not a maintenance nightmare.

Hence, I thought, all we need to do is re-start the instance on a schedule, whats the best way to do it? Cron jobs flashed as a possible answer!

The Problem

The environment we were talking about was an Elastic BeanStalk Auto-Scaling environment, which meant that EC2 instances will be added and removed on demand.

If we were going to use cron jobs, we needed to make sure that whatever instances are currently in service, they all honour the cron job at all times. This means, new instances that get added on demand, in service should automatically have the cron jobs setup on them too!

The Solution

To do this in the easiest possible way, we ended up using the Advanced Environment Customization with Configuration Files (.ebextensions). AWS Elastic BeanStalk has a feature where we could provide configuration files bundled with our web application source code. These files are basically configuration files under the directory named ".ebextensions".

Now, to setup the cron job reliably on Elastic BeanStalk instances, all we needed to do was to add the "cron-linux.config" file under the ".ebextensions" directory and bundle it with the application source code which gets deployed to the environment.

The folder structure would look like this

The cron-linux.config will be YAML file. Here are sample contents of the cron-linux.config file, this setup re-starts the Elastic BeanStalk instance every day at 0530 hrs.

Thats about it, deploying this along with you source bundle on the environment ensures that the environment instances are restarted every day at 0530 hrs without fail!
Have some Fun!