Ref: https://learn.cantrill.io/courses/1820301/lectures/41301397
Protect an EC2 Instance if it gets Stopped
- Create a Lambda function that restarts an instance if it ever gets into the stopped state:
- Protect EC2 instance Python script
- Create a pattern matching rule in EventBridge
- Event to be tracked:
EC2 Instance State-change Notification
- Recommended to generate a JSON sample of the event, to see what info is being delivered
- Fill out the event pattern to match EC2 instance moving to
Stopped
state:
- Screenshot
- Optionally: specify instance ID(s) that it should apply to → in the DEMO it is specified to only have the rule for one of the two instances
- Specify the Lambda function that protects EC2 instances as target for the EventBridge rule:
- Test the rule by stopping an instance. After it is stopped, the instance should move back to
Running
state automatically after a while
- Logs from executed Lambda functions can be found in CWLogs → every Lambda function is a log group, and within it every execution is a log stream
Stop all EC2 Instances at a Specific Time Every Day
- Create a schedule rule in EventBridge
- With the new EventBridge Scheduler you have a more sophisticated UI and can specify schedules in multiple ways, even outside of event buses. With the traditional “Create Rule”, you could only specify the schedule in Unix CRON format, and the time HAD to be in UTC!
- Specify the schedule with a Unix CRON expression:
- ‼️ Careful with time zone! CRON is by default UTC, but the UI with EventBridge Scheduler might adapt it to your current time zone! Always check the “next triggers” to be sure configuration is correct!
- Select the Lambda function that stops instances as the target for this rule
- Wait for the specified time and observe how the instances are stopped. If the protection rule is still in place, the protected instances will then start running again after being stopped