Auto reboot an AWS EC2 instance at midnight

2019-04-11 13:38发布

问题:

I've been looking at solutions where I can automatically reboot an EC2 instance at midnight everynight.

I've had a look at how CloudWatch alarms can reboot an instance based on the metrics it has available, but don't think that is the right path.

The reason I'm looking to do so is that because over time a certain process I have running on the instance fails to respond correctly and the process seems to respond correctly on an instance reboot.

At the moment I am manually logging in and rebooting the instance but if there was a way to remove my 'human input which could be subject to forgetting on certain days', that would be really helpful.

Any advice would be much appreciated.

回答1:

I would suggest before doing this maybe looking into setting up a crontab on that box for restarting that specific process, as that would be less disruptive to your environment than rebooting the whole instance.

Still, if you've deemed that this would be better for you in the short term, then CloudWatch Events would be a good solution for you. CloudWatch Events are different from the CloudWatch Alerts that you've been looking at thus far, where CW Events allows you to fire events on a wide scope of event patterns defined by actions occurring within AWS services, or arbitrary scheduling patterns.

You can set up a scheduled event to fire at midnight every night (by defining a cron expression), configured with a target that will call EC2 RebootInstances API for a given instance id.

Example configuration from the AWS Console:

Further Reading

  • AWS Documentation - Schedule Expressions for Rules
  • AWS Documentation - Creating a CloudWatch Events Rule That Triggers on a Schedule