AWS EC2 instances start/stop automation with Cloudwatch and System Manager Automation

Our development team got bigger and we got more and more EC2 instances for each dev team. But, they are not in use after office hours. In order to save cost, we make a plan to stop and start at certain time.

There are quite a lot of ways to automate EC2 instances to start and stop. For our case, I choose Cloudwatch to trigger AWS System Manager Automation.

Let’s say you got A/B/C/D/E instances. On each server, create a role and attach AmazonEC2RoleforSSM policy or add that policy to the existing role. So, the System Manager will be able to retrieve the list of EC2 instances. Let’s recap the following list of things that we do

  • Create EC2 instances
  • Create a role with AmazonEC2RoleforSSM policy attached
  • Install system manager agent on EC2 instances
  • Wait to appear on AWS Systems Manager Fleet Manager

Now, it’s ready to set a cron job on Cloudwatch. Go to cloudwatch Rules and create a rule. There are two types of rules Event Pattern and schedule. I choose to schedule and Cron expression. On the right side, I choose the Targets as SSM Automation. And then, we need to choose Document. Choose, AWS-StopEC2Instance. Next step, we choose “Configure automation parameter(s)” and pass instance id. In our case, A/B/C/D/E instance ids.

For AutomationAssumeRole, go to IAM and create a new role to Allows SSM to call AWS services on your behalf (Like the following). Choose AmazonSSMAutomationRule as policy. When you finish creating the IAM role, copy Role ARN and paste it on AutomationAssumeRole.

As for the cron expression, I choose 0 14 ? * MON-FRI * which means 10 pm (Mon to Fri) Singapore time. And click on Configure detail and save.

That’s for the shutdown. You can check it’s working or not on AWS System Manager > Automation. For the beginning, I won’t set to 10 pm Mon to Fri. I would set to run every minutes by setting 0/1 * * * ? * on cron.

If you plan to start, same as the above process. You create a cron and choose AWS-StartEC2Instance instead of AWS-StopEC2Instance.

I hope, this is helpful. Comments and ask if you have questions. Will help answers as much as I can!

Leave a Reply